public JsonResult GET_municipality_update_filters(RequestBusinessFilter request) { try { BusinessResultResponse response = new BusinessResultResponse() { Status = a2m.Common.Responses.Response.Status.Ok }; Municipality currentMunicipality = MunicipalityManager.getMunicipalityByNormalizedName(request.CurrentMunicipality); if (currentMunicipality == null){ a2m.A2MApplication.Log.Error("BusinessController unable to found municipality " + request.CurrentMunicipality); JSONResponse responseError = new JSONResponse() { Status = a2m.Common.Responses.Response.Status.Error }; return Json(responseError, JsonRequestBehavior.AllowGet); } MunicipalityModel MunicipalityModel = new MunicipalityModel(); MunicipalityModel.Municipality = currentMunicipality; MunicipalityModel.CurrentPage = request.CurrentPage; //TODO FILTERING BussinessManager BussinessManager = new BussinessManager(); MunicipalityModel.BusinessList = BussinessManager.GetBusinessFromMunicipalityIdAndFilters(request.toBusinesFilter(), a2m.A2MApplication.ResultsPaginateSize); response.ResultHtmlView = RenderRazorViewToString("~/Views/Municipality/MunicipalitySearchResult.cshtml", MunicipalityModel); response.PageSize = a2m.A2MApplication.ResultsPaginateSize; response.TotalResult = MunicipalityModel.BusinessList.Count; response.NextPage = request.CurrentPage + 1; return Json(response, JsonRequestBehavior.AllowGet); } catch (Exception ex) { a2m.A2MApplication.Log.Error("BusinessController", ex); JSONResponse response = new JSONResponse() { Status = a2m.Common.Responses.Response.Status.Error }; return Json(response, JsonRequestBehavior.AllowGet); } }
public ActionResult <dynamic> Unsubscribe() { string authorization = Request.Headers["Authorization"]; string token = authorization.Substring("Bearer ".Length).Trim(); Int32 userId = _userService.GetUserId(token); view_user user = _contextForView.view_user.FirstOrDefault(x => x.id == userId); if (!user.is_subscribed) { throw new MindnoteException("痾~你好像不是訂閱用戶", HttpStatusCode.ExpectationFailed); } transaction existedTransaction = _context.transaction.FirstOrDefault(x => x.id == user.transaction_id); if (!existedTransaction.is_next_subscribe) { throw new MindnoteException("已經取消訂閱囉~下一期我們將停止扣款"); } // transaction existedTransaction = new transaction { id = user.transaction_id ?? -1 }; // _context.Attach<transaction>(existedTransaction); existedTransaction.is_next_subscribe = false; _context.SaveChanges(); JSONResponse json = new JSONResponse(JSONResponseStatus.OK, new { }); return(json.toResponseObj()); }
internal void StartGames(List <string> MachinesToStart, string GUID) { lock (Connections) foreach (string Machine in MachinesToStart) { new Action(() => { JSONResponse <object> Return = Connections[Machine].Connection.TransmitJSONCommand <PlayGameModel, object>(new JSONAction <PlayGameModel>() { ActionName = "StartGame", ActionData = new PlayGameModel() { GUID = GUID } }); if (Return.RequestStatus == JSONResponseStatus.Success) { AttendantConsole.Log($"{Machine} Has started"); } else { AttendantConsole.Log($"{Machine} Has Failed to start with this message:\n{Return.Message}"); } }).Invoke(); } }
/// <summary> /// Post JSON request to server, without throwing if theres a bad request /// </summary> /// <typeparam name="T">Model type to post</typeparam> /// <typeparam name="R">Expected result type</typeparam> /// <param name="client">The client.</param> /// <param name="URL"></param> /// <param name="model">The model.</param> /// <returns></returns> public static async Task <JSONResponse <R> > PostJSONAsync <T, R>(this HttpClient client, string URL, T model) where R : ServerResponse { var serializedModel = JsonSerializer.Serialize <T>(model); var content = new StringContent(serializedModel, Encoding.UTF8, "application/json"); var result = await client.PostAsync(URL, content); var response = new JSONResponse <R> { IsSuccessful = result.IsSuccessStatusCode, StatusCode = result.StatusCode }; string stringContent = await result.Content.ReadAsStringAsync(); try { response.Response = JsonSerializer.Deserialize <R>(stringContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch { var serverResponse = Serialization.Deserialize <ServerResponse>(stringContent); response.Response = default; response.Response.Errors = serverResponse.Errors; response.IsSuccessful = false; } return(response); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JSONResponse response = new JSONResponse(); var array = JArray.Load(reader); if (array.Count != 2) { // Or maybe throw an exception? Debug.WriteLine("Unexpected array length for " + array.ToString()); } foreach (var entry in array) { if (entry["campaignId"] != null) { response.Inf = entry.ToObject <Inf>(); } else if (entry["reason"] != null) { response.number = entry.ToObject <number>(); } else { // Or maybe throw an exception? Debug.WriteLine("Unknown entry " + entry.ToString()); } } return(response); }
public ActionResult EmailDelete() { string getType = Request["_type"]; string getNoReferensi = Request["_noReferensi"]; ViewBag.Type = "deleteEmail"; Params paramList = new Params() { Parameter = new Dictionary <string, string>() }; ESBData esbData = new ESBData() { Result = new List <StringDictionary>() }; Object[] data = new Object[1]; JSONResponse jsonResponse = new JSONResponse(); bool checkSpv = false; switch (getType) { case "inbox": checkSpv = RoleNPrivilege.checkEntityButtonByRoleID(new Guid(Session["RoleID"].ToString()), "EmailInbox", "Delete"); break; case "kirimEmail": checkSpv = RoleNPrivilege.checkEntityButtonByRoleID(new Guid(Session["RoleID"].ToString()), "EmailSend", "Delete"); break; } switch (checkSpv) { case true: paramList.RequestTransType = "DeleteEmailByRefNo"; paramList.Parameter.Add("PK_ID", getNoReferensi); paramList.WSDL = "ESBDBDelimiter"; esbData = EAI.RetrieveESBData(paramList); if (esbData != null && esbData.Result.Count != 0) { foreach (StringDictionary kvp in esbData.Result) { if (kvp.ContainsKey("result")) { jsonResponse.Value = new { Message = Resources.Email.EmailDeleteSuccess }; jsonResponse.Response = kvp["result"]; } } } break; } return(Json(jsonResponse)); }
void webSocket_MessageReceived(object sender, MessageReceivedEventArgs e) { JSONResponse value = JsonConvert.DeserializeObject <JSONResponse>(e.Message); switch (value.response) { case "startMonitoring": if (CPUData != null) { CPUData(this, e); } return; case "getDISKUsage": if (DiskData != null) { DiskData(this, e); } return; case "getRAMUsage": if (RAMData != null) { RAMData(this, e); } return; } //var value.parameters[0]; //Console.WriteLine(value.response); }
/** * constructor of the controller * @param string appName the name of the app * @param IRequest request an instance of the request * @since 6.0.0 - parameter appName was added in 7.0.0 - parameter app was removed in 7.0.0 */ public Controller(string appName, IRequest request) { this.appName = appName; this.request = request; // default responders this.responders.Add("json", data => { if (data is DataResponse) { var response = new JSONResponse(((DataResponse)data).getData(), ((DataResponse)data).getStatus()); var dataHeaders = data.getHeaders(); var headers = response.getHeaders(); if (dataHeaders.ContainsKey("Content-Type")) { headers.Remove("Content-Type"); } response.setHeaders(dataHeaders.Concat(headers).ToDictionary(o => o.Key, p => p.Value)); return(response); } return(new JSONResponse(data)); }); }
public ActionResult <dynamic> DeleteNode([FromRoute] Int32 boardId, [FromRoute] Int16 nodeId) { string authorization = Request.Headers["Authorization"]; string token = authorization.Substring("Bearer ".Length).Trim(); Int16 userId = _userService.GetUserId(token); node node = _context.node.FirstOrDefault(x => x.id == nodeId && x.owner_id == userId && x.board_id == boardId && x.deleted_at == null); if (node is null) { throw new MindnoteException("筆記已經找不到了 Q_Q", HttpStatusCode.NotFound); } else { node.deleted_at = DateTime.Now; } List <node_relationship> relationships = _context.node_relationship.Where(x => (x.child_node_id == node.id || x.parent_node_id == node.id) && x.deleted_at == null).ToList(); foreach (node_relationship relationship in relationships) { relationship.deleted_at = DateTime.Now; } node.updated_at = DateTime.Now; Int32 deleteResult = _context.SaveChanges(); JSONResponse result = new JSONResponse(JSONResponseStatus.OK, new { }); return(result.toResponseObj()); }
public String backupfile(String Date, String Time) { var request = WebRequest.CreateHttp(urlbackup + "/" + Date + "/" + Time + ".json"); request.Method = "GET"; request.ContentType = "application/json"; var response = request.GetResponse(); var json = (new StreamReader(response.GetResponseStream())).ReadToEnd(); if (json != null) { var request2 = WebRequest.CreateHttp(urlmain + ".json"); request2.Method = "PATCH"; request2.ContentType = "application/json"; var buffer = Encoding.UTF8.GetBytes(json); request2.ContentLength = buffer.Length; request2.GetRequestStream().Write(buffer, 0, buffer.Length); var response2 = request2.GetResponse(); var json2 = (new StreamReader(response2.GetResponseStream())).ReadToEnd(); JSONResponse rs = JsonConvert.DeserializeObject <JSONResponse>(json2); return(rs.ToString()); } else { return("False"); } }
void w_RAMData(object sender, WebSocket4Net.MessageReceivedEventArgs e) { JSONResponse value = JsonConvert.DeserializeObject <JSONResponse>(e.Message); Hashtable diskData = value.parameters["GetRamUsage"]; m = JsonConvert.DeserializeObject <MEMORYSTATUSEX>(diskData["ramUsage"].ToString()); }
void webSocket_MessageReceived(object sender, MessageReceivedEventArgs e) { JSONResponse value = JsonConvert.DeserializeObject <JSONResponse>(e.Message); //var value.parameters[0]; Console.WriteLine(value.response); }
public static JSONResponse JSONToObject(string json) { JSONResponse response = new JSONResponse(); response = JsonUtility.FromJson <JSONResponse>(json); return(response); }
void w_CPUData(object sender, WebSocket4Net.MessageReceivedEventArgs e) { JSONResponse value = JsonConvert.DeserializeObject <JSONResponse>(e.Message); processSet.Clear(); processSet = value.parameters["StartMonitoring"]; CPU_Response_Recieved = true; }
void w_DiskData(object sender, WebSocket4Net.MessageReceivedEventArgs e) { JSONResponse value = JsonConvert.DeserializeObject <JSONResponse>(e.Message); Hashtable diskData = value.parameters["GetDiskUsage"]; diskDataValues = JsonConvert.DeserializeObject <DiskDataValues>(diskData["diskUsage"].ToString()); Disk_Response_Recieved = true; }
public static IEnumerator PostPhoto(string route, string parameters) { requestState = State.started; string url = urlBase + route; UnityWebRequest request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = Encoding.UTF8.GetBytes(parameters); request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //string downloadedPhoto = Application.persistentDataPath + "/userPicture.png"; //string downloadedPhoto = Application.dataPath+ "/userPicture.png"; //Debug.Log(downloadedPhoto); //File.WriteAllBytes (downloadedPhoto, request.b); //WWW www = new WWW (url); //yield return www; //File.WriteAllBytes (downloadedPhoto, bodyRaw); if (PlayerPrefs.GetString("data") != null || PlayerPrefs.GetString("data") != "") { string token = PlayerPrefs.GetString("token"); if (token != null || token != "") { request.SetRequestHeader("Authorization", token); } } yield return(request.Send()); if (request.error != null) { Debug.Log("request error: " + request.error); requestState = State.error; } else { response = JSONHelper.JSONToObject(request.downloadHandler.text); if (response.code == 200) { PlayerPrefs.SetString("urlPhoto", response.data); Debug.Log(response.data); /*WWW www = new WWW (response.data); * yield return www; * File.WriteAllBytes (downloadedPhoto, www.bytes);*/ requestState = State.successful; } else { requestState = State.aborted; } } }
private JSONResponse <dynamic> OnMessageReceived(JSONAction <dynamic> Message) { Console.WriteLine($"Message Recived.\n{Message}"); switch (Message.ActionName) { case "StopGame": { JSONResponse <dynamic> Return = new JSONResponse <dynamic>() { ActionName = Message.ActionName, ActionData = new { }, RequestStatus = JSONResponseStatus.Success }; Console.WriteLine($"Returing with:\n{Return}"); return(Return); } case "ClearCharges": { JSONResponse <dynamic> Return = new JSONResponse <dynamic>() { ActionName = Message.ActionName, ActionData = new { }, RequestStatus = JSONResponseStatus.Success }; Console.WriteLine($"Returing with:\n{Return}"); return(Return); } case "GetSlaveInfo": { JSONResponse <SlaveInfo> Return = new JSONResponse <SlaveInfo>() { ActionName = Message.ActionName, ActionData = Info, RequestStatus = JSONResponseStatus.Success }; Console.WriteLine($"Returing with:\n{Return}"); return(Return.ToDynamic()); } case "StartGame": { //AttendantConsole.ActivateForTappedCard(Message.DynamicAutoCast<SlaveInfo>().ActionData); JSONResponse <dynamic> Return = new JSONResponse <dynamic>() { ActionName = Message.ActionName, ActionData = new { }, RequestStatus = JSONResponseStatus.Success }; Console.WriteLine($"Returing with:\n{Return}"); return(Return); } default: { JSONResponse <dynamic> Return = new JSONResponse <dynamic>() { ActionName = Message.ActionName, ActionData = Message.ActionData, Message = "The Client has failed to find the requested action.", RequestStatus = JSONResponseStatus.ActionNotFound }; Console.WriteLine($"Returing with:\n{Return}"); return(Return); } } }
public static JSONResponse CreateResponse(Session session, ResponseStatus status, object value) { JSONResponse response = new JSONResponse(); response.Body = new Dictionary <string, object>(); response.Body["sessionId"] = session == null ? null : session.ToString(); response.Body["status"] = (int)status; response.Body["value"] = value; return(response); }
public static JSONResponse SwitchProcess(string data) { JSONResponse resp = new JSONResponse(); switch (data) { } return(resp); }
public JSONResponse SubmitFile(Annotation model, ActionType actionType) { JSONResponse result = new JSONResponse(); List <string> errorMessage = new List <string>(); string successMessage = Resources.LetterTemplate.Alert_Success; if (ModelState.IsValid) { KeyValuePair <int, string> results = new KeyValuePair <int, string>(1, string.Empty); switch (actionType) { case ActionType.Create: results = db.Annotation_Insert(model); break; case ActionType.Edit: results = db.Annotation_Update(model); break; default: break; } if (results.Key == 0 || results.Key == 16 || results.Key == 6) { UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext); string url = u.Action("Edit", "LetterTemplate", new { id = model.ObjectID, success = successMessage }); result.Value = true; result.Response = url; return(result); } else { result.Value = false; result.Response = results.Value.ToString(); return(result); } } else { foreach (var key in ModelState.Keys) { var error = ModelState[key].Errors.FirstOrDefault(); if (error != null) { errorMessage.Add(error.ErrorMessage); } } result.Value = false; result.Response = errorMessage.First(); return(result); } }
public String[] Checkout(int userid, int paymentid) { bool success = factory.checkout(userid, paymentid); if (!success) { return(JSONResponse.setMessage("error", "Opss...", "Checkout Failed")); } return(JSONResponse.setMessage("success", "Yeay...", "Checkout Success")); }
public String[] UpdateStatus(String id, String role, String status) { var data = userRepository.getUser(Int32.Parse(id)); if (data == null) { return(JSONResponse.setMessage("error", "Opss...", "User not found")); } userRepository.update(Int32.Parse(id), Int32.Parse(role), status); return(JSONResponse.setMessage("success", "Yeay...", "User has been updated")); }
public JSONResponse <GetMachineGamesReturn> GetGames(JSONAction <object> This) { ArcadeGameStartAndStopService.Logger.WriteLog($"Get Games was called\nWith Data:\n{This}\n"); JSONResponse <GetMachineGamesReturn> Return = new JSONResponse <GetMachineGamesReturn>() { ActionData = new GetMachineGamesReturn(), ActionName = This.ActionName, RequestStatus = JSONResponseStatus.Success }; Return.ActionData.VRMachineGames = ArcadeGameStartAndStopService.GameConfig.GamesRaw; ArcadeGameStartAndStopService.Logger.WriteLog($"Retuning to get games with:\n{Return}\n"); return(Return); }
public String[] RegisterUser(string email, string name, string password, string gender) { if (userRepository.getUser(email) != null) { return(JSONResponse.setMessage("error", "Opss...", "Account already registered")); } User user = userFactory.createUser(email, name, password.GetHashCode().ToString(), gender); userRepository.insertUser(user); return(JSONResponse.setMessage("success", "Yeay...", "Account success to registered")); }
public Object getrealtime() { var request = WebRequest.CreateHttp(urlmain + ".json"); request.Method = "GET"; request.ContentType = "application/json"; var response = request.GetResponse(); var json = (new StreamReader(response.GetResponseStream())).ReadToEnd(); JSONResponse rs = JsonConvert.DeserializeObject <JSONResponse>(json); return(rs); }
public String[] Add(String name, String desc) { if (typeRepository.getProductTypes(name) != null) { return(JSONResponse.setMessage("error", "Opss...", "Product type already exist")); } ProductType productType = typeFactory.createProductType(name, desc); typeRepository.insertProduct(productType); return(JSONResponse.setMessage("success", "Yeay..", "Product type has been added")); }
public static object GetValueOptions(ElementRequest request) { JSONResponse response = new JSONResponse(); if (request.Target.IsValueReadOnly()) { response.Options = new string[] { "GET", "POST", "OPTIONS" }; } else { response.Options = new string[] { "GET", "OPTIONS" }; } return(response); }
public string[] Update(String id, String name, String productTypeID, String price, String qty) { bool canEdit = productHandler.isValidData(id); if (!canEdit) { return(JSONResponse.setMessage("error", "Opss...", "Product not found")); } Product product = productFactory.createProduct(name, Int32.Parse(productTypeID), Int32.Parse(price), Int32.Parse(qty)); productRepository.updateProduct(Int32.Parse(id), product); return(JSONResponse.setMessage("success", "Yeay...", "Product has been updated")); }
public static JSONResponse Create(JSONRequest request) { if (!request.Body.ContainsKey("desiredCapabilities")) { throw new ArgumentException("desiredCapabilities not provided"); } Dictionary <string, object> sessionSetupInfo = request.Body.ContainsKey("sessionSetup") ? (Dictionary <string, object>)request.Body["sessionSetup"] : null; Session session = GetFactory(request).Create(flatten((Dictionary <string, object>)request.Body["desiredCapabilities"]), sessionSetupInfo); JSONResponse response = new JSONResponse(); response.StatusCode = 303; response.Location = "/session/" + session.ToString(); return(response); }
public String[] Add(string type) { if (payment.getPaymentType(type) != null) { return(JSONResponse.setMessage("error", "Opss...", "Payment type already exist")); } PaymentType paymentType = new PaymentType(); paymentType.Type = type; payment.insertPayment(paymentType); return(JSONResponse.setMessage("success", "Yeay..", "Payment type has been added")); }
internal void StopGames(List <string> MachinesToStop) { lock (Connections) foreach (string Machine in MachinesToStop) { new Action(() => { JSONResponse <object> Return = Connections[Machine].Connection.TransmitJSONCommand <object, object>(new JSONAction <object>() { ActionName = "StopGame", ActionData = new { } }); AttendantConsole.Log($"{Machine} Has stoped"); }).Invoke(); } }