/// <summary> /// 作者登录 /// </summary> /// <param name="loginAuthor"></param> /// <returns></returns> public AuthorInfoEntity AuthorLogin(AuthorInfoQuery queryAuthor) { HttpClientHelper clientHelper = new HttpClientHelper(); AuthorInfoEntity authorEntity = clientHelper.PostAuth<AuthorInfoEntity, AuthorInfoQuery>(GetAPIUrl(APIConstant.AUTHORLOGIN), queryAuthor); if (authorEntity != null) { if (authorEntity.Pwd == WKT.Common.Security.MD5Handle.Encrypt(queryAuthor.Pwd)) { # region 设置该用户的角色列表 RoleAuthorQuery roleAuthorQuery = new RoleAuthorQuery(); roleAuthorQuery.JournalID = queryAuthor.JournalID; roleAuthorQuery.AuthorID = authorEntity.AuthorID; IList<RoleAuthorEntity> roleAuthorList = clientHelper.PostAuth<IList<RoleAuthorEntity>, RoleAuthorQuery>(GetAPIUrl(APIConstant.AUTHORGETROLELIST), roleAuthorQuery); if (roleAuthorList != null && roleAuthorList.Count > 0) { authorEntity.RoleIDList = roleAuthorList.Select(p => p.RoleID).ToList<long>(); authorEntity.RoleID = authorEntity.RoleIDList[0]; } # endregion if (authorEntity.RoleIDList == null) { authorEntity.RoleIDList = new List<long> { -1}; } return authorEntity; } else { return null; } }
/// <summary> /// 处理在入款时改变稿件状态 /// </summary> /// <param name="auditBillEntity"></param> /// <returns></returns> public ExecResult DealFinaceInAccount(CirculationEntity cirEntity) { HttpClientHelper clientHelper = new HttpClientHelper(); ExecResult result = clientHelper.PostAuth<ExecResult, CirculationEntity>(GetAPIUrl(APIConstant.DealFinaceInAccount), cirEntity); return result; }
public bool Delete(int addressId, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<bool>(svc.Delete(Constants.BlogRestUrl, string.Format("address/{0}", addressId), authenticationToken)); return result; } }
public static ISpider Get() { ISettings settings = SettingsFactory.Get(); ILogger logger = LoggerFactory.Get(); IHttpClientHelper httpClientHelper = new HttpClientHelper(settings); return new Spider(settings, logger, httpClientHelper); }
public Address Update(Address address, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<Address>(svc.Put(Constants.BlogRestUrl, "address", address, authenticationToken)); return result; } }
public Album Update(Album album, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<Album>(svc.Put(Constants.BlogRestUrl, "album", album, authenticationToken)); return result; } }
public Album GetUserDefaultGroup(int userId, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<Album>(svc.Get(Constants.BlogRestUrl, string.Format("users/{0}/albums/default", userId), authenticationToken)); return result; } }
public Album Get(int id) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<Album>(svc.Get(Constants.BlogRestUrl, string.Format("album/{0}", id))); return result; } }
public Address GetByUser(int userId) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<Address>(svc.Get(Constants.BlogRestUrl, string.Format("users/{0}/address", userId))); return result; } }
/// <summary> /// 获取一个实体对象 /// </summary> /// <param name="mapID"></param> /// <returns></returns> public RoleAuthorEntity GetRoleAuthor(long mapID) { HttpClientHelper clientHelper = new HttpClientHelper(); RoleAuthorQuery roleAuthorQuery = new RoleAuthorQuery(); roleAuthorQuery.MapID = mapID; RoleAuthorEntity roleAuthorEntity = clientHelper.PostAuth<RoleAuthorEntity, RoleAuthorQuery>(GetAPIUrl(APIConstant.GETROLEAUTHORLIST), roleAuthorQuery); return roleAuthorEntity; }
/// <summary> /// 从存储媒介中删除对象 /// </summary> /// <param name="mapID"></param> /// <returns></returns> public ExecResult DeleteRoleAuthor(long mapID) { HttpClientHelper clientHelper = new HttpClientHelper(); RoleAuthorEntity roleAuthor = new RoleAuthorEntity(); roleAuthor.MapID = mapID; ExecResult execResult = clientHelper.PostAuth<ExecResult, RoleAuthorEntity>(GetAPIUrl(APIConstant.DELETEROLEAUTHOR), roleAuthor); return execResult; }
public User Update(User user, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<User>( svc.Put(Constants.BlogRestUrl, "users", user, authenticationToken)); return result; } }
public ChatMessagesList GetChatMessagesListByUsername(string username, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<ChatMessagesList>( svc.Get(Constants.BlogRestUrl, string.Format("user/{0}/chats", username), authenticationToken)); return result; } }
public User GetByUserName(string username) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<User>( svc.Get(Constants.BlogRestUrl, string.Format("users/{0}", username))); return result; } }
public List<ChatMessage> GetMoreChatMessagesByUsernames(string fromUsername, string toUsername, string authenticationToken, int skip = 25) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<List<ChatMessage>>( svc.Get(Constants.BlogRestUrl, string.Format("chat/{0}/{1}/more/{2}", fromUsername, toUsername, skip), authenticationToken)); return result; } }
public ChatMessage AddChatMessage(ChatMessage chatMessage, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<ChatMessage>( svc.Post(Constants.BlogRestUrl, "album", chatMessage, authenticationToken)); return result; } }
public void ShouldThrowExceptionWhenHttpClientFromGetResponseIsNull() { var fakeResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = null }; var fakeHandler = new FakeHttpMessageHandler(fakeResponse); var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") }; var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient }; Assert.Throws<BlogException>(() => httpClientHelper.Get("http://localhost/", "foo")); }
public List<ChatMessage> GetChatMessagesByUserIds(int fromUserId, int toUserId, string authenticationToken) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<List<ChatMessage>>( svc.Get(Constants.BlogRestUrl, string.Format("chat/{0}/{1}", fromUserId, toUserId), authenticationToken)); return result; } }
public List<CommentLike> Get(int commentId) { using (var svc = new HttpClientHelper()) { var result = JsonHelper.DeserializeJson<List<CommentLike>>( svc.Get(Constants.BlogRestUrl, string.Format("comments/{0}/likes", commentId))); return result; } }
public void Add(int commentId, string username, string authenticationToken) { using (var svc = new HttpClientHelper()) { var commentLikeDummy = new CommentLike(); svc.Post(Constants.BlogRestUrl, string.Format("comments/likes?commentId={0}&username={1}", commentId, username), commentLikeDummy, authenticationToken); } }
public static Zap Create() { var settings = new Settings(); var logger = new CommandLineLogger(); var httpClientHelper = new HttpClientHelper(settings); var scanner = new Scanner(settings, logger, httpClientHelper); var reporting = new Reporting(settings,logger,httpClientHelper); var spider = new Spider(settings, logger, httpClientHelper); return new Zap( settings, logger, scanner, reporting, spider); }
public void ShouldHaveAuthenticationHeaderOnHttpGet() { var fakeResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("{ Test: Message }") }; var fakeHandler = new FakeHttpMessageHandler(fakeResponse); var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") }; var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient }; httpClientHelper.HttpGet("http://localhost/", "foo", "bar"); Assert.AreEqual(httpClientHelper.AuthenticationToken, "bar"); }
public void ShouldReturnStringOnHttpGet() { var fakeResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent("{ Test: Message }") }; var fakeHandler = new FakeHttpMessageHandler(fakeResponse); var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") }; var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient }; var result = httpClientHelper.HttpGet("http://localhost/", "foo"); Assert.AreEqual(fakeResponse, result); }
/// <summary> /// 批量保存缴费通知数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public ExecResult BatchSavePayNotice(IList<PayNoticeEntity> list) { ExecResult result = new ExecResult(); if (list != null && list.Count > 0) { HttpClientHelper clientHelper = new HttpClientHelper(); result = clientHelper.Post<ExecResult, IList<PayNoticeEntity>>(GetAPIUrl(APIConstant.PAYNOTICE_BATCHSAVE), list); if (result.result == EnumJsonResult.success.ToString()) { int index = 0; string returnData = string.Empty; foreach (var model in list) { SiteConfigFacadeAPIService service = new SiteConfigFacadeAPIService(); MessageRecodeEntity logModel = new MessageRecodeEntity(); logModel.MsgType = 1; logModel.JournalID = model.JournalID; logModel.SendUser = model.SendUser; logModel.MsgTitle = model.Title; logModel.MsgContent = model.Body; logModel.CID = model.CID; if (model.PayType == 1) logModel.SendType = -3; else if (model.PayType == 2) logModel.SendType = -4; IList<Int64> userList = new List<Int64>() { model.AuthorID }; var emailResult = service.SendEmailOrSms(userList, logModel); index++; returnData = emailResult.msg; if (model.IsSms && !string.IsNullOrWhiteSpace(model.SmsContent)) { logModel.MsgType = 2; logModel.MsgContent = model.SmsContent; var smsResult = service.SendEmailOrSms(userList, logModel); result.msg += smsResult.msg; } } result.msg += returnData + "共计通知 " + index + " 人"; } } return result; }
/// <summary> /// 得到投稿自动分配设置 /// </summary> /// <param name="query"></param> /// <returns></returns> public EditorAutoAllotEntity GetAllowAllotInfo(EditorAutoAllotQuery query) { HttpClientHelper clientHelper = new HttpClientHelper(); EditorAutoAllotEntity cSetResult = clientHelper.PostAuth<EditorAutoAllotEntity, EditorAutoAllotQuery>(GetAPIUrl(APIConstant.CONTRIBUTION_GETAUTOALLOTINFO), query); if (cSetResult.SubjectAuthorMap != null && cSetResult.SubjectAuthorMap.Count > 0) { foreach (SubjectAuthorMapEntity item in cSetResult.SubjectAuthorMap) { item.AuthorName = GetMemberName(item.AuthorID); } } else { cSetResult.SubjectAuthorMap = new List<SubjectAuthorMapEntity>(0); } cSetResult.AuthorName = GetMemberName(cSetResult.AuthorID); cSetResult.OddAuthorName = GetMemberName(cSetResult.OddAuthorID); return cSetResult; }
/// <summary> /// 获取所有列表 /// </summary> /// <param name="query"></param> /// <returns></returns> public IList<MenuEntity> GetAllMenuList(MenuQuery query) { HttpClientHelper clientHelper = new HttpClientHelper(); IList<MenuEntity> listAllMenu = clientHelper.Post<IList<MenuEntity>,MenuQuery>(GetAPIUrl(APIConstant.SYSGETSYSMENUAJAX), query); IList<MenuEntity> listResult = new List<MenuEntity>(); if (listAllMenu != null) { IList<MenuEntity> listRoot = listAllMenu.Where(item => item.PMenuID == 0).ToList<MenuEntity>(); foreach (MenuEntity item in listRoot) { item.MenuUrl = SiteConfig.RootPath + item.MenuUrl; item.IconUrl = SiteConfig.RootPath + item.IconUrl; IList<MenuEntity> listChild = listAllMenu.Where(p => p.PMenuID == item.MenuID).ToList<MenuEntity>(); if (listChild != null) { // 二级 foreach (MenuEntity itemChild in listChild) { itemChild.MenuUrl = SiteConfig.RootPath + itemChild.MenuUrl; itemChild.IconUrl = SiteConfig.RootPath + itemChild.IconUrl; item.children.Add(itemChild); // 三级 IList<MenuEntity> lastListChild = listAllMenu.Where(p => p.PMenuID == itemChild.MenuID).ToList<MenuEntity>(); foreach (MenuEntity lastChild in lastListChild) { lastChild.MenuUrl = SiteConfig.RootPath + lastChild.MenuUrl; lastChild.IconUrl = SiteConfig.RootPath + lastChild.IconUrl; itemChild.children.Add(lastChild); } } } listResult.Add(item); } } return listResult; }
/// <summary> /// 删除角色 /// </summary> /// <param name="queryRole"></param> /// <returns></returns> public ExecResult DelRole(RoleInfoQuery queryRole) { HttpClientHelper clientHelper = new HttpClientHelper(); ExecResult execResult = clientHelper.PostAuth<ExecResult, RoleInfoQuery>(GetAPIUrl(APIConstant.SYSDELROLEINFO), queryRole); return execResult; }
/// <summary> /// 批量删除 /// </summary> /// <param name="rightrequest"></param> /// <returns></returns> public BasicResponse DeleteRights(RightsDeleteRequest rightrequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/Right/DeleteRights?token=" + Token, JSONHelper.ToJSONString(rightrequest)); return(JSONHelper.ParseJSONString <BasicResponse>(responseStr)); }
public BasicResponse <List <RightInfo> > GetRightList() { var responseStr = HttpClientHelper.Post(Webapi + "/v1/Right/GetAllList?token=" + Token, string.Empty); return(JSONHelper.ParseJSONString <BasicResponse <List <RightInfo> > >(responseStr)); }
public BasicResponse <List <R_PhistoryInfo> > GetPersonR_PhistoryByTimer(Sys.Safety.Request.R_Phistory.R_PhistoryGetLastByTimerRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/R_Phistory/GetPersonR_PhistoryByTimer?token=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <BasicResponse <List <R_PhistoryInfo> > >(responseStr)); }
/// <summary> /// 注册TenPayV3Info信息 /// </summary> /// <param name="tenPayV3Info"></param> /// <param name="name">公众号唯一标识(或名称)</param> public static void Register(TenPayV3Info tenPayV3Info, string name) { var key = GetKey(tenPayV3Info.MchId, tenPayV3Info.Sub_MchId); Data[key] = tenPayV3Info; //添加到全局变量 if (!name.IsNullOrEmpty()) { Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_AppId = tenPayV3Info.AppId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_AppSecret = tenPayV3Info.AppSecret; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_MchId = tenPayV3Info.MchId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_Key = tenPayV3Info.Key; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_CertPath = tenPayV3Info.CertPath; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_CertSecret = tenPayV3Info.CertSecret; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_TenpayNotify = tenPayV3Info.TenPayV3Notify; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_WxOpenTenpayNotify = tenPayV3Info.TenPayV3_WxOpenNotify; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_SubMchId = tenPayV3Info.Sub_MchId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_SubAppId = tenPayV3Info.Sub_AppId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_SubAppSecret = tenPayV3Info.Sub_AppSecret; } //进行证书注册 #if NETSTANDARD2_0 try { var service = SenparcDI.GlobalServiceCollection; var certName = key; var certPassword = tenPayV3Info.CertSecret; var certPath = tenPayV3Info.CertPath; //添加注册 //service.AddSenparcHttpClientWithCertificate(certName, certPassword, certPath, false); #region 测试添加证书 //添加注册 if (!string.IsNullOrEmpty(certPath)) { if (File.Exists(certPath)) { try { var cert = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); var checkValidationResult = false; var serviceCollection = SenparcDI.GlobalServiceCollection; //serviceCollection.AddHttpClient<SenparcHttpClient>(certName) serviceCollection.AddHttpClient(certName) .ConfigurePrimaryHttpMessageHandler(() => { var httpClientHandler = HttpClientHelper.GetHttpClientHandler(null, RequestUtility.SenparcHttpClientWebProxy, System.Net.DecompressionMethods.None); httpClientHandler.ClientCertificates.Add(cert); if (checkValidationResult) { httpClientHandler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(RequestUtility.CheckValidationResult); } return(httpClientHandler); }); } catch (Exception ex) { Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog($"添加微信支付证书发生异常", $"certName:{certName},certPath:{certPath}"); Senparc.CO2NET.Trace.SenparcTrace.BaseExceptionLog(ex); } } else { Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog($"已设置微信支付证书,但无法找到文件", $"certName:{certName},certPath:{certPath}"); } } #endregion } catch (Exception ex) { throw; } finally { SenparcDI.ResetGlobalIServiceProvider(); } #endif }
public BasicResponse <List <JC_AlarmNotificationPersonnelConfigInfo> > GetAlarmNotificationPersonnelListByAnalysisModeName(AlarmNotificationPersonnelConfigGetListRequest getListByAnalysisModelIdRequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnelConfig/GetAlarmNotificationPersonnelListByAnalysisModeName?token=" + Token, JSONHelper.ToJSONString(getListByAnalysisModelIdRequest)); return(JSONHelper.ParseJSONString <BasicResponse <List <JC_AlarmNotificationPersonnelConfigInfo> > >(responseStr)); }
/// <summary> /// 刷新 /// </summary> /// <param name="request"></param> /// <returns></returns> public RefreshResponse Refresh(RefreshRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/refresh.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <RefreshResponse>(responseStr)); }
/// <summary> /// Get All Log By Specific Date. /// </summary> /// <param name="httpClient"> /// reference http client object. /// </param> /// <param name="dateTime"> /// Target Date /// </param> /// <param name="controllerUrls"> /// AuditLog, DebugLog, ErrorLog. /// </param> /// <param name="accessToken"> /// Access token used for authentication. /// </param> /// <param name="mediaType"> /// MIME Type are you going to post/get. => application/json (mostly...) /// </param> /// <param name="urls"> /// Target URL => https://www.darwin.com/ /// </param> /// <returns> /// Http Response. /// </returns> public static async Task <HttpResponseMessage> GetListLoggingByDateAsync(this HttpClient httpClient, DateTime dateTime, string controllerUrls, string accessToken, string mediaType) { httpClient = HttpClientHelper.SettingHttpClient(ref httpClient, Urls.LoggingServer_URL, mediaType, accessToken); return(await httpClient.GetAsync(controllerUrls + "/search/" + dateTime.ToString("dd-MM-yyyy"))); }
/// <summary> /// Delete All Log /// </summary> /// <param name="httpClient"> /// reference http client object. /// </param> /// <param name="controllerUrls"> /// AuditLog, DebugLog, ErrorLog. /// </param> /// <param name="accessToken"> /// Access token used for authentication. /// </param> /// <param name="mediaType"> /// MIME Type are you going to post/get. => application/json (mostly...) /// </param> /// <param name="urls"> /// Target URL => https://www.darwin.com/ /// </param> /// <returns> /// Http Response. /// </returns> public static async Task <HttpResponseMessage> DeleteLoggingAllAsync(this HttpClient httpClient, string controllerUrls, string accessToken, string mediaType) { httpClient = HttpClientHelper.SettingHttpClient(ref httpClient, Urls.LoggingServer_URL, mediaType, accessToken); return(await httpClient.DeleteAsync(controllerUrls)); }
/// <summary> /// 结束广播任务 /// </summary> /// <param name="request"></param> /// <returns></returns> public EndPaTaskResponse endPaTask(EndPaTaskRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/endPaTask.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <EndPaTaskResponse>(responseStr)); }
public WalletControllerTests(WebApiTestFactory factory) : base(factory) { _httpClientHelper = new HttpClientHelper(Client); }
/// <summary> /// 修改分区 /// </summary> /// <param name="request"></param> /// <returns></returns> public PartitionControlResponse setZone(PartitionControlRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/setZone.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <PartitionControlResponse>(responseStr)); }
/// <summary> /// 查询终端 /// </summary> /// <param name="request"></param> /// <returns></returns> public TerminalQueryResponse queryTerm(TerminalQueryRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/queryTerm.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <TerminalQueryResponse>(responseStr)); }
/// <summary> /// Get Single Log By Id /// </summary> /// <param name="httpClient"> /// reference http client object. /// </param> /// <param name="Id"> /// GUID Logging. /// </param> /// <param name="controllerUrls"> /// AuditLog, DebugLog, ErrorLog. /// </param> /// <param name="accessToken"> /// Access token used for authentication. /// </param> /// <param name="mediaType"> /// MIME Type are you going to post/get. => application/json (mostly...) /// </param> /// <param name="urls"> /// Target URL => https://www.darwin.com/ /// </param> /// <returns> /// Http Response. /// </returns> public static async Task <HttpResponseMessage> GetLoggingByIdAsync(this HttpClient httpClient, string Id, string controllerUrls, string accessToken, string mediaType) { httpClient = HttpClientHelper.SettingHttpClient(ref httpClient, Urls.LoggingServer_URL, mediaType, accessToken); return(await httpClient.GetAsync(controllerUrls + "/" + Id)); }
public async Task<bool> ProcessInprocessQueue() { if (!InprocessQueue.IsEmpty) { string fileName; while (InprocessQueue.TryDequeue(out fileName)) { byte[] buffer = new byte[1024]; using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, true)) { int bytesRead = 0; long totalBytes = 0; do { // Asynchronously read from the file stream. bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length); totalBytes += bytesRead; } while (bytesRead > 0); fileStream.Seek(0, SeekOrigin.Begin); var httpClientHelper = new HttpClientHelper(); string correlationId = Settings.UseFileNameAsExternalCorrelationId ? Path.GetFileName(fileName) : null; Uri enqueueUri = httpClientHelper.GetEnqueueUri(); Console.WriteLine("Sending request - " + enqueueUri + " - for file " + Path.GetFileName(fileName) + ". Request size - " + totalBytes + " bytes."); var response = await httpClientHelper.SendPostRequestAsync(enqueueUri, fileStream, correlationId); if (response.IsSuccessStatusCode) { var messageId = await response.Content.ReadAsStringAsync(); await Console.Out.WriteLineAsync("File - " + Path.GetFileName(fileName) + " - enqueued successfully.").ConfigureAwait(false); await Console.Out.WriteLineAsync("Response - " + messageId.ToString()).ConfigureAwait(false); await Task.Run(() => { var successOutput = Path.Combine(Settings.SuccessDir, Path.GetFileName(fileName)); if (File.Exists(successOutput)) { File.Delete(successOutput); } File.Move(fileName, successOutput); Console.Out.WriteLineAsync("File moved to success location."); }); } else { await Console.Out.WriteLineAsync("File - " + Path.GetFileName(fileName) + " - enqueued failed.").ConfigureAwait(false); await Console.Out.WriteLineAsync("Response - Status: " + response.StatusCode + ", Reason: " + response.ReasonPhrase).ConfigureAwait(false); await Task.Run(() => { var failureOutput = Path.Combine(Settings.ErrorDir, Path.GetFileName(fileName)); if (File.Exists(failureOutput)) { File.Delete(failureOutput); } File.Move(fileName, failureOutput); Console.Out.WriteLineAsync("File moved to failure location.").ConfigureAwait(false); }); } } } } return true; }
/// <summary> /// Not Used Widely. Only Within This Class. /// Used For Add New Log Record. /// </summary> /// <param name="httpClient"> /// reference http client object. /// </param> /// <param name="logModel"> /// Object to log /// </param> /// <param name="controllerUrls"> /// AuditLog, DebugLog, ErrorLog. /// </param> /// <returns> /// Http Response. /// </returns> private static async Task <HttpResponseMessage> PostLoggingAsync(this HttpClient httpClient, LogModel logModel, string controllerUrl) { var content = HttpClientHelper.CreateHttpContentJson(logModel); return(await httpClient.PostAsync(controllerUrl, content)); }
public BasicResponse <bool> HasAlarmNotificationForAnalysisModel(GetAlarmNotificationByAnalysisModelIdRequest getByAnalysisModelIdRequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnelConfig/HasAlarmNotificationForAnalysisModel?token=" + Token, JSONHelper.ToJSONString(getByAnalysisModelIdRequest)); return(JSONHelper.ParseJSONString <BasicResponse <bool> >(responseStr)); }
/// <summary> /// Used For Get All URL Configuration. /// </summary> /// <param name="httpClient"> /// reference http client object. /// </param> /// <param name="accessToken"> /// Access token used for authentication. /// </param> /// <param name="mediaType"> /// MIME Type are you going to post/get. => application/json (mostly...) /// </param> /// <param name="urls"> /// Target URL => https://www.darwin.com/ /// </param> /// <returns> /// Http Response. /// </returns> public static async Task <HttpResponseMessage> GetAllURLConfigurationAsync(this HttpClient httpClient, string accessToken, string mediaType) { httpClient = HttpClientHelper.SettingHttpClient(ref httpClient, Urls.ConfigurationServer_URL, mediaType, accessToken); return(await httpClient.GetAsync(Constants.NetStandard.ConfigurationServer.ControllerUrls.URLConfiguration_URL)); }
public BasicResponse <JC_AlarmNotificationPersonnelConfigInfo> UpdateJC_AlarmNotificationPersonnelConfig(AlarmNotificationPersonnelConfigUpdateRequest jC_Alarmnotificationpersonnelconfigrequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnelConfig/UpdateJC_AlarmNotificationPersonnelConfig?token=" + Token, JSONHelper.ToJSONString(jC_Alarmnotificationpersonnelconfigrequest)); return(JSONHelper.ParseJSONString <BasicResponse <JC_AlarmNotificationPersonnelConfigInfo> >(responseStr)); }
/// <summary> /// 启动音乐广播任务 /// </summary> /// <param name="request"></param> /// <returns></returns> public StartPaMusicTaskResponse startPaMusicTask(StartPaMusicTaskRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/startPaMusicTask.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <StartPaMusicTaskResponse>(responseStr)); }
public GetCalendarTests() { client = new HttpClientHelper(new IntegrationFixture().Client); }
/// <summary> /// 删除播放列表音乐 /// </summary> /// <param name="request"></param> /// <returns></returns> public PlayListMusicControlResponse delPlayListMusic(PlayListMusicControlRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/delPlayListMusic.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <PlayListMusicControlResponse>(responseStr)); }
/// <summary> /// 添加一个全新信息到权限表并返回成功后的权限对象(支持添加、更新,根据状态来判断) /// </summary> /// <param name="rightrequest"></param> /// <returns></returns> public BasicResponse <RightInfo> AddRightEx(RightAddRequest rightrequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/Right/AddRightEx?token=" + Token, JSONHelper.ToJSONString(rightrequest)); return(JSONHelper.ParseJSONString <BasicResponse <RightInfo> >(responseStr)); }
/// <summary> /// 监听呼叫 /// </summary> /// <param name="request"></param> /// <returns></returns> public MonitorCallResponse monitorCall(MonitorCallRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/monitorCall.do?accessToken=" + Token, JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <MonitorCallResponse>(responseStr)); }
public BasicResponse <List <RightInfo> > GetRightList(RightGetListRequest rightrequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/Right/GetPageList?token=" + Token, JSONHelper.ToJSONString(rightrequest)); return(JSONHelper.ParseJSONString <BasicResponse <List <RightInfo> > >(responseStr)); }
public async Task <ApiResult> CodeLogin(UserLoginModel1 model) { if (string.IsNullOrEmpty(model.Code)) { return(new ApiResult { status = 0, msg = "微信code不能为空" }); } HttpClient httpClient = new HttpClient(); List <KeyValuePair <string, string> > parmArray = new List <KeyValuePair <string, string> >(); parmArray.Add(new KeyValuePair <string, string>("appid", appid)); parmArray.Add(new KeyValuePair <string, string>("secret", secret)); parmArray.Add(new KeyValuePair <string, string>("js_code", model.Code)); string result = await HttpClientHelper.GetResponseByGetAsync(httpClient, parmArray, "https://api.weixin.qq.com/sns/jscode2session"); if (result.Contains("errcode")) { WeChatErrorResultModel errorModel = JsonConvert.DeserializeObject <WeChatErrorResultModel>(result); return(new ApiResult { status = 0, msg = "微信返回errcode:" + errorModel.errcode + ",errmsg:" + errorModel.errmsg }); } WeChatResultModel rightModel = JsonConvert.DeserializeObject <WeChatResultModel>(result); User user = JwtHelper.JwtDecrypt <User>(ControllerContext); var userDTO = await userService.GetModelAsync(user.Id); if (userDTO == null) { return(new ApiResult { status = 0, msg = "会员不存在" }); } if (string.IsNullOrEmpty(userDTO.ShareCode)) { string getTokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret); string res = await HttpClientHelper.GetResponseByGetAsync(httpClient, getTokenUrl); if (res.Contains(@"errcode\")) { return(new ApiResult { status = 1, data = res }); } GetAccessToken getAccessToken = JsonConvert.DeserializeObject <GetAccessToken>(res); Parm parm = new Parm(); parm.scene = userDTO.Mobile; string getCodeUrl = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", getAccessToken.access_token); var result1 = await HttpClientHelper.GetResponseStringByPostJsonAsync(httpClient, parm, getCodeUrl); string path = ImageHelper.SaveByte(result1); await userService.UpdateShareCodeAsync(user.Id, path); } if (rightModel.OpenId != user.Code.Substring(3, 28)) { return(new ApiResult { status = 0, msg = "登录失败" }); } return(new ApiResult { status = 1, msg = "登录成功" }); }
/// <summary> /// 删除成员 /// </summary> /// <param name="queryRole"></param> /// <returns></returns> public ExecResult DelMember(AuthorInfoQuery authorQuery) { HttpClientHelper clientHelper = new HttpClientHelper(); ExecResult execResult = clientHelper.PostAuth<ExecResult, AuthorInfoQuery>(GetAPIUrl(APIConstant.SYSDELMEMBERINFO), authorQuery); return execResult; }
public async Task <ApiResult> Login(UserLoginModel model) { if (string.IsNullOrEmpty(model.Mobile)) { return(new ApiResult { status = 0, msg = "登录手机号不能为空" }); } if (!Regex.IsMatch(model.Mobile, @"^1\d{10}$")) { return(new ApiResult { status = 0, msg = "登录手机号格式不正确" }); } if (string.IsNullOrEmpty(model.Password)) { return(new ApiResult { status = 0, msg = "密码不能为空" }); } if (string.IsNullOrEmpty(model.Code)) { return(new ApiResult { status = 0, msg = "微信code不能为空" }); } long userId = await userService.CheckLoginAsync(model.Mobile, model.Password); if (userId == -1 || userId == -2) { return(new ApiResult { status = 0, msg = "登录账号或密码错误" }); } if (userId == -3) { return(new ApiResult { status = 0, msg = "会员账号已经被冻结" }); } HttpClient httpClient = new HttpClient(); List <KeyValuePair <string, string> > parmArray = new List <KeyValuePair <string, string> >(); parmArray.Add(new KeyValuePair <string, string>("appid", appid)); parmArray.Add(new KeyValuePair <string, string>("secret", secret)); parmArray.Add(new KeyValuePair <string, string>("js_code", model.Code)); string result = await HttpClientHelper.GetResponseByGetAsync(httpClient, parmArray, "https://api.weixin.qq.com/sns/jscode2session"); if (result.Contains("errcode")) { WeChatErrorResultModel errorModel = JsonConvert.DeserializeObject <WeChatErrorResultModel>(result); return(new ApiResult { status = 0, msg = "微信返回errcode:" + errorModel.errcode + ",errmsg:" + errorModel.errmsg }); } WeChatResultModel rightModel = JsonConvert.DeserializeObject <WeChatResultModel>(result); User setUser = new User(); setUser.Id = userId; if (string.IsNullOrEmpty(rightModel.OpenId)) { setUser.Code = ""; } setUser.Code = CommonHelper.GetCaptcha(3) + rightModel.OpenId + CommonHelper.GetCaptcha(2); log.Debug($"登录中获得的Code:{setUser.Code}"); string token = JwtHelper.JwtEncrypt <User>(setUser); long tokenId = await userTokenService.UpdateAsync(userId, token); var userDTO = await userService.GetModelAsync(userId); if (userDTO == null) { return(new ApiResult { status = 0, msg = "会员不存在" }); } //if (string.IsNullOrEmpty(userDTO.ShareCode)) //{ // string getTokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret); // string res = await HttpClientHelper.GetResponseByGetAsync(httpClient, getTokenUrl); // if (res.Contains(@"errcode\")) // { // return new ApiResult { status = 1, data = res }; // } // GetAccessToken getAccessToken = JsonConvert.DeserializeObject<GetAccessToken>(res); // Parm parm = new Parm(); // parm.scene = userDTO.Mobile; // string getCodeUrl = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", getAccessToken.access_token); // var result1 = await HttpClientHelper.GetResponseStringByPostJsonAsync(httpClient, parm, getCodeUrl); // string path = ImageHelper.SaveByte(result1); // await userService.UpdateShareCodeAsync(userId, path); //} return(new ApiResult { status = 1, msg = "登录成功", data = new { token = token } }); }
/// <summary> /// 编辑成员 /// </summary> /// <param name="queryRole"></param> /// <returns></returns> public ExecResult EditMember(AuthorInfoEntity authorEntity) { HttpClientHelper clientHelper = new HttpClientHelper(); ExecResult execResult = clientHelper.PostAuth<ExecResult, AuthorInfoEntity>(GetAPIUrl(APIConstant.SYSEDITMEMBERINFO), authorEntity); return execResult; }
public BasicResponse <List <JC_AlarmNotificationPersonnelConfigInfo> > AddAlarmNotificationPersonnelConfig(AlarmNotificationPersonnelConfigListAddRequest addRequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnelConfig/AddAlarmNotificationPersonnelConfig?token=" + Token, JSONHelper.ToJSONString(addRequest)); return(JSONHelper.ParseJSONString <BasicResponse <List <JC_AlarmNotificationPersonnelConfigInfo> > >(responseStr)); }
/// <summary> /// Creates an appropriatly configured HttpClient that will be used in communicating with the /// Spring Cloud Configuration Server /// </summary> /// <param name="settings">the settings used in configuring the HttpClient</param> /// <returns>The HttpClient used by the provider</returns> protected static HttpClient GetHttpClient(ConfigServerClientSettings settings) { return(HttpClientHelper.GetHttpClient(settings.ValidateCertificates, settings.Timeout)); }
public BasicResponse <List <JC_AlarmNotificationPersonnelConfigInfo> > GetAlarmNotificationPersonnelConfigAllList(GetAllAlarmNotificationRequest getAllAlarmNotificationRequest) { var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnelConfig/GetAlarmNotificationPersonnelConfigAllList?token=" + Token, JSONHelper.ToJSONString(getAllAlarmNotificationRequest)); return(JSONHelper.ParseJSONString <BasicResponse <List <JC_AlarmNotificationPersonnelConfigInfo> > >(responseStr)); }
/// <summary> /// Processes input queue /// </summary> /// <returns> /// Task object for continuation /// </returns> private async Task ProcessInputQueue() { using (_httpClientHelper = new HttpClientHelper(_settings, _retryPolicyForHttp)) { var fileCount = 0; while (InputQueue.TryDequeue(out DataMessage dataMessage)) { try { if (fileCount > 0 && _settings.Interval > 0) //Only delay after first file and never after last. { System.Threading.Thread.Sleep(_settings.Interval * 1000); } fileCount++; var sourceStream = _retryPolicyForIo.Execute(() => FileOperationsHelper.Read(dataMessage.FullPath, FileShare.None)); if (sourceStream == null) { continue; //Nothing to do here } sourceStream.Seek(0, SeekOrigin.Begin); if (Log.IsDebugEnabled) { Log.DebugFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_Uploading_file_1_File_size_2_bytes, _context.JobDetail.Key, dataMessage.FullPath.Replace(@"{", @"{{").Replace(@"}", @"}}"), sourceStream.Length)); } // Post enqueue file request var response = await _httpClientHelper.PostStreamRequestAsync(_httpClientHelper.GetEnqueueUri(), sourceStream, dataMessage.Name); sourceStream.Close(); sourceStream.Dispose(); if (response.IsSuccessStatusCode) { var messageId = await response.Content.ReadAsStringAsync(); var targetDataMessage = new DataMessage(dataMessage) { MessageId = messageId, FullPath = Path.Combine(_settings.UploadSuccessDir, dataMessage.Name), MessageStatus = MessageStatus.Enqueued }; // Move to inprocess/success location _retryPolicyForIo.Execute(() => FileOperationsHelper.Move(dataMessage.FullPath, targetDataMessage.FullPath)); if (_settings.ProcessingJobPresent) { _retryPolicyForIo.Execute(() => FileOperationsHelper.WriteStatusFile(targetDataMessage, _settings.StatusFileExtension)); } if (Log.IsDebugEnabled) { Log.DebugFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_File_1_uploaded_successfully_Message_Id_2, _context.JobDetail.Key, dataMessage.FullPath.Replace(@"{", @"{{").Replace(@"}", @"}}"), targetDataMessage.MessageId)); } } else { // Enqueue failed. Move message to error location. Log.ErrorFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_Enqueuing_failed_for_file_1_Failure_response_Status_2_Reason_3, _context.JobDetail.Key, dataMessage.FullPath.Replace(@"{", @"{{").Replace(@"}", @"}}"), response.StatusCode, response.ReasonPhrase)); var targetDataMessage = new DataMessage(dataMessage) { FullPath = Path.Combine(_settings.UploadErrorsDir, dataMessage.Name), MessageStatus = MessageStatus.Failed }; // Move data to error location _retryPolicyForIo.Execute(() => FileOperationsHelper.Move(dataMessage.FullPath, targetDataMessage.FullPath)); // Save the log with enqueue failure details _retryPolicyForIo.Execute(() => FileOperationsHelper.WriteStatusLogFile(targetDataMessage, response, _settings.StatusFileExtension)); } } catch (Exception ex) { Log.ErrorFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_Failure_processing_file_1_Exception_2, _context.JobDetail.Key, dataMessage.FullPath.Replace(@"{", @"{{").Replace(@"}", @"}}"), ex.Message), ex); throw; } } } }
/// <summary> /// 登录 /// </summary> /// <param name="request"></param> /// <returns></returns> public LoginResponse Login(LoginRequest request) { var responseStr = HttpClientHelper.Post(Webapi + "/api/REST-API/login.do", JSONHelper.ToJSONString(request)); return(JSONHelper.ParseJSONString <LoginResponse>(responseStr)); }