/// <summary> /// <see cref="IApiConnector.WriteObject"/> /// </summary> public bool WriteObject(Entity obj) { var result = new ServerResult(); var data = obj.GetRequestData(); if (data == null) { Log.Write("Write Failed for " + obj.GetType().Name + ": Unable to get request data", LogSeverity.Error); result.Success = false; result.ErrorMessage = "Unable to get request data"; SetLatestEntityServerResult(obj, result); return(false); } if (!obj.IsNew) { var response = CallServer(obj.RelativeUrl + "/" + obj.Id, data, Method.PUT); return(ExtractResponse(obj, response, result)); } else { var response = CallServer(obj.RelativeUrl, data, Method.POST); var successfull = ExtractResponse(obj, response, result); if (successfull) { //Update id given from server var fromServer = (Entity)JsonConvert.DeserializeObject(response.Content, obj.GetType()); obj.Id = fromServer.Id; } return(successfull); } }
public void smartFolderChildClick() { ServerResult mailboxRes = (ServerResult)formMain.treeView1.SelectedNode.Parent.Parent.Tag; String cvowner = mailboxRes.cvowner; String core = formMain.treeView1.SelectedNode.Parent.Parent.Parent.Text; SolrQuery query = new SolrQuery(formMain.ip, formMain); String jid1 = formMain.treeView1.SelectedNode.Text; XmlDocument doc = query.getJidSmartFolderMessages(core, cvowner, jid1, formMain.start); List <XmlDocument> docs = new List <XmlDocument>(); docs.Add(doc); XMLParser parser = new XMLParser(docs); List <ServerResult> results = parser.results; formMain.currentPage = results; formMain.lastPage = (parser.numFound / formMain.pageSize); formMain.writeMailsInList(formMain.currentPage); if (formMain.listView1.Items.Count == 0) { formMain.nextButton.Visible = false; formMain.previousButton.Visible = false; formMain.customPageBox.Visible = false; formMain.label1.Visible = false; formMain.lastPageButton.Visible = false; } else { formMain.nextButton.Visible = true; formMain.previousButton.Visible = true; formMain.customPageBox.Visible = true; formMain.label1.Visible = true; formMain.lastPageButton.Visible = true; } }
/// <summary> /// 获取当前的连接数量 /// </summary> /// <param name="callback"></param> public async void GetLikeNumber(Action <string, Exception> callback) { await Task.Run(() => { try { ServerResult serverResult = JsonConvert.DeserializeObject <ServerResult>(HttpRequestHelper.HttpGet(string.Concat(GlobalData.BaseServerUrl, "/api/BeePCLauncher/GetLikeNumber"), string.Empty)); if (serverResult.StatusCode != 200) { this._logger.Error(serverResult.Data); } else { string data = serverResult.Data; int num = 1306; if (!int.TryParse(data, out num)) { callback("暂无数据", null); } else { callback(num.ToString(), null); } } } catch (Exception exception1) { Exception exception = exception1; this._logger.Error <Exception>(exception); callback("暂无数据", exception); } }); }
/// <summary> /// 获取指定的图片连接 /// </summary> /// <param name="callback"></param> public async void GetImageLinkData(Action <ImageLinkData, Exception> callback) { await Task.Run(() => { try { ServerResult serverResult = JsonConvert.DeserializeObject <ServerResult>(HttpRequestHelper.HttpGet(string.Concat(GlobalData.BaseServerUrl, "/api/BeePCLauncher/GetBeePCLauncherInfo"), string.Empty)); if (serverResult.StatusCode != 200) { this._logger.Error(serverResult.Data); } else { ImageLinkData imageLinkDatum = JsonConvert.DeserializeObject <ImageLinkData>(serverResult.Data); callback(imageLinkDatum, null); } } catch (Exception exception1) { Exception exception = exception1; this._logger.Error <Exception>(exception); callback(null, exception); } }); }
public static byte[] Execute(byte[] input, string db_path = null) { try { Init(db_path); var result = db._Internal_server_execute(input); return(ServerResultHelper.GetBytes(result)); } catch (Exception ex) { //try //{ // if (!ex.Message.Contains("Linqdb:")) // { // var rg = new Random(); // File.WriteAllText("error_" + rg.Next() + ".txt", ex.Message + " " + ex.StackTrace + (ex.InnerException != null ? (" " + ex.InnerException.Message + " " + ex.InnerException.StackTrace) : "")); // } //} //catch (Exception) { } var cm = new ServerResult() { ServerError = ex.Message + ex.StackTrace }; return(ServerResultHelper.GetBytes(cm)); } }
private async Task reportToApiServer( string message = default(string), string path = default(string), Task postTransferTask = null) { if (message != default(string)) { HttpResponseMessage result = await Tools.post(Tools.API_NOTIFY, new Dictionary <string, string> { { "username", Tizen.Applications.Preference.Get <string>("username") }, { "password", Tizen.Applications.Preference.Get <string>("password") }, { "message", message } }); if (result.IsSuccessStatusCode) { JsonValue resJson = JsonValue.Parse(await result.Content.ReadAsStringAsync()); log($"RESULT: {resJson["result"]}"); Debug.WriteLine(Tools.TAG, $"Message has been submitted to the Server. length={message.Length}"); } else { Toast.DisplayText("Failed to submit a notification to server!"); } } else if (path != null) { HttpResponseMessage result = await Tools.post( Tools.API_SUBMIT_DATA, new Dictionary <string, string> { { "username", Tizen.Applications.Preference.Get <string>("username") }, { "password", Tizen.Applications.Preference.Get <string>("password") } }, File.ReadAllBytes(path) ); if (result == null) { Toast.DisplayText("Please check your WiFi connection first!"); return; } if (result.IsSuccessStatusCode) { JsonValue resJson = JsonValue.Parse(await result.Content.ReadAsStringAsync()); ServerResult resCode = (ServerResult)int.Parse(resJson["result"].ToString()); if (resCode == ServerResult.OK) { postTransferTask?.Start(); } else { log($"Failed to upload {path.Substring(path.LastIndexOf(Path.PathSeparator) + 1)}"); } } else { log($"Failed to upload {path.Substring(path.LastIndexOf(Path.PathSeparator) + 1)}"); } } }
private void LoadDependenciesData() { #region Users list CRUDResult get_user = ApiActions.GET(PreferenceForm.API_MAIN_URL() + "users/get_all"); ServerResult sr_user = JsonConvert.DeserializeObject <ServerResult>(get_user.data); if (sr_user.result == ServerResult.SERVER_RESULT_SUCCESS) { this.list_users = sr_user.users; } #endregion Users list #region Leave reason CRUDResult get_leave_cause = ApiActions.GET(PreferenceForm.API_MAIN_URL() + "istab/get_leave_cause"); ServerResult sr_leave_cause = JsonConvert.DeserializeObject <ServerResult>(get_leave_cause.data); if (sr_leave_cause.result == ServerResult.SERVER_RESULT_SUCCESS) { this.list_reason = sr_leave_cause.istab; } #endregion Leave reason #region Medical Certificate this.list_medcert.Add(new ComboboxItem("N/A (ไม่ระบุ)", 9, "X")); this.list_medcert.Add(new ComboboxItem("ไม่มีใบรับรองแพทย์", 0, "N")); this.list_medcert.Add(new ComboboxItem("มีใบรับรองแพทย์", 1, "Y")); #endregion Medical Certificate #region Status this.list_status.Add(new ComboboxItem("WAIT", (int)CustomDateEvent.EVENT_STATUS.WAIT_FOR_CONFIRM, "WAIT")); this.list_status.Add(new ComboboxItem("CONFIRMED", (int)CustomDateEvent.EVENT_STATUS.CONFIRMED, "CONFIRMED")); this.list_status.Add(new ComboboxItem("CANCELED", (int)CustomDateEvent.EVENT_STATUS.CANCELED, "CANCELED")); #endregion Status }
public async Task <string> CriarUsuario(User user) { try { Client.CancelPendingRequests(); user.Senha = Criptografia.CriptografarMD5(user.Senha); var json = JsonConvert.SerializeObject(user); var content = new StringContent(json, Encoding.UTF8, "application/json"); var uri = $"{this.uri}/usuario"; HttpResponseMessage result = await Client.PostAsync(uri, content); ServerResponse = JsonConvert.DeserializeObject <ServerResult>(result.Content.ReadAsStringAsync().Result); if (result.StatusCode == HttpStatusCode.OK) { return("Usuário criado com sucesso!"); } return(ServerResponse.Mensagem); } catch { throw new Exception(MensagemErro); } }
public ServerResult <User> create(User entity, bool withMsg = true) { ServerResult <User> sr = passCreateGurd(entity); if (!sr.success) { return(sr); } sr = getByUniqueParams(entity, withMsg); if (sr.success) { sr.error.addMessage(HttpError.entityExist, withMsg); sr.fail(); } else { sr.succeed(); sr.result = new User(); sr.result.apiId = entity.apiId; if (sr.result.apiId == null) { sr.result.apiId = Helper.Helper.RandomId(); } sr.result.name = entity.name; sr.result.email = entity.email; sr.result.password = entity.password; sr.error.addInfo(HttpError.getAddIdIntoTable(TabelList.User, sr.result.apiId)); db.Add(sr.result); db.SaveChanges(); } return(sr); }
private void submitChangeMacAddress() { string json_data = "{\"id\": " + this.editing_mac_id.ToString() + ","; json_data += "\"mac_address\":\"" + this.txtMacAddress.Text.cleanString() + "\","; json_data += "\"create_by\":\"" + this.G.loged_in_user_name + "\"}"; CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "macallowed/update", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); if (post.result) { switch (sr.result) { case ServerResult.SERVER_RESULT_SUCCESS: this.DialogResult = DialogResult.OK; this.Close(); break; default: MessageBox.Show(sr.message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } } else { MessageBox.Show(sr.message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnOK_Click(object sender, EventArgs e) { List <Users> list_selected_trainer = (from r in this.dgvSelected.Rows.Cast <DataGridViewRow>() select(Users) r.Tag).ToList <Users>(); StringBuilder trainer_id = new StringBuilder(); int cnt = 0; foreach (Users u in list_selected_trainer) { cnt++; trainer_id.Append((cnt == 1 ? u.id.ToString() : "," + u.id.ToString())); } string json_data = "{\"date\":\"" + this.date_event.Date.ToMysqlDate() + "\","; json_data += "\"trainer_id\":\"" + trainer_id.ToString() + "\","; json_data += "\"rec_by\":\"" + this.date_event.G.loged_in_user_name + "\"}"; Console.WriteLine(" >>> " + json_data); CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "trainingcalendar/change", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { this.DialogResult = DialogResult.OK; this.Close(); } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); } }
private void showEditForm(int mac_id) { CRUDResult get = ApiActions.GET(PreferenceForm.API_MAIN_URL() + "macallowed/get_at&mac_id=" + mac_id.ToString()); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(get.data); if (get.result) { MacAddressEditForm editForm = new MacAddressEditForm(); editForm.G = this.G; int id = sr.macallowed.First <MacAllowed>().id; string mac_address = sr.macallowed.First <MacAllowed>().mac_address; editForm.editing_mac_id = id; editForm.txtMacAddress.Text = mac_address; if (editForm.ShowDialog() == DialogResult.OK) { this.loadMacAddressData(mac_id); } } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); } }
private void workerSave_Dowork(object sender, DoWorkEventArgs e) { string is_greendisc = this.chkGreendisc.CheckState.ToYesOrNoString(); string is_pinkdisc = this.chkPinkdisc.CheckState.ToYesOrNoString(); string json_data = "{\"id\":" + this.parent_form.serial.id.ToString() + ","; json_data += "\"verext\":\"" + this.verext + "\","; json_data += "\"is_greendisc\":\"" + is_greendisc + "\","; json_data += "\"is_pinkdisc\":\"" + is_pinkdisc + "\","; json_data += "\"users_name\":\"" + this.G.loged_in_user_name + "\"}"; CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "serial/up_new_rwt_line", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { this.parent_form.serial = sr.serial[0]; this.parent_form.problem = sr.problem; this.parent_form.problem_im_only = (sr.problem.Count > 0 ? sr.problem.Where <Problem>(t => t.probcod == "IM").ToList <Problem>() : new List <Problem>()); this.parent_form.verext = sr.verext[0]; this.save_result = true; } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); this.save_result = false; } }
private void workerSubmit_Dowork(object sender, DoWorkEventArgs e) { string json_data = "{\"id\":" + this.serial.id.ToString() + ","; json_data += "\"lost_sernum\":\"" + this.mskLostSernum.Text.cleanString() + "\","; json_data += "\"new_sernum\":\"" + this.mskNewSernum.Text.cleanString() + "\","; json_data += "\"version\":\"" + this.txtVersion.Text.cleanString() + "\","; json_data += "\"is_newrwt\":\"" + this.chkNewRwt.CheckState.ToYesOrNoString() + "\","; json_data += "\"is_newrwt_job\":\"" + this.chkNewRwtJob.CheckState.ToYesOrNoString() + "\","; json_data += "\"is_cdtraining\":\"" + this.chkCDTraining.CheckState.ToYesOrNoString() + "\","; json_data += "\"users_name\":\"" + this.G.loged_in_user_name + "\"}"; CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "serial/lost_renew", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); Console.WriteLine(sr.message); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { this.DialogResult = DialogResult.OK; this.submit_result = true; } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); this.submit_result = false; } }
private void IstabAddEditForm_Load(object sender, EventArgs e) { if (this.mode == FORM_MODE.ADD) { this.Text = "Add data : " + Istab.getTabtypTitle(this.tabtyp); this.txtTypcod.Focus(); } else { this.Text = "Edit data : " + Istab.getTabtypTitle(this.tabtyp); this.txtTypcod.Enabled = false; this.txtAbbreviate_th.Focus(); CRUDResult get = ApiActions.GET(PreferenceForm.API_MAIN_URL() + "istab/get_by_id&id=" + this.istab.id); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(get.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { if (sr.istab != null) { this.istab = sr.istab.First <Istab>(); this.txtTypcod.Text = this.istab.typcod; this.txtAbbreviate_en.Text = this.istab.abbreviate_en; this.txtAbbreviate_th.Text = this.istab.abbreviate_th; this.txtTypdes_en.Text = this.istab.typdes_en; this.txtTypdes_th.Text = this.istab.typdes_th; } } } }
public ServerResult <Auth_DB_Context.User> Authenticate(string email, string password) { ServerResult <Auth_DB_Context.User> sr = ServerResult <Auth_DB_Context.User> .create(); try{ sr.result = db.User.Where(x => x.email == email && x.password == password).First(); } catch { sr.error.addMessage(Helper.HttpError.getIdNotExist(TabelList.User, email)); return(sr); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, sr.result.apiId), new Claim("Role", "Admin"), new Claim(ClaimTypes.Country, "DE") }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); sr.result.token = tokenHandler.WriteToken(token); sr.result.WithoutPassword(); return(sr); }
public static bool CreateHolidayNote(NoteCalendar note) { string url = PreferenceForm.API_MAIN_URL() + "notecalendar/create_holiday_note"; string json_string = "{\"date\":\"" + note.date + "\","; json_string += "\"type\":" + note.type.ToString() + ","; json_string += "\"description\":\"" + note.description + "\","; json_string += "\"group_maid\":\"" + note.group_maid + "\","; json_string += "\"group_weekend\":\"" + note.group_weekend + "\","; json_string += "\"max_leave\":" + note.max_leave.ToString() + ","; json_string += "\"rec_by\":\"" + note.rec_by + "\"}"; CRUDResult get = ApiActions.POST(url, json_string); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(get.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { return(true); } else if (sr.result == ServerResult.SERVER_CREATE_RESULT_FAILED_EXIST) { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); return(false); } else { if (MessageAlert.Show(sr.message, "Error", MessageAlertButtons.RETRY_CANCEL, MessageAlertIcons.ERROR) == DialogResult.Retry) { return(CreateHolidayNote(note)); } return(false); } }
//Existe um laço nos métodos de requisição e dentro desse laço o método "Autenticar" é chamado para refazer a validação da token, caso o mesmo tenha expirado. public async Task <string> Autenticar(string cpf, string senha) { try { Client.CancelPendingRequests(); var senhaEncriptada = Criptografia.CriptografarMD5(senha); var json = JsonConvert.SerializeObject(new { cpf, senha = senhaEncriptada }); var content = new StringContent(json, Encoding.UTF8, "application/json"); var uri = $"{this.uri}/autenticacao"; HttpResponseMessage result = await Client.PostAsync(uri, content); ServerResponse = JsonConvert.DeserializeObject <ServerResult>(result.Content.ReadAsStringAsync().Result); if (result.StatusCode == HttpStatusCode.OK) { CrossSecureStorage.Current.SetValue("SenhaUsuario", senha); CrossSecureStorage.Current.SetValue("CpfUsuario", cpf); CrossSecureStorage.Current.SetValue("Token", ServerResponse.Chave); return(ServerResponse.Chave); } return(ServerResponse.Mensagem); } catch { throw new Exception(MensagemErro); } }
private void inquireAll() { if (this.serial_list.Count == 0) { string ids = string.Empty; for (int i = 0; i <= 100; i++) { if (i == 0) { ids += this.serial_id_list[i].id.ToString(); } else { ids += "," + this.serial_id_list[i].id.ToString(); } } CRUDResult get = ApiActions.GET(PreferenceForm.API_MAIN_URL() + "serial/get_inquiry&sort=" + this.sortMode + "&ids=" + ids); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(get.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { if (sr.serial_list.Count > 0) { this.serial_list = sr.serial_list; this.toolStripLoadedRec.Text = this.serial_list.Count.ToString(); this.toolStripTotalRec.Text = this.serial_id_list.Count.ToString(); } } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); } } }
/// <summary> /// <see cref="IApiConnector.UnlinkEntity"/> /// </summary> public bool UnlinkEntity(Entity parent, Entity child) { var url = parent.RelativeUrl + "/" + parent.Id + "/" + _restResources.GetResource(child.GetType()) + "/" + child.Id; var response = CallServer(url, customMethod: "UNLINK"); var result = new ServerResult(); return(ExtractResponse(parent, response, result)); }
public HttpResponseMessage getServerList([FromBody] ServerRequest nServerRequest) { ServerResult serverResult_ = new ServerResult(); serverResult_.mRoleList = RoleAspect.getRoleList(nServerRequest.mOperatorName, nServerRequest.mVersionNo, nServerRequest.mAccountId); serverResult_.mServerList = ServerAspect.getServerList(nServerRequest.mOperatorName, nServerRequest.mVersionNo); return(toJson(serverResult_)); }
private void toolStripDelete_Click(object sender, EventArgs e) { if (this.dgvIstab.CurrentCell == null) { return; } if (this.dgvIstab.Rows[this.dgvIstab.CurrentCell.RowIndex].Tag is Istab) { this.dgvIstab.Tag = DGV_TAG.DELETE; if (MessageAlert.Show(StringResource.CONFIRM_DELETE, "", MessageAlertButtons.OK_CANCEL, MessageAlertIcons.QUESTION) == DialogResult.OK) { this.FormProcessing(); Istab delete_item = (Istab)this.dgvIstab.Rows[this.dgvIstab.CurrentCell.RowIndex].Tag; bool delete_success = false; string err_msg = ""; BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate { CRUDResult delete = ApiActions.DELETE(PreferenceForm.API_MAIN_URL() + "istab/delete&id=" + ((Istab)this.dgvIstab.Rows[this.dgvIstab.CurrentCell.RowIndex].Tag).id.ToString()); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(delete.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { delete_success = true; } else { delete_success = false; err_msg = sr.message; } }; worker.RunWorkerCompleted += delegate { if (delete_success) { int delete_row_index = this.dgvIstab.Rows.Cast <DataGridViewRow>().Where(r => ((Istab)r.Tag).id == delete_item.id).First <DataGridViewRow>().Cells[1].RowIndex; this.GetIstabData(null, false, delete_row_index); } else { MessageAlert.Show(err_msg, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); this.dgvIstab.Tag = DGV_TAG.NORMAL; this.FormRead(); } }; worker.RunWorkerAsync(); } else { this.FillInDatagrid((Istab)this.dgvIstab.Rows[this.dgvIstab.CurrentCell.RowIndex].Tag); } } }
public async Task <ServerResult> CreateAsync(PersonDto model) { var newModel = _mapper.Map <Person>(model); _context.People.Add(newModel); await _context.SaveChangesAsync(); return(ServerResult.Success()); }
public async Task <ServerResult> DeleteAsync(Guid id) { var toReturn = new ServerResult <UserProfileDto>(); await _inactivateUserCommand.ExecuteAsync(id); MergeMessages(toReturn, _registerUsersCommand); return(toReturn); }
private void btnOK_Click(object sender, EventArgs e) { bool post_success = false; this.formSaving(); BackgroundWorker workerSave = new BackgroundWorker(); workerSave.DoWork += delegate { string json_data = "{\"sernum\":\"" + this.mskSernum.Text + "\","; json_data += "\"qty\":" + this.numQty.Value.ToString() + ","; json_data += "\"version\":\"" + this.txtVersion.Text + "\","; json_data += "\"dealer\":\"" + this.txtDealer.Text + "\","; json_data += "\"is_newrwt\":\"" + this.chkNewRwt.CheckState.ToYesOrNoString() + "\","; json_data += "\"is_newrwtjob\":\"" + this.chkNewRwtJob.CheckState.ToYesOrNoString() + "\","; json_data += "\"is_cdtraining\":\"" + this.chkCDTraining.CheckState.ToYesOrNoString() + "\","; json_data += "\"users_name\":\"" + this.G.loged_in_user_name + "\"}"; CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "serial/generate_sn", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { post_success = true; this.parent_window.serial = sr.serial[0]; this.parent_window.busityp = (sr.busityp.Count > 0 ? sr.busityp[0] : new Istab()); this.parent_window.area = (sr.area.Count > 0 ? sr.area[0] : new Istab()); this.parent_window.howknown = (sr.howknown.Count > 0 ? sr.howknown[0] : new Istab()); this.parent_window.verext = (sr.verext.Count > 0 ? sr.verext[0] : new Istab()); this.parent_window.dealer = (sr.dealer.Count > 0 ? sr.dealer[0] : new Dealer()); this.parent_window.problem = new List <Problem>(); this.parent_window.problem_im_only = new List <Problem>(); } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); post_success = false; } }; workerSave.RunWorkerCompleted += delegate { if (post_success) { this.DialogResult = DialogResult.OK; this.Close(); } else { this.formEdit(); } }; workerSave.RunWorkerAsync(); }
public async Task <ServerResult> PutAsync([FromBody] UserProfileDto userProfile) { var toReturn = new ServerResult(); await _registerUsersCommand.ExecuteAsync(userProfile); MergeMessages(toReturn, _registerUsersCommand); return(toReturn); }
public async Task <ServerResult <UserProfileDto> > GetAsync(Guid id) { var toReturn = new ServerResult <UserProfileDto>(); toReturn.Data = await _userProfileQuery.RunAsync(id); MergeMessages(toReturn, _registerUsersCommand); return(toReturn); }
public async Task <IEnumerable <Photo> > GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken cancellationToken = default(CancellationToken)) { var photos = new List <Photo>(); var httpClient = new HttpClient(); var requestStr = "http://funnygif.lihulab.net/news/photos?page=" + (pageIndex + 1); var requestUri = new Uri(requestStr); try { //var httpClient = new HttpClient(); var httpResponse = await httpClient.GetAsync(requestUri); if (httpResponse.StatusCode == HttpStatusCode.NotFound) { return(photos); } //httpResponse.EnsureSuccessStatusCode(); var bytes = await httpResponse.Content.ReadAsBufferAsync(); var properEncodedString = Encoding.UTF8.GetString(bytes.ToArray()); JObject res = JObject.Parse(properEncodedString); var results = res["results"].Children().ToList(); var serverResults = new List <ServerResult>(); foreach (var result in results) { ServerResult serverResult = result.ToObject <ServerResult>(); serverResults.Add(serverResult); } foreach (var result in serverResults) { var item = new Photo(); item.Cover = result.imglink; item.Title = result.title; var imgurls = result.content.Split(' '); item.Urls = new List <string>(); foreach (var url in imgurls) { if (url.Length > 10) { item.Urls.Add(url); } } photos.Add(item); } } catch (Exception ex) { var dialog = new MessageDialog("发生网络错误。若重复出现,联系作者修复。"); await dialog.ShowAsync(); } return(photos); }
private void btnOK_Click(object sender, EventArgs e) { TimeSpan ts = TimeSpan.Parse(this.tmTo.Value.Hour.ToString() + ":" + this.tmTo.Value.Minute.ToString() + ":00") - TimeSpan.Parse(this.tmFrom.Value.Hour.ToString() + ":" + this.tmFrom.Value.Minute.ToString() + ":00"); if (this.support_note == null) // add mode { string json_data = "{\"date\":\"" + this.date.ToMysqlDate() + "\","; json_data += "\"sernum\":\"\","; json_data += "\"start_time\":\"" + this.tmFrom.Text + ":00\","; json_data += "\"end_time\":\"" + this.tmTo.Text + ":00\","; json_data += "\"duration\":\"" + ts.ToString().Substring(0, 8) + "\","; json_data += "\"reason\":\"" + SupportNote.BREAK_REASON.TRAINING_TRAINER.FormatBreakReson() + "\","; json_data += "\"remark\":\"\","; json_data += "\"users_name\":\"" + this.user.username + "\","; json_data += "\"is_break\":\"Y\","; json_data += "\"rec_by\":\"" + this.main_form.G.loged_in_user_name + "\"}"; CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "supportnote/create_break", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { this.DialogResult = DialogResult.OK; this.Close(); } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); } } else // update mode { string json_data = "{\"id\":" + this.support_note.id.ToString() + ","; json_data += "\"date\":\"" + this.date.ToMysqlDate() + "\","; json_data += "\"sernum\":\"\","; json_data += "\"start_time\":\"" + this.tmFrom.Text + ":00\","; json_data += "\"end_time\":\"" + this.tmTo.Text + ":00\","; json_data += "\"duration\":\"" + ts.ToString().Substring(0, 8) + "\","; json_data += "\"reason\":\"" + SupportNote.BREAK_REASON.TRAINING_TRAINER.FormatBreakReson() + "\","; json_data += "\"remark\":\"\","; json_data += "\"users_name\":\"" + this.user.username + "\","; json_data += "\"is_break\":\"Y\","; json_data += "\"rec_by\":\"" + this.main_form.G.loged_in_user_name + "\"}"; CRUDResult post = ApiActions.POST(PreferenceForm.API_MAIN_URL() + "supportnote/update_break", json_data); ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(post.data); if (sr.result == ServerResult.SERVER_RESULT_SUCCESS) { this.DialogResult = DialogResult.OK; this.Close(); } else { MessageAlert.Show(sr.message, "Error", MessageAlertButtons.OK, MessageAlertIcons.ERROR); } } }
public async Task <ServerResult> DeleteUserAsync(ApplicationUser user) { var result = await _userManager.DeleteAsync(user); return(result.Succeeded ? ServerResult.Success() : new ServerResult() { Succeeded = false, Errors = result.Errors.Select(e => e.Description).ToArray() }); }
// shutdown from external // thread safe public void Shutdown(ServerResult request) { SetResult(request); cancelTokenSource.Cancel(); }
// use the most serious result // thread safe private void SetResult(ServerResult request) { if (request == ServerResult.None) { throw new ArgumentException("request must not be NONE"); } lock (this) { int prev = (int)runResult; int next = Math.Max((int)request, prev); runResult = (ServerResult)next; } }