public void BeforeAll() { // Arrange _emailAddressSubmitted = "*****@*****.**"; _genericResponse = new GenericResponse(true,"some message"); _program = MockRepository.GenerateStub<AlphaProgram>(); _program.Stub(p => p.SaveInterestedCustomer(Arg<string>.Is.Anything)).Return(_genericResponse); var controller = new CustomerController(_program); // Act _result = controller.SubmitCustomerEmail(new SubmitCustomerEmailModel {CustomerEmail = _emailAddressSubmitted}); _responseData = _result.Data as JsonResponse; }
public static GenericResponse deleteProduct(int idUser, int idProduct) { GenericResponse ret = new GenericResponse(); Dictionary<string, object> parameters = new System.Collections.Generic.Dictionary<string, object>(); parameters.Add("idUser", idUser); parameters.Add("idProducto", idProduct); DataSet result; try { result = DataAccess.executeStoreProcedureDataSet("Spr_delete_product", parameters); if (null != result) { //Verificando respuesta if ((int)result.Tables[0].Rows[0]["Success"] == 1) { string carpeta = string.Empty; parameters.Clear(); parameters.Add("idUser", idUser); carpeta = DataAccess.executeStoreProcedureString("spr_Get_InfoLogo", parameters); if (!String.IsNullOrEmpty(carpeta)) { string PathDocs = ConfigurationManager.AppSettings["EmpresasFiles"]; string inicio = HttpContext.Current.Server.MapPath( PathDocs ); string directorioFisico = inicio + carpeta + "\\products\\" + idProduct; //Si ok Eliminando fotos foreach ( DataRow row in result.Tables[1].Rows ) { if (System.IO.File.Exists(directorioFisico + "\\" + (string)row["nombreArchivo"] )) File.Delete(directorioFisico + "\\" + (string)row["nombreArchivo"]); if (System.IO.File.Exists(directorioFisico + "\\small_" + (string)row["nombreArchivo"])) File.Delete(directorioFisico + "\\small_" + (string)row["nombreArchivo"]); } } } } } catch (Exception ex) { ret.success = false; ret.message = ex.Message; } return ret; }
public async Task Should_Perform_Basic_Rpc_For_Generic_Message_Types() { /* Setup */ var response = new GenericResponse<First, Second> { Prop = "This is the response." }; var requester = BusClientFactory.CreateDefault(); var responder = BusClientFactory.CreateDefault(); responder.RespondAsync<GenericRequest<First,Second>, GenericResponse<First,Second>>((req, i) => { return Task.FromResult(response); }); /* Test */ var recieved = await requester.RequestAsync<GenericRequest<First, Second>, GenericResponse<First, Second>>(); /* Assert */ Assert.Equal(expected: response.Prop, actual: recieved.Prop); }
public static GenericResponse deleteCategory(int idUser, int idCategory) { GenericResponse ret = new GenericResponse(); Dictionary<string, object> parameters = new System.Collections.Generic.Dictionary<string, object>(); parameters.Add("idUser", idUser); parameters.Add("idCategoria", idCategory); DataSet result; try { result = DataAccess.executeStoreProcedureDataSet("Spr_delete_category", parameters); } catch (Exception ex) { ret.success = false; ret.message = ex.Message; } return ret; }
public GenericResponse<List<Product>> TumUrunler() { var result = new GenericResponse<List<Product>>(); var postData = new List<KeyValuePair<string, string>>(); //postData.Add(new KeyValuePair<string, string>("userId", "5")); // servise geçirmek istediğimiz parametreleri bu sekilde ekliyoruz //postData.Add(new KeyValuePair<string, string>("keyword", "engin")); //postData.Add(new KeyValuePair<string, string>("count", "15")); var parameters = new HttpFormUrlEncodedContent(postData); client.PostAsync(new Uri("http://yazokulu2015webservice.azurewebsites.net/urunler/tumu"), parameters) .AsTask().ContinueWith(response => { result = JsonConvert.DeserilizeObject<GenericResponse<List<Product>>>(response.Result); } ).Wait(); return result; }
public string ResivirData(UsuarioRequest request) { GenericResponse _resonse = new GenericResponse(); _operation = GerenteOperacion.GenerarOperacion(); _conectorNegocio = new NegocioObtenerDatos(); bool estado = false; try { Informacion.LogInformacion(LogManager.GetCurrentClassLogger(), " [ " + GerenteLog.GetObtenerMetodo() + " ] -- [ " + _operation + " ] REQUEST: " + GerenteJson.SerializeObject(request)); if (ModelState.IsValid) { _resonse = _conectorNegocio.VerificarCanal(request.Canal, request.PassCanal, _operation, ref estado); if (!estado) { return(GerenteJson.SerializeObject(_resonse)); } _resonse = _conectorNegocio.MandarDatosUsuario(request, _operation); Informacion.LogInformacion(LogManager.GetCurrentClassLogger(), " [ " + GerenteLog.GetObtenerMetodo() + " ] -- [ " + _operation + " ] RESPONSE: " + GerenteJson.SerializeObject(_resonse)); } else { var errors = string.Join(" | ", ModelState.Values .SelectMany(v => v.Errors) .Select(e => e.ErrorMessage)); _resonse.mensaje = Convert.ToString(errors); return(GerenteJson.SerializeObject(_resonse)); } } catch (Exception ex) { Informacion.LogError(LogManager.GetCurrentClassLogger(), " [ " + GerenteLog.GetObtenerMetodo() + " ] -- [ " + _operation + " ]. Se genero un error en Recibir los datos.", ex); } return(JsonConvert.SerializeObject(_resonse)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, [Inject] IContactRepository repo, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string requestId = req.Query["request_id"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); IActionResult response; if (req.Method.ToLower() == "get") { var query = await repo.GetAllAsync(); var listOfContacts = query.Skip(0).Take(25).ToList(); var result = new GenericResponse <IEnumerable <ContactDto> >(true, listOfContacts.Select(o => new ContactDto { Id = o.Id, Names = o.Names })) { RequestId = requestId ?? data?.request_id }; response = new OkObjectResult(result); } else { response = new OkObjectResult(""); } return(response); }
/// <summary> /// overridable data binding method. /// </summary> protected virtual void NidoDataBinding() { this.Items.Clear(); GenericResponse <IEnumerable <E> > response = myHandler.GetAllGeneric(); if (response.Successful) { IEnumerable <E> list = response.Result; //if (list.Count() > 0) //{ foreach (E item in list) { //this.Items.Add(new ListItem(item.Text, item.Value)); this.Items.Add(new ListItem(item.Text, item.Value)); } this.SelectedValue = this.Items[0].Value; //} } else { throw response.CurrentException; } }
public async Task <IActionResult> Data([FromRoute] string projectType, [FromRoute] string id) { var projectId = $"{projectType}/{id}"; _logger.LogInformation("Dummy data url test for {projectId}", projectId); using var session = _documentStore.OpenAsyncSession(); //var user = await _platformAdminUserManager.GetByUniqueIdentifierAsync(User.Identity.Name, session); var testMode = TestProjectId.IsValidIdentity(projectId) && !ProjectId.IsValidIdentity(projectId); var project = testMode ? await _projectManager.GetTest((TestProjectId)projectId, session) : await _projectManager.Get((ProjectId)projectId, session); var payload = DummyPayload(project.Name, project.Applications.FirstOrDefault()?.SecretKey); try { var result = await _applicationTestHttpClient.SendDataTest(project.Applications.First(), payload); return(Ok(result)); } catch (Exception ex) { _logger.LogError(ex, "Unable to test application. {@request}", projectId); return(Ok(GenericResponse.Failed(ex.Message, System.Net.HttpStatusCode.BadRequest))); } }
public GenericResponse BuildRefundResponse(GenericResponse response, string responseString) { var resObj = new PrintecResponse(); string[] valuesArray; //valuesArray = responseString.Split((char)0x1C); //resObj.SystemId = valuesArray[0]; //resObj.TransactionType = valuesArray[1]; //resObj.NOInstallments = Int32.Parse(valuesArray[2]); //resObj.NoOfPostdatedMonths = Int32.Parse(valuesArray[3]); //resObj.TerminalIdentification = valuesArray[4]; //resObj.BatchNumber = Int32.Parse(valuesArray[5]); //resObj.ResponseCode = valuesArray[6]; //resObj.OriginalAmountOrBatchTotalNetAmount = decimal.Parse(valuesArray[7]); //resObj.ModifiedAmount = decimal.Parse(valuesArray[8]); //resObj.RetrievalReferenceNumber = valuesArray[9]; //resObj.TransReferNumberOrBatchTotalCounter = valuesArray[10]; //resObj.AuthCode = valuesArray[11]; //resObj.AccountNumber = valuesArray[12]; //resObj.ExpirationDate = DateTime.Parse(valuesArray[13]); //resObj.CardholderName = valuesArray[14]; //resObj.DCCTransactionAmount = valuesArray[15]; //resObj.DCCCurrency = valuesArray[16]; //resObj.DCCMarkUpPercentage = valuesArray[17]; //resObj.DCCExchangeDateOfRate = valuesArray[18]; //resObj.ResponseTextMessage = valuesArray[19]; //resObj.CardProductName = valuesArray[20]; //resObj.OriginalResponseCode = valuesArray[21]; //resObj.FirstInstallmentDate = DateTime.Parse(valuesArray[22]); //resObj.NetAmount = valuesArray[23]; //resObj.ExpirationDate = DateTime.Parse(valuesArray[24]); //resObj.ExpirationDate = DateTime.Parse(valuesArray[25]); //resObj.ExpirationDate = DateTime.Parse(valuesArray[26]); //response.Result.ResponseCode = resObj.ResponseCode; return(response); }
public GenericResponse SplitString(string[] dirArray) { var result = new GenericResponse(); try { char[] separator = { '_' }; if (dirArray != null) { // based on folder structure of var publicHtml = dirArray[0]; var likelyChapter = dirArray[1]; var firstChar = likelyChapter.Substring(0, 1); if (firstChar.All(char.IsDigit)) { //it's a chapter var chapterArray = likelyChapter.Split(separator); if (chapterArray != null) { result.Value = chapterArray[0]; result.Text = chapterArray[1]; result.Status = "OK"; } } } } catch (Exception ex) { result.Text = ex.Message; result.Value = ex.StackTrace; result.Status = "ERROR"; } return(result); }
public GenericResponse <AccessToken> CreateAccessTokenByRefreshToken(string refreshToken) { GenericResponse <TUser> userResponse = userService.GetUserWithRefreshToken(refreshToken); if (userResponse.Success) { if (userResponse.Object.RefreshTokenEndDate > DateTime.Now) { AccessToken accessToken = tokenHandler.CreateAccessToken(userResponse.Object); userService.SaveRefreshToken(userResponse.Object.TUserId, accessToken.RefreshToken); return(new GenericResponse <AccessToken>(accessToken)); } else { return(new GenericResponse <AccessToken>("refreshtoken suresi dolmus")); } } else { return(new GenericResponse <AccessToken>("refreshtoken bulunamadı")); } }
private async void ActuallyWaitlist() { var dialog = DialogHelper.CreateProgressDialog("Please wait...", this); dialog.Show(); GenericResponse response = null; cts.Cancel(); response = await Services.Workshop.JoinWaitlist(session.Id); dialog.Hide(); if (response.Success) { DialogHelper.ShowDialog(this, "You have been placed on the waitlist successfully", "Success"); isWaitlisted = true; FindViewById <RelativeLayout>(Resource.Id.notifications).Visibility = ViewStates.Gone; } else { DialogHelper.ShowDialog(this, response.Message, response.Title); } UpdateButtons(); }
public bool AddScore() //AddScore API call { try { using (Client rpcClient = new Client(LittleTiggy.LeaderBoardAPIEndpoint, LittleTiggy.apiTimeOut)) { Debug.WriteLine("API Endpoint:" + LittleTiggy.LeaderBoardAPIEndpoint); Debug.WriteLine("Player name to send: " + this.name); JArray parameters = JArray.Parse(@"['" + this.name + @"', '" + this.score + @"', '" + this.difficulty + "']"); Request request = rpcClient.NewRequest("app.AddScore", parameters); GenericResponse response = rpcClient.Rpc(request); if (response.Result != null) { JToken result = response.Result; Debug.WriteLine(result); return(true); } else { Debug.WriteLine("Error in response! Error code: {0}", response.Error.Code); return(false); } } } catch (System.Exception ex) { LittleTiggy.bDisableNetworkCalls = true; Debug.WriteLine("Unable to connect to API endpoint"); Debug.WriteLine(ex.ToString()); return(false); } }
public override GenericResponse <T> GetByID(GenericRequest <T> Request) { GenericResponse <T> response = new GenericResponse <T>(); try { response.Entity = _context.Set <T>().Find(Request.ID); if (response.Entity == null) { response.Result_Type = CoreEnum.Result_Type.NoData; } else { response.Result_Type = CoreEnum.Result_Type.Success; } } catch (Exception ex) { response.Result_Type = CoreEnum.Result_Type.Failed; response.Message = ex.Message.ToString(); } return(response); }
public IActionResult Get([FromRoute(Name = "id")] int id) { Log.Information($"Calling get applicant by id api for id : {id}"); Applicant applicant = _applicantDataService.Get(id); if (applicant == null) { Log.Warning($"Applicant with id : {id} cannot be found"); GenericResponse failureResponse = new GenericResponse { Success = false }; return(new NotFoundObjectResult(failureResponse)); } Log.Information("Applicant found"); ApplicantViewModel mappedApplicant = _mapper.Map <ApplicantViewModel>(applicant); Log.Information("Applicant mapped"); DataGenericResponse <ApplicantViewModel> response = new DataGenericResponse <ApplicantViewModel> { Success = true, Data = mappedApplicant }; Log.Information("Request completed"); return(new OkObjectResult(response)); }
public GenericResponse <InfoPrincipalModel> InfoPrincipal() { GenericResponse <InfoPrincipalModel> response = new GenericResponse <InfoPrincipalModel>(); JwtDecodeModel model = (JwtDecodeModel)Thread.CurrentPrincipal; try { bool esVendedor = false; esVendedor = model.Roles.Count() == 1 && model.IsInRole("Vendedor"); ProductoServicio prodServicio = new ProductoServicio(); VentaServicio ventServicio = new VentaServicio(); ClienteServicio cliServicio = new ClienteServicio(); PromocionServicio promServicio = new PromocionServicio(); InfoPrincipalModel data = new InfoPrincipalModel(); data.CantClientes = cliServicio.Listar("").Count(); data.CantProductos = prodServicio.Listar("", 0).Count(); data.CantVentas = esVendedor ? ventServicio.Listar("", model.Id).Count() : ventServicio.Listar("", 0).Count(); data.CantUsuarios = esVendedor ? 0 : servicio.Listar("").Count(); data.PromosActuales = promServicio.Listar("", 1); data.ProdBajoStock = prodServicio.Listar("", 1); response.Data = data; response.Codigo = 200; // OK response.Error = false; response.Mensaje = "OK"; } catch (Exception ex) { throw new CustomResponseException(ex.Message, 500); } return(response); }
public async static Task <GenericResponse <TOut> > PostRequest <TOut, Tin>(Uri uri, Tin model) { var outResponse = new GenericResponse <TOut>(); HttpResponseMessage response = null; var json = JsonConvert.SerializeObject(model); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { HttpClient httpClient = new HttpClient(); response = await httpClient.PostAsync(uri, content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var jsondata = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var responseModel = await Task.Run(() => JsonConvert.DeserializeObject <GenericResponse <TOut> >(jsondata) ).ConfigureAwait(false); outResponse = responseModel; } } catch (Exception e) { Console.WriteLine(e.Message); } return(outResponse); }
public GenericResponse GetPreSignedURL(string bucketName, string keyName) { string responseBody = ""; var result = new GenericResponse(); try { GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest() { BucketName = bucketName, Key = keyName, Expires = DateTime.Now.AddMinutes(2) }; string url = _client.GetPreSignedURL(request1); //return Redirect(url); responseBody = url; // Now you process the response body. result.Text = "SUCCESS"; result.Value = responseBody; } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message); result.Text = "ERROR"; result.Value = e.Message; } catch (Exception e) { result.Text = "ERROR"; result.Value = e.Message; } return(result); }
public async Task <GenericResponse <object> > RemoveRole(AddRemoveRoleDto removeRoleDto) { try { var user = await _userRepository.FindById(removeRoleDto.UserId); if (user is null) { return(new GenericResponse <object>(new object(), false).AddErrorMessage("User doesn't exists")); } var role = await _roleRepository.FindById(removeRoleDto.RoleId); var removed = user.RemoveRole(role); await _userRepository.UnitOfWork.Commit(); var response = new GenericResponse <object>(new object(), removed); if (removed) { response.AddInfoMessage("Successfully removed"); } else { response.AddErrorMessage("Cannot remove - check if role exists"); } return(response); } catch (Exception) { await _userRepository.UnitOfWork.Rollback(); throw; } }
public async Task <IActionResult> CreateWallet(string uniqueKey) { GenericResponse <Account> response = new GenericResponse <Account>(); Credentials model = new Credentials(); BlockChainController chainController = new BlockChainController(); try { var account = await chainController .CreateWallet(uniqueKey); model.UniqueKey = CustomHashing.ComputeSha256Hash(uniqueKey); model.PrimaryKey = CustomEncryption.Encrypt(account.PrivateKey, uniqueKey); _context.Credentials.Add(model); await _context.SaveChangesAsync(); if (account != null) { response.HasError = false; response.Messege = "Sucessfull"; response.Result = account; response.StatusCode = 200; } } catch (Exception e) { response.HasError = true; response.Messege = "unsucessfull"; response.Result = null; response.StatusCode = 400; } return(Ok(response)); }
public GenericResponse <StaticPage> AddStaticPagePage(StaticPage staticPage) { GenericResponse <StaticPage> response = new GenericResponse <StaticPage>(); repo.Add(staticPage); StaticPage confirm = repo.GetAll().FirstOrDefault(s => s.StaticPageTitle == staticPage.StaticPageTitle && s.StaticPageContent == staticPage.StaticPageContent && s.StaticPageImageFileName == staticPage.StaticPageImageFileName); if (confirm != null && repo.GetAll().Contains(confirm)) { response.Success = true; response.Payload = confirm; } else { response.Success = false; response.Message = "ERROR : Static Page was not entered into database."; response.Payload = staticPage; } return(response); }
public JsonResult RetrieveUserSettings(SettingsRetrieveDTO settingsDTO) { GenericResponse responseObj = null; int timeStart = DateTime.Now.TimeOfDay.Seconds; SendInfo info = null; try { info = settingsService.RetrieveSettings(settingsDTO); string message = settingsService.DeviceTokenSetting(settingsDTO, info.Id); responseObj = new GenericResponse() { Status = 0, ResponseTime = DateTime.Now.TimeOfDay.Seconds - timeStart, Message = message, Data = info, }; return(Json(responseObj, JsonRequestBehavior.AllowGet)); } catch (Exception e) { responseObj = new GenericResponse() { Status = 1, ResponseTime = DateTime.Now.TimeOfDay.Seconds - timeStart, Message = e.Message, Data = info, }; ResponseLogging(responseObj); return(Json(responseObj, JsonRequestBehavior.AllowGet)); } }
// POST api/<controller> public IActionResult Create([FromBody] dto_User Model) { GenericResponse response = new GenericResponse(); if (ModelState.IsValid) { response.FillSuccess(); FillBase(Model); if (_service_account.validate(Model)) { _service_User.CreateOREdit(Model); response.data = Model; } else { response.FillError("Already Exist"); } } else { response.FillError(); } return(Ok(response)); }
public async Task <GenericResponse <IEnumerable <Article> > > GetAllArticles() { var response = new GenericResponse <IEnumerable <Article> >(); try { using (_articleRepository) { response.Status = HttpStatusCode.OK; response.Message = "Success"; var articles = await _articleRepository.GetAllArticles(); response.Payload = articles; } } catch (Exception ex) { response.Status = HttpStatusCode.InternalServerError; response.Message = "Failed"; } return(response); }
public JsonResult Do() { using (var mem = new MemoryStream()) using (var reader = new StreamReader(mem)) { Request.Body.CopyTo(mem); var body = reader.ReadToEnd(); mem.Seek(0, SeekOrigin.Begin); Login data = (JsonConvert.DeserializeObject <Login>(reader.ReadToEnd())); BLSeguridad seguridad = new BLSeguridad(); GenericResponse <LoginResponse> login = seguridad.CheckUserPass(data.user, data.password); if (login.Result.Estado == true) { HttpContext.Session.SetString("usuario_userid", login.Result.IdUsuario.ToString()); HttpContext.Session.SetString("user", login.Result.username); } return(Json(login)); } }
public void AddGuestLogin(string operatorLogin, string loginOfGuest) { if (!LoginHasRight(operatorLogin, true, Command.AddGuest)) { return; } string nickname = GetNickname(operatorLogin); if (nickname == null) { return; } string nickofGuest = GetNickname(loginOfGuest); if (nickofGuest != null) { GenericResponse <bool> ignoreResponse = Context.RPCClient.Methods.AddGuest(loginOfGuest); if (!ignoreResponse.Erroneous && ignoreResponse.Value) { Context.RPCClient.Methods.SaveGuestList("guestlist.txt"); SendFormattedMessage(Settings.AddGuestMessage, "AdminNickname", StripTMColorsAndFormatting(nickname), "GuestNickname", StripTMColorsAndFormatting(nickofGuest)); } else { SendFormattedMessageToLogin(operatorLogin, "{[#ServerStyle]}> {[#ErrorStyle]}Could not add " + StripTMColorsAndFormatting(nickofGuest) + "to guest list"); } } else { SendNoPlayerWithLoginMessageToLogin(operatorLogin, loginOfGuest); } }
protected override async Task <GenericResponse <StoreDto> > ExecuteCore(GetByGuidRequest request) { var stores = await storeRepository.FindOne(request.Id); return(GenericResponse <StoreDto> .AsSuccess(stores.ToDto())); }
public IActionResult UpdatePerson([FromBody] PersonDto person) { GenericResponse <bool> response = personService.UpdatePerson(person); return(StatusCode(response.StatusCode, response)); }
public IActionResult SavePerson([FromBody] PersonDto person) { GenericResponse <string> response = personService.SavePerson(person); return(StatusCode(response.StatusCode, response)); }
public IActionResult GetPerson([FromBody] PersonSearchDto person) { GenericResponse <IEnumerable <PersonDto> > response = personService.GetPerson(person); return(StatusCode(response.StatusCode, response)); }
public IActionResult DeletePerson(string idPerson) { GenericResponse <bool> response = personService.DeletePerson(idPerson); return(StatusCode(response.StatusCode, response)); }
protected void ProcessCreateResponse(GenericResponse response) { _handle = response.ObjectHandle; }
protected void ProcessPrepareResponse(GenericResponse response) { Descriptor[] descriptors = new Descriptor[] { null, null }; this.ParseSqlInfo(response.Data, DescribeInfoAndBindInfoItems, ref descriptors); this.fields = descriptors[0]; this.parameters = descriptors[1]; }
protected void ProcessExecuteResponse(GenericResponse response) { // nothing to do here }
protected void ProcessAllocateResponce(GenericResponse response) { this.handle = response.ObjectHandle; this.allRowsFetched = false; this.state = StatementState.Allocated; this.statementType = DbStatementType.None; }
protected byte[] ProcessInfoSqlResponse(GenericResponse respose) { System.Diagnostics.Debug.Assert(respose.Data != null && respose.Data.Length > 0); return respose.Data; }
public static async Task <GenericResponse> GetList(string filtro = "", string ordenar_por = "", string orden = "", int Page = 1) { GenericResponse response = new GenericResponse(); try { List <CloureParam> cparams = new List <CloureParam>(); cparams.Add(new CloureParam("module", "shows_news")); cparams.Add(new CloureParam("topic", "listar")); if (filtro.Length > 0) { cparams.Add(new CloureParam("filtro", filtro)); } if (ordenar_por.Length > 0) { cparams.Add(new CloureParam("ordenar_por", ordenar_por)); } if (orden.Length > 0) { cparams.Add(new CloureParam("orden", orden)); } cparams.Add(new CloureParam("pagina", Page.ToString())); string res = await CloureManager.ExecuteAsync(cparams); JsonObject api_result = JsonObject.Parse(res); string error = api_result.GetNamedString("Error"); if (error == "") { JsonObject api_response = api_result.GetNamedObject("Response"); JsonArray registers = api_response.GetNamedArray("Registros"); foreach (JsonValue jsonValue in registers) { JsonObject register = jsonValue.GetObject(); ShowArticle item = new ShowArticle(); item.Id = (int)register.GetNamedNumber("Id"); item.Titulo = register.GetNamedString("Titulo"); JsonArray available_commands_arr = register.GetNamedArray("AvailableCommands"); item.AvailableCommands = new List <AvailableCommand>(); foreach (JsonValue available_cmd_obj in available_commands_arr) { JsonObject available_cmd_item = available_cmd_obj.GetObject(); int available_cmd_id = (int)available_cmd_item.GetNamedNumber("Id"); string available_cmd_name = available_cmd_item.GetNamedString("Name"); string available_cmd_title = available_cmd_item.GetNamedString("Title"); AvailableCommand availableCommand = new AvailableCommand(available_cmd_id, available_cmd_name, available_cmd_title); item.AvailableCommands.Add(availableCommand); } response.Items.Add(item); } response.TotalPages = (int)api_response.GetNamedNumber("TotalPaginas"); } else { throw new Exception(error); } } catch (Exception ex) { var dialog = new MessageDialog(ex.Message); await dialog.ShowAsync(); } return(response); }
protected virtual void ProcessAttachResponse(GenericResponse response) { // Save the database connection handle this.handle = response.ObjectHandle; }
protected void Page_Load(object sender, EventArgs e) { GenericRequest request; GenericResponse response = new GenericResponse(); response.error = String.Empty; // Need passed in store id and number of requested results. // 1. Deserialize the incoming Json. try { request = GetRequestInfo(); } catch (Exception ex) { response.error = ex.Message.ToString(); // Return the results as Json. SendInfoAsJson(response); return; } // Do stuff here. SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); try { connection.Open(); response.rsos = new List <string>(); string sql = String.Format("SELECT E.email FROM EventUser E, StudentOrg S WHERE S.rsoID=@rso AND S.admin=E.userID"); SqlCommand command = new SqlCommand(sql, connection); command.Parameters.Add(new SqlParameter("@rso", request.rso)); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { string adminEmail = Convert.ToString(reader["email"]); string text = System.IO.File.ReadAllText(@"C:\SwishGameRoot\JSONServices\email.config"); int startPos = text.IndexOf(">"); int endPos = text.LastIndexOf("<"); string pass = text.Substring(startPos + 1, endPos - 7); MailMessage mail = new MailMessage(); //Setting From , To and CC mail.From = new MailAddress("*****@*****.**", request.name); mail.To.Add(new MailAddress(adminEmail, "RSO Admin")); mail.Body = "Name: " + request.name + "\nEmail: " + request.email + "\nSubject: " + request.subject + "\nBody: " + request.body; mail.Sender = new MailAddress(request.email, request.name); mail.Subject = request.subject; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; try { SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587); smtpClient.EnableSsl = true; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", pass); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Send(mail.From.ToString(), mail.To.ToString(), mail.Subject, mail.Body); } catch (SmtpException ex) { string msg = "Mail cannot be sent: "; msg += ex.Message; response.error = msg; SendInfoAsJson(response); return; } } if (response.error != "") { SendInfoAsJson(response); return; } /* #if CRAP * response.error = sql; * SendInfoAsJson(response); * return; #endif */ } catch (Exception ex) { response.error = ex.Message.ToString(); } finally { if (connection.State == ConnectionState.Open) { connection.Close(); } } SendInfoAsJson(response); }
protected void ProcessCreateResponse(GenericResponse response) { this.handle = response.ObjectHandle; }