/// <summary> /// API call to get a Mechanic /// </summary> /// <param name="mechId"> Mechanic Id </param> public Mecanico GetMech(string mechId) { if (string.IsNullOrEmpty(mechId)) { ErrorWriter.InvalidArgumentsError(); return(null); } try { var request = new RestRequest($"{prefix}/mechanics/{mechId}", Method.GET) { RequestFormat = DataFormat.Json }; var response = client.Execute <Mecanico>(request); string notFoundMsg = "El Mecánico requerido no existe"; CheckStatusCode(response, notFoundMsg); return(response.Data); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
/// <summary> /// Reads from the stream until the external program is ended. /// </summary> private void StreamReaderThread_Error() { StreamReader reader = _stdError; bool doAppend = OutputAppend; while (true) { string logContents = reader.ReadLine(); if (logContents == null) { break; } // ensure only one thread writes to the log at any time lock (_lockObject) { ErrorWriter.WriteLine(logContents); if (Output != null) { StreamWriter writer = new StreamWriter(Output.FullName, doAppend); writer.WriteLine(logContents); doAppend = true; writer.Close(); } } } lock (_lockObject) { ErrorWriter.Flush(); } }
/// <summary> /// API call to update a Booking /// </summary> /// <param name="newBook"> New Booking </param> public bool UpdateBooking(Booking newBook) { if (newBook == null) { ErrorWriter.InvalidArgumentsError(); return(false); } try { newBook.updated_at = DateTime.Now; var bookId = newBook.booking_id; var request = new RestRequest($"{bookPrefix}/{bookId}", Method.POST) { RequestFormat = DataFormat.Json }; request.AddJsonBody(newBook); var response = client.Execute(request); string notFoundMsg = "La Reserva requerida no existe"; CheckStatusCode(response, notFoundMsg); return(true); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
public ActionResult PayPub(string pubId, bool res) { try { if (res) { var changeRes = PC.ChangeStatus(pubId, "ACT"); if (!changeRes) { return(Error_FailedRequest()); } } else { SetErrorMsg("Hubo un error procesando su pago, por favor inténtelo nuevamente. Si el problema persiste, contacte a soporte"); return(RedirectToAction("PubDetails", new { pubId })); } } catch (Exception e) { ErrorWriter.ExceptionError(e); return(Error_CustomError(e.Message)); } SetSuccessMsg("La Publicación fue pagada cone éxito"); return(RedirectToAction("PubDetails", new { pubId })); }
public string visitBinaryExpr(Expression.Binary expr) { var firstType = expr.First.Accept(this); var secondType = expr.Second.Accept(this); if (firstType == null || secondType == null) { return(null); } if (firstType != secondType) { ErrorWriter.Write(expr.First, "Cannot operate with {0} and {1}", firstType, secondType); return(null); } // TODO use eval to get types? var type = expr.Operator.Type; if ( (type == TokenType.EQUAL || type == TokenType.AND || type == TokenType.NOT)) { return("bool"); } return(expr.First.Accept(this)); }
/// <summary> /// API call to update an User /// </summary> /// <param name="newUser"> New User </param> public bool UpdateUser(Usuario newUser) { if (newUser == null) { ErrorWriter.InvalidArgumentsError(); return(false); } try { var userId = newUser.appuser_id; var request = new RestRequest($"{prefix}/users/{userId}", Method.POST) { RequestFormat = DataFormat.Json }; request.AddJsonBody(newUser); var response = client.Execute(request); string notFoundMsg = "El Usuario requerido no existe"; CheckStatusCode(response, notFoundMsg); return(true); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
public ActionResult PubList() { List <PublicacionMec> pubs; try { // Ger user data var userId = User.Identity.GetUserId(); var user = UC.GetUser(userId); if (user == null) { return(Error_FailedRequest()); } // Conseguir todas las publicaciones porque obvio no hay filtro de user por API :tired_af: pubs = PC.GetAllPub(string.Empty, string.Empty, string.Empty, string.Empty).ToList(); if (pubs == null) { return(Error_FailedRequest()); } // Filtrar para las publicaciones de Mecánicos pubs = pubs.Where(x => x.appuser_id.Equals(userId)).ToList(); } catch (Exception e) { ErrorWriter.ExceptionError(e); return(Error_CustomError(e.Message)); } return(View(pubs)); }
/* ---------------------------------------------------------------- */ /* SERVICES CALLER */ /* ---------------------------------------------------------------- */ /// <summary> /// API call to list all Services /// </summary> public IEnumerable <Servicio> GetAllServ(string name, string serv_status, bool deleted = false) { try { var delString = deleted ? "&deleted=true" : ""; var url = $"{fullPrefix}?name={name}&serv_status={serv_status}{delString}"; // Request Base var request = new RestRequest(url, Method.GET) { RequestFormat = DataFormat.Json }; // Ejecutar request y guardar la respuesta var response = client.Execute <List <Servicio> >(request); // Levanta una excepción si el status code es diferente de 200 CheckStatusCode(response); var servs = response.Data; // Retorna el producto return(servs); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
/// <summary> /// API call to get a Service /// </summary> /// <param name="servId"> Service Id </param> public Servicio GetServ(string servId) { if (string.IsNullOrEmpty(servId)) { ErrorWriter.InvalidArgumentsError(); return(null); } try { var request = new RestRequest($"{fullPrefix}/{servId}", Method.GET) { RequestFormat = DataFormat.Json }; var response = client.Execute <Servicio>(request); string notFoundMsg = "El Servicio requerido no existe"; CheckStatusCode(response, notFoundMsg); var serv = response.Data; return(serv); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
public ClaimsIdentity CreateIdentity(bool isAuthenticated, string userName, dynamic payload, string token) { if (string.IsNullOrEmpty(userName) || payload == null) { return(null); } try { // Decode the payload from token in order to create a claim string userId = payload.userId; string role = payload.Usertype; // Define the claim var jwtIdentity = new ClaimsIdentity( new JwtIdentity(isAuthenticated, userName, DefaultAuthenticationTypes.ApplicationCookie) ); // Add Claims NameIdentifier and Role jwtIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId)); jwtIdentity.AddClaim(new Claim(ClaimTypes.Role, role)); jwtIdentity.AddClaim(new Claim(ClaimTypes.Authentication, token)); return(jwtIdentity); } catch (Exception e) { ErrorWriter.ExceptionError(e); return(null); } }
/// <summary> /// CREATES A FAKE IDENTITY FOR TESTING WITHOUT API /// </summary> public ClaimsIdentity CreateFakeIdentity() { try { // Decode the payload from token in order to create a claim string userId = "FAKE_USER_ID"; string role = "ADM"; // Define the claim var jwtIdentity = new ClaimsIdentity( new JwtIdentity(true, "FAKE_USER", DefaultAuthenticationTypes.ApplicationCookie) ); // Add Claims NameIdentifier and Role jwtIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId)); jwtIdentity.AddClaim(new Claim(ClaimTypes.Role, role)); return(jwtIdentity); } catch (Exception e) { ErrorWriter.ExceptionError(e); return(null); } }
private void Continue(object sender, RoutedEventArgs e) { try { string arrarar = settings.ASSKOP(); if (Password.Password != null) { exehs = Convert.ToBase64String(App.md5.ComputeHash(Encoding.UTF8.GetBytes(Password.Password))); } if (exehs == arrarar) { Logs.WriteLog("Password was entered correctly!"); this.Close(); } else { SystemSounds.Hand.Play(); InfoMessage.ShowInfo("ERROR!", "Password was entered incorrectly!"); Logs.WriteLog("ERROR-Password was entered incorrectly!"); return; } } catch (Exception ex) { ErrorWriter.WriteError(ex); } }
public bool visitAssignmentStmt(Statement.Assignment stmt) { var identifier = stmt.Identifier; if (!environment.Contains(identifier.Name)) { ErrorWriter.Write(identifier, "Cannot assign to uninitialized variable '{0}'", identifier.Name); return(false); } var variableType = environment.GetType(identifier.Name); var initializerType = stmt.Value.Accept(expressionAnalyzer); if (initializerType == null) { return(false); } if (initializerType != variableType) { ErrorWriter.Write(stmt.Value, "Cannot assign value of type {2} to variable {0} of type {1}", identifier.Name, variableType, initializerType); return(false); } if (environment.isLocked(identifier.Name)) { ErrorWriter.Write(stmt.Value, "Cannot reassign loop variable {0} during loop", identifier.Name); return(false); } return(true); }
public bool visitDeclarementStmt(Statement.Declarement stmt) { var identifier = stmt.Identifier; var initializer = stmt.Initializer; var type = stmt.Type; var valid = true; if (environment.Contains(identifier.Name)) { ErrorWriter.Write(identifier, "Cannot initialize variable '{0}' twice", identifier.Name); valid = false; } if (initializer == null) { environment.Declare(identifier.Name, type); return(valid); } var initializerType = initializer.Accept(expressionAnalyzer); if (initializerType == null) { valid = false; } else if (initializerType != type) { ErrorWriter.Write(stmt.Initializer, "Cannot initialize variable '{0}' of type {1} to type {2}", identifier.Name, type, initializerType); valid = false; } environment.Declare(identifier.Name, type); return(valid); }
/// <summary> /// API call to change the Password of an User /// </summary> /// <param name="password"></param> /// <param name="oldPassword"></param> /// <returns></returns> public bool UpdatePassword(string password, string oldPassword) { if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(oldPassword)) { ErrorWriter.InvalidArgumentsError(); return(false); } try { var request = new RestRequest($"user-auth/change-password", Method.POST); password = JwtProvider.EncryptHMAC(password); oldPassword = JwtProvider.EncryptHMAC(oldPassword); request.AddJsonBody(new { psw = password, old_psw = oldPassword }); var response = client.Execute(request); if (response.StatusCode == HttpStatusCode.Conflict) { throw new Exception("La contraseña ingresada es incorrecta"); } // Throw an exception if the StatusCode is different from 200 CheckStatusCode(response); return(true); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
public ActionResult PubList(string comuna, string bussName, string pubTitle) { List <PublicacionMec> pubs; try { pubs = PMC.GetAllPub(comuna, "ACT", bussName, pubTitle).ToList(); if (pubs == null) { return(Error_FailedRequest()); } } catch (Exception e) { ErrorWriter.ExceptionError(e); return(Error_CustomError(e.Message)); } // To keep the state of the search filters when the user make a search ViewBag.comuna = comuna; ViewBag.bussName = bussName; ViewBag.pubTitle = pubTitle; return(View(pubs)); }
/// <summary> /// API call to get an User /// </summary> /// <param name="userId"> User Id </param> public Usuario GetUser(string userId) { if (string.IsNullOrEmpty(userId)) { ErrorWriter.InvalidArgumentsError(); return(null); } try { var request = new RestRequest($"{prefix}/users/{userId}", Method.GET) { RequestFormat = DataFormat.Json }; var response = client.Execute <Usuario>(request); string notFoundMsg = "El Usuario requerido no existe"; CheckStatusCode(response, notFoundMsg); return(response.Data); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
/// <summary> /// Reads from the stream until the external program is ended. /// </summary> private void StreamReaderThread_Error() { try { var reader = m_StdError; while (true) { var logContents = reader.ReadLine(); if (logContents == null) { break; } // ensure only one thread writes to the log at any time lock (LockObject) { if (Verbose) { ErrorWriter.WriteLine(logContents); } MemoryWriter.WriteLine(logContents); } } lock (LockObject) { ErrorWriter.Flush(); MemoryWriter.Flush(); } } catch (Exception) { // just ignore any errors } }
public ActionResult AddPub(PublicacionMec newPub) { if (newPub == null) { return(Error_InvalidUrl()); } string newPubId; try { newPub.created_at = DateTime.Now; newPub.updated_at = DateTime.Now; newPubId = PC.AddPub(newPub); if (newPubId == null) { return(Error_FailedRequest()); } } catch (Exception e) { ErrorWriter.ExceptionError(e); return(Error_CustomError(e.Message)); } SetSuccessMsg("Publicación creada con éxito, te vamos a mandar un mail cuando sea aceptada por nuestro personal!"); return(RedirectToAction("PubDetails", new { pubId = newPubId })); }
private void btnOk_Click(object sender, EventArgs e) { try { btnOk.Enabled = false; btnPrint.Enabled = false; btnClose.Enabled = false; dtpFrom.Enabled = false; dtpTo.Enabled = false; Cursor = GWMHIS.BussinessLogicLayer.Classes.PublicStaticFun.WaitCursor( ); CreateTreeList( ); } catch (Exception err) { MessageBox.Show("统计发生错误!请稍后再试!"); ErrorWriter.WriteLog(err.Message); } finally { Cursor = Cursors.Default; btnOk.Enabled = true; btnPrint.Enabled = true; btnClose.Enabled = true; dtpFrom.Enabled = true; dtpTo.Enabled = true; } }
public ActionResult PayPub(string pubId) { if (string.IsNullOrEmpty(pubId)) { return(Error_InvalidUrl()); } PublicacionMec pub; try { pub = PC.GetPub(pubId); if (pub == null) { return(Error_FailedRequest()); } } catch (Exception e) { ErrorWriter.ExceptionError(e); return(Error_CustomError(e.Message)); } return(View(pub)); }
public bool?CheckStatusCode(IRestResponse response, string notFoundMsg = null, string badRequestMsg = null, string unauthorizedMsg = null, string internalServerErrorMsg = null, string genericMgs = null) { if (response.StatusCode != HttpStatusCode.OK) { ErrorWriter.CustomError($"RES CONTENT : {response.Content} \nSTATUS ID : {response.StatusCode}"); } switch (response.StatusCode) { case HttpStatusCode.BadRequest: throw new Exception(badRequestMsg ?? Resources.Messages.APIError_BadRequest); case HttpStatusCode.Unauthorized: throw new Exception(unauthorizedMsg ?? Resources.Messages.APIError_Unauthorized); case HttpStatusCode.InternalServerError: throw new Exception(internalServerErrorMsg ?? Resources.Messages.APIError_InternalServerError); case HttpStatusCode.NotFound: throw new Exception(notFoundMsg ?? Resources.Messages.APIError_NotFound); case HttpStatusCode.OK: return(true); default: throw new Exception(genericMgs ?? Resources.Messages.Error_SolicitudFallida); } }
public string visitOperandExpr(Expression.Operand expr) { switch (expr.Value.GetName()) { case "UNARY": case "BINARY": return(((Expression)expr.Value).Accept(this)); case "INTEGER": return("int"); case "STRING": return("string"); case "VAR_IDENTIFIER": var ident = (VarIdentifier)expr.Value; if (!environment.Contains(ident.Name)) { ErrorWriter.Write(ident, "Cannot operate on uninitalized variable '{0}'", ident.Name); return(null); } return(environment.GetType(ident.Name)); default: return(null); } }
private void Parser_OnNewData(object arg1, string arg2) { try { if (string.IsNullOrEmpty(arg2)) { InfoMessage.ShowInfo("ERROR", "Checking updates has been not correct!"); Logs.WriteLog("ERROR-Checking updates has been not correct!"); Progress = 0; Message = "ERROR, Click at 'Cancel' button to continue..."; } else { if (arg2.Contains(App.Version.Replace("v", ""))) { Progress = 0; Message = "Your application has the current version. Click at 'Cancel' button to continue..."; Logs.WriteLog("A new version of app not found. Your application has the current version."); } else { Logs.WriteLog("Update file has been finded!"); Progress = 0; CheckSize(); } } } catch (Exception ex) { ErrorWriter.WriteError(ex); Progress = 0; Message = "ERROR, Click at 'Cancel' button to continue..."; } }
// TODO: TBD: refactor this type of functionality to base class, i.e. ReportErrorLevel... private bool TryReportErrorLevel(int level) { // TODO: TBD: perhaps an indexer would be great as well... var descriptor = Levels.FirstOrDefault(x => x.ErrorLevel == level); // TODO: TBD: perhaps, CanReport property? // ReSharper disable once InvertIf if (descriptor != null && !IsNullOrEmpty(descriptor.Description)) { switch (level) { case Logger.CriticalLevel: case Logger.ErrorLevel: ErrorWriter.WriteLine(descriptor.Description); break; default: Writer.WriteLine(descriptor.Description); break; } } // Error Level will have been Reported. return(level != DefaultErrorLevel); }
public JsonResult LoginPost(string userName, string pass) { int flag = FlagStatus.ServerError; try { string MD5Pass = Lib.Encrypt(pass); UserListBL uBL = new UserListBL(); //UserModel usermodel = new UserModel(); if (userName != string.Empty && pass != string.Empty) { var user = uBL.GetUserByUserPass(userName, MD5Pass); if (user != null)//nếu tồn tại trong hệ thống thì get DB xem ở nhóm nào, quyền gì { var usermodel = uBL.GetPermission_ByUserName(userName); FormsAuthentication.SetAuthCookie(JsonConvert.SerializeObject(usermodel, Formatting.None), false); flag = FlagStatus.Success; } else { flag = FlagStatus.DataNotFound; } } } catch (Exception ex) { ErrorWriter.WriteLog(Server.MapPath("~"), "[LoginPost]", ex.ToString()); return(Json(flag, JsonRequestBehavior.AllowGet)); } return(Json(flag, JsonRequestBehavior.AllowGet)); }
/// <summary> /// API call to add a Booking /// </summary> /// <param name="newRest"> New Booking </param> public string AddBooking(Booking newBook) { if (newBook == null) { ErrorWriter.InvalidArgumentsError(); return(null); } try { var request = new RestRequest($"{bookPrefix}", Method.POST) { RequestFormat = DataFormat.Json }; request.AddJsonBody(newBook); var response = client.Execute(request); CheckStatusCode(response); return(response.Content); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
public string GetjsonInfo(string strMethod, string inputJson) { var res = ""; try { string urlAddress = string.Empty; urlAddress = ConfigurationManager.AppSettings["serviceURL"]; WebClient client = new WebClient(); client.Headers["Content-type"] = "application/json"; client.Encoding = Encoding.UTF8; ServicePointManager.MaxServicePointIdleTime = 1000; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; res = client.UploadString(urlAddress + strMethod, inputJson); JavaScriptSerializer jsJson = new JavaScriptSerializer(); jsJson.MaxJsonLength = 2147483644; return(res); } catch (Exception ex) { res = ex.Message.ToString(); ErrorWriter.WriteLog(ex.GetType().ToString(), ex.GetType().Name.ToString(), ex.InnerException.ToString(), "UserRepository_GetjsonInfo", strMethod); return(res); } }
/// <summary> /// API call to change the Status of a Booking /// </summary> /// <param name="bookId"> Booking Id </param> /// <param name="bookStatusId"> Booking Status Id </param> public bool ChangeBookStatus(string bookId, string bookStatusId) { if (string.IsNullOrEmpty(bookId) || string.IsNullOrEmpty(bookStatusId)) { ErrorWriter.InvalidArgumentsError(); return(false); } try { var request = new RestRequest($"{bookPrefix}/{bookId}/change-status?status={bookStatusId}", Method.POST); var response = client.Execute(request); // Throw an exception if the StatusCode is different from 200 CheckStatusCode(response); return(true); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }
/// <summary> /// API call to change the Status of a Mechanic /// </summary> /// <param name="mechId"> User Id </param> /// <param name="statusId"> User Status Id </param> public bool ChangeMechStatus(string mechId, string statusId) { if (string.IsNullOrEmpty(mechId) || string.IsNullOrEmpty(statusId)) { ErrorWriter.InvalidArgumentsError(); return(false); } try { string url = $"{prefix}/mechanics/{mechId}/change-status?status={statusId}"; var request = new RestRequest(url, Method.POST); var response = client.Execute(request); // Throw an exception if the StatusCode is different from 200 CheckStatusCode(response); return(true); } catch (Exception e) { ErrorWriter.ExceptionError(e); throw e; } }