public IHttpActionResult Create(DataDto data) { try { foreach (ImageDto imageDto in data.Data) { Image newImage = new Image(); newImage.name = imageDto.Name; newImage.url = imageDto.Url; newImage.page = GetPageNo(); newImage.requestCount = 0; db.Images.Add(newImage); db.SaveChanges(); } return(Ok("Created")); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } }
// POST api/<controller> public void Post([FromBody] DataDto value) { if (value == null) { return; } }
public void Post([FromBody] DataDto dataDto) { if (dataDto.data.Length > 0) { using (var random = new RNGCryptoServiceProvider()) { // store the retrieved value in redis var redisKey = Configuration["RedisKey"]; var redisUrl = Configuration["RedisURL"]; ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(string.Format("{0},abortConnect=false,ssl=true,password={1}", redisUrl, redisKey)); IDatabase cache = connection.GetDatabase(); // Perform cache operations using the cache object... // Simple put of integral data types into the cache cache.StringSet("receivedValue", dataDto.data); var key = new byte[16]; random.GetBytes(key); byte[] result = Encryption.EncryptStringToBytes_Aes(dataDto.data, key); string decryptedResult = Encryption.DecryptStringFromBytes_Aes(result, key); } } }
public static async Task <HttpData <T[]> > GetDataAsync <T>(this HttpApiClient client, string library, string method, object[] values) { T[] result = null; HttpData <string> data = await client.GetRawDataAsync(library, method, values); if (CheckDataContent(data)) { DataDto <T> dto = null; try { dto = JsonConvert.DeserializeObject <DataDto <T> >(data.Content); } catch (Exception ex) { client.OnErrorOccured(new HttpErrorEventArgs( ex, data.RequestUri.ToString(), HttpVerb.Get, "Invalid response format. JSON expected.")); data.SetSuccessFlag(false); } if (dto != null && dto.Data != null) { result = dto.Data; } } return(new HttpData <T[]>(data, result)); }
public string Post([FromBody] DataDto value) { string id = Guid.NewGuid().ToString(); _data[id] = value.Data; return(id); }
public LocationDto GetLocalization(DataDto dto) { IConfigurationSection googleMapsSection = _configuration.GetSection("Integrations:Google"); var apiKey = googleMapsSection["ApiKey"]; GoogleSigned.AssignAllServices(new GoogleSigned(apiKey)); var request = new GeocodingRequest { Address = dto.Address }; var response = new GeocodingService().GetResponse(request); var result = response.Results.FirstOrDefault(); if (result != null) { return(new LocationDto { Latitude = result.Geometry.Location.Latitude, Longitude = result.Geometry.Location.Longitude }); } return(null); }
public async Task <IHttpActionResult <string> > Import([FromBody] DataDto data) { try { int importedAdj = 0; int importedNoun = 0; foreach (AdjectiveReadDto adjDto in data.Adjectives) { Adjective adj = new Adjective { Value = adjDto.Value, CreationDate = DateTime.Now, ModificationDate = DateTime.Now }; await _adjService.CreateAsync(adj); importedAdj++; } foreach (NounReadDto nounDto in data.Nouns) { Noun noun = new Noun { Value = nounDto.Value, CreationDate = DateTime.Now, ModificationDate = DateTime.Now }; await _nounService.CreateAsync(noun); importedNoun++; } return(Ok <string>("Imported " + importedAdj + " adjective(s) and " + importedNoun + " noun(s).")); } catch { return(InternalServerError <string>("Could not import.")); } }
public static async Task <TResult> CampaignGroupWithVoice(string apiUrl, DataDto data) { TResult result = null; using var httpClient = new HttpClient(); using var request = new HttpRequestMessage( new HttpMethod("POST"), $"{apiUrl}") { Content = new StringContent(HelperExtention.ToDynamicJson(data)) }; request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse($"{Constant.GatewayMediaTypeJson}"); var response = await httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); await response.Content.ReadAsStringAsync().ContinueWith(x => { if (x.IsFaulted) { if (x.Exception != null) { throw x.Exception; } } result = JsonConvert.DeserializeObject <TResult>(x.Result); }); return(result); }
public string Post([FromBody] DataDto value) { string id = Guid.NewGuid().ToString(); RedisHelper.Instance.Set(id, value.Data); RabbitMqHelper.Instance.SendMessage(id); return(id); }
public static void ProcessFile(string path) { Console.WriteLine("Processing file '{0}'.", path); DataExtractor de = new DataExtractor(path); DataDto data = de.GetData(); DataPersistor.SaveDataToDatabase(data); Console.WriteLine(" -- Processed file." + Environment.NewLine); }
public ResultDto GetMoreInformations(DataDto dto) { var informations = _smartyStreetsService.GetInformations(dto); var location = _googleMapsService.GetLocalization(dto); return(new ResultDto { Informations = informations, Location = location }); }
public string Post([FromBody] DataDto value) { string id = Guid.NewGuid().ToString(); Redis.Instance.Database.StringSet(id, value.Data); const string exchangeName = "backend-api"; _rabbitMq.ExchangeDeclare(exchangeName, ExchangeType.Fanout); _rabbitMq.PublishToExchange(exchangeName, id); return(id); }
public IHttpActionResult ObterDataTrabalhoFuncionario(int id) { using (var sessao = new GDATransaction()) { var dataTrabalho = new DataDto { Data = FuncionarioDAO.Instance.ObtemDataAtraso(sessao, (uint)id), }; return(this.Item(dataTrabalho)); } }
public IActionResult EntryInputAction([FromBody] DataDto dataDto) { Entry entry = new Entry(); entry.Title = dataDto.Title; entry.Content = dataDto.Content; _IUnitOfWork.EntryRepository.Insert(entry); _IUnitOfWork.Complete(); return(new JsonResult("ok")); }
public void ExecuteAndGetResultSteps() { const long vertId = 987654; const string queryName = "Trav-vertices-withid"; string pathText = "Vertices/WithId(" + vertId + ")"; const string expectScript = "g.V.has(_P, Tokens.T.eq, _P)[0..99];"; var expectValues = new List <object> { DbName.Vert.Vertex.VertexId, vertId }; var dto = new DataDto(); dto.Id = "A"; dto.VertexType = VertexType.Id.Vertex; dto.Properties = new Dictionary <string, string>(); dto.Properties.Add(DbName.Vert.Vertex.VertexId, vertId + ""); dto.Properties.Add(DbName.Vert.Vertex.VertexType, (byte)dto.VertexType + ""); dto.Properties.Add(DbName.Vert.Vertex.Timestamp, "1236546735"); var vertDtos = new List <IDataDto> { dto }; var mockRes = new Mock <IDataResult>(MockBehavior.Strict); mockRes.Setup(x => x.ToDtoList()).Returns(vertDtos); vMockData .Setup(x => x.Execute(It.IsAny <WeaverQuery>(), queryName)) .Returns(mockRes.Object) .Callback((IWeaverQuery q, string name) => TestUtil.CheckWeaverScript(q, expectScript, "_P", expectValues)); IList <FabElement> result = vOper.Execute(vMockOpCtx.Object, pathText); Assert.NotNull(result, "Result should be filled."); Assert.AreEqual(1, result.Count, "Incorrect result count."); Assert.AreEqual(typeof(FabVertex), result[0].GetType(), "Incorrect result[0] type."); FabVertex v = (FabVertex)result[0]; Assert.AreEqual(vertId, v.Id, "Incorrect result[0].Id."); //// IList <FabTravStep> resultSteps = vOper.GetResultSteps(); Assert.NotNull(resultSteps, "Result steps should be filled."); Assert.Less(0, resultSteps.Count, "Incorrect result steps count."); }
public IEnumerable <WeatherForecast> Post([FromBody] DataDto dto) { var sample = dto.Data; var rng = new Random(); return(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray()); }
public static DataDto MapDataToDto(Models.Data data) { var dataDto = new DataDto { Latitude = data.Latitude, Longitude = data.Longitude, Time = data.Time, Line = data.Line, Brigade = data.Brigade }; return(dataDto); }
public string Post([FromBody] DataDto value) { string textId = Guid.NewGuid().ToString(); Redis.Instance.SetDatabase(Redis.Instance.CalculateDatabase(textId)); Redis.Instance.Database.StringSet($"{ConstantLibrary.Redis.Prefix.Text}{textId}", value.Data); Console.WriteLine($"'{ConstantLibrary.Redis.Prefix.Text}{textId}: {value.Data}' to redis database({Redis.Instance.Database.Database})"); const string exchangeName = "backend-api"; _rabbitMq.ExchangeDeclare(exchangeName, ExchangeType.Fanout); _rabbitMq.PublishToExchange(exchangeName, textId); return(textId); }
public string Post([FromBody] DataDto value) { string textId = Guid.NewGuid().ToString(); Redis.Instance.SetDatabase(Redis.Instance.CalculateDatabase(textId)); Console.WriteLine($"'{ConstantLibrary.Redis.Prefix.Text}{textId}: {value.Data}' to redis database({Redis.Instance.Database.Database})"); Redis.Instance.Database.StringSet($"{ConstantLibrary.Redis.Prefix.Text}{textId}", value.Data); Console.WriteLine($"{textId} to {_publishExchangeName} exchange"); _rabbitMq.PublishToExchange(_publishExchangeName, textId); return(textId); }
public async Task <IHttpActionResult <DataDto> > GetAll() { try { var adjList = await _adjService.ReadAllAsync(); var nounList = await _nounService.ReadAllAsync(); DataDto data = new DataDto(adjList, nounList); return(Ok(data)); } catch { return(InternalServerError <DataDto>(new DataDto())); } }
private List <DataDto> ParseData(XElement[] elements) { List <DataDto> results = new List <DataDto>(); foreach (XElement element in elements) { var data = new DataDto { Number = int.Parse(element.Attribute("number").Value), String = element.Attribute("string").Value, }; results.Add(data); } return(results); }
public DataDto GetDto(ObjRef o) { var dict = o.Object().Attributes.UserDictionary; var dataDto = new DataDto { EtakId = Convert.ToInt32(dict.Where(x => x.Key == ETAK_ID).FirstOrDefault().Value), Address = dict.Where(x => x.Key == EHR_ID).FirstOrDefault().Value.ToString(), ApartmentsCount = Convert.ToInt32(dict.Where(x => x.Key == APARTMENTS_PERHOUSE).FirstOrDefault().Value), EhrId = Convert.ToInt32(dict.Where(x => x.Key == EHR_ID).FirstOrDefault().Value), GovernmentOwnedCount = Convert.ToInt32(dict.Where(x => x.Key == GOVERNMENT_OWNED_COUNT).FirstOrDefault().Value), LivingAreaPerHouse = Convert.ToInt32(dict.Where(x => x.Key == LIVING_AREA_PERHOUSE).FirstOrDefault().Value), NoElectricityPercent = Convert.ToInt32(dict.Where(x => x.Key == ELECTRICITY_WITHOUT_CONTRACT_PERCENT).FirstOrDefault().Value), UnInhabitedPercent = Convert.ToInt32(dict.Where(x => x.Key == UNINHABITED_PERCENT).FirstOrDefault().Value), }; return(dataDto); }
public InformationsDto GetInformations(DataDto dto) { IConfigurationSection smartyAuthNSection = _configuration.GetSection("Integrations:SmartyStreets"); var authId = smartyAuthNSection["Id"]; var authToken = smartyAuthNSection["Token"]; var client = new ClientBuilder(authId, authToken).BuildInternationalStreetApiClient(); Lookup lookup = new Lookup(dto.Address, dto.Country); client.Send(lookup); var candidates = lookup.Result; var candidate = candidates.FirstOrDefault(); return(candidate != null ? GetInformationsDto(candidate.Components) : null); }
public object Validar(UserDto user) { var data = new DataDto(); var validarUser = db.Users.Where(x => x.Password == user.Password && x.Email == user.Email).FirstOrDefault(); if (validarUser != null) { data.Resultado = true; data.Mensaje = "Bienvenido al Sistema"; } else { data.Resultado = false; data.Mensaje = "Los datos ingresados no son validos"; } return(data); }
public static async Task <TResult> CampaignWithVoice(string apiUrl, DataDto data) { TResult result = null; using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("POST"), $"{apiUrl}"); var multipartContent = new MultipartFormDataContent(); foreach (var t in data.Recipient) { multipartContent.Add(new StringContent(t), "recipient[]"); } var voiceId = data.VoiceId ?? ""; var scheduleDate = data.ScheduleDate ?? ""; multipartContent.Add(new ByteArrayContent(await File.ReadAllBytesAsync(data.File)), "file", Path.GetFileName(data.File)); multipartContent.Add(new StringContent(voiceId), "voice_id"); multipartContent.Add(new StringContent(data.IsSchedule.ToString()), "is_schedule"); multipartContent.Add(new StringContent(scheduleDate), "schedule_date"); multipartContent.Add(new StringContent(data.Campaign), "campaign"); request.Content = multipartContent; var response = await httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); await response.Content.ReadAsStringAsync().ContinueWith(x => { if (x.IsFaulted) { if (x.Exception != null) { throw x.Exception; } } result = JsonConvert.DeserializeObject <TResult>(x.Result); }); return(result); }
private IMessageType Parse(DataDto dataDto) { if (dataDto.Value.StartsWith("@")) { return(new AdminMessageType()); } else if (dataDto.Value.StartsWith("/")) { return(new CommandMessageType()); } else if (dataDto.Value.StartsWith("http://you")) { return(new YoutubeMessageType()); } else if (dataDto.Value.StartsWith("http://wiki")) { return(new WikiMessageType()); } return(null); }
public DataDto Get() { var zipkinConfig = ZipkinSetup(); var context = System.Web.HttpContext.Current.GetOwinContext(); var zipkinClient = new ZipkinClient(zipkinConfig, context); AccountDto acct = null; using (var httpClient = new HttpClient(new ZipkinMessageHandler(zipkinClient))) { var response = httpClient.GetAsync("http://channel.ZipkinLab.localmachine.altsrc.net/account/9999").Result; if (response.IsSuccessStatusCode) { var content = response.Content.ReadAsStringAsync().Result; acct = JsonConvert.DeserializeObject <AccountDto>(content); } } using (var httpClient = new HttpClient(new ZipkinMessageHandler(zipkinClient))) { var sharedResponse = httpClient.GetAsync($"http://shared.ZipkinLab.localmachine.altsrc.net/api/shared/3").Result; if (sharedResponse.IsSuccessStatusCode) { var sharedContent = sharedResponse.Content.ReadAsStringAsync().Result; } } var dataDto = new DataDto(acct.Customer.FirstName, acct.Customer.LastName, acct.AccountId); var span = new Span(); //span.Id = ??? zipkinClient.RecordBinary <object>(span, "correlationId", Guid.NewGuid().ToString("N")); return(dataDto); }
public IActionResult CreateUser(DataDto userModel) { try { var user = _mapper.Map <Data>(userModel); var adduser = _userService.CreateUser(user, userModel.Password); if (adduser == null) { return(BadRequest(new { message = "Cannot be empty" })); } return(Ok(userModel)); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
public List <DataDto> GetDataList(string serviceTrade, DateTime startDate, DateTime endDate, string projectName, string projectShortName, List <HeaderDto> list_Header, List <LeftDto> list_Left) { List <DataDto> listData = new List <DataDto>(); List <FlowOrderDto> List_flowOrder = FlowOrderSearchByDate(serviceTrade, startDate, endDate, projectName, projectShortName); foreach (HeaderDto header in list_Header) { foreach (LeftDto left in list_Left) { DataDto data = new DataDto(); data.ProjectId = left.ProjectId; decimal?sumAmt = 0; foreach (FlowOrderDto flowOrder in List_flowOrder) { if (flowOrder.ProjectId == left.ProjectId && flowOrder.PayTime <= header.EndDate && flowOrder.PayTime >= header.StartDate) { sumAmt += flowOrder.PayAmt; if (flowOrder.PaymentType == "预付款" || flowOrder.PaymentType == "押金") { data.AdvancePaymentChk = true; } if (flowOrder.FactChk == "1") { data.FactPayChk = true; } } } data.SumAmt = sumAmt; listData.Add(data); } } return(listData); }
public async Task <ResponseDto> NotifyAsync(string message, string title, string[] recipient, string sender, string scheduleDate, bool isSchedule = false, Attachment attachments = null) { //init data object var data = new DataDto { Message = message, Recipient = recipient, Sender = sender, ScheduleDate = scheduleDate, IsSchedule = isSchedule, File = attachments?.File, Campaign = title }; var scopeFactory = _services .BuildServiceProvider() .GetRequiredService <IServiceScopeFactory>(); var stream = await CreateStream(scopeFactory, data); if (!HelperExtention.IsNullAttachment(attachments)) { _campaign = await ApiCallHelper <ResponseDto> .CampaignWithVoice( $"{Constant.MnotifyGatewayJsonEndpoint}/voice/quick?key={ApiKey}", data ); await InsertOrUpdateRecord(scopeFactory, stream); return(_campaign); } if (!HelperExtention.IsNullGroupWithMessage(null, null)) { _campaign = await ApiCallHelper <ResponseDto> .CampaignGroup( $"{Constant.MnotifyGatewayJsonEndpoint}/sms/group?key={ApiKey}", data ); await InsertOrUpdateRecord(scopeFactory, stream); return(_campaign); } if (!HelperExtention.IsNullAttachmentWithGroup(attachments, null)) { _campaign = await ApiCallHelper <ResponseDto> .CampaignGroupWithVoice( $"{Constant.MnotifyGatewayJsonEndpoint}/voice/group?key={ApiKey}", data ); await InsertOrUpdateRecord(scopeFactory, stream); return(_campaign); } _campaign = await ApiCallHelper <ResponseDto> .Campaign( $"{Constant.MnotifyGatewayJsonEndpoint}/sms/quick?key={ApiKey}", data ); await InsertOrUpdateRecord(scopeFactory, stream); return(_campaign); }