public async Task <IResponse <bool> > NotifyAsync(NotificationDto notifyDto) { try { using var http = new HttpClient(); http.DefaultRequestHeaders.Add("Token", _configuration["CustomSettings:NotifierToken"]); var notify = await http.PostAsync(_configuration["CustomSettings:NotifierUrl"], new StringContent(notifyDto.SerializeToJson(), Encoding.UTF8, "application/json")); if (!notify.IsSuccessStatusCode) { return new Response <bool> { Message = ServiceMessage.Error } } ; return((await notify.Content.ReadAsStringAsync()).DeSerializeJson <Response <bool> >()); } catch (Exception e) { FileLoger.Error(e); return(new Response <bool> { Message = ServiceMessage.Error }); } }
public async Task <IResponse <string> > DeleteAsync(int id) { try { var asset = await _lossAssetRepo.FindAsync(id); if (asset == null) { return new Response <string> { Message = ServiceMessage.RecordNotExist } } ; _lossAssetRepo.Delete(asset); var delete = await _appUow.ElkSaveChangesAsync(); if (File.Exists(asset.PhysicalPath)) { File.Delete(asset.PhysicalPath); } return(new Response <string> { IsSuccessful = delete.IsSuccessful, Message = delete.Message }); } catch (Exception e) { FileLoger.Error(e); return(new Response <string> { Message = ServiceMessage.Error }); } }
protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; try { if (authCookie != null) { _userBiz = IocInitializer.GetInstance(typeof(IUserBusiness)) as Business.Implement.UserBusiness; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); var currentUser = serializer.Deserialize <CurrentUserPrincipal>(authTicket.UserData); currentUser.SetIdentity(authTicket.Name); var rep = _userBiz.GetAvailableActions(currentUser.UserId); if (rep != null) { currentUser.UserActionList = rep.Items.ToList(); HttpContext.Current.User = currentUser; } } } catch (Exception ex) { FileLoger.Info(authCookie.Value, GlobalVariable.LogPath); FileLoger.Error(ex, GlobalVariable.LogPath); RedirectToAuthentication(); } }
public async Task <IResponse <Dictionary <string, int> > > GetLossCountLastDaysAsync(int dayCount = 10) { var result = new Response <Dictionary <string, int> >(); try { var cache = (Response <Dictionary <string, int> >)_cacheProvider.Get(LossCountLastDaysCacheKey()); if (cache != null) { return(cache); } result.Result = await _appUow.LossRepo.GetLossCountLastDaysAsync(dayCount); if (result.Result.Count() == 0) { return new Response <Dictionary <string, int> > { Message = ServiceMessage.RecordNotExist } } ; result.IsSuccessful = true; result.Message = ServiceMessage.Success; _cacheProvider.Add(LossCountLastDaysCacheKey(), result, DateTimeOffset.Now.AddMinutes(30)); return(result); } catch (Exception e) { FileLoger.Error(e); return(result); } }
public IActionResponse <bool> Send(Message message) { var result = new ActionResponse <bool>(); try { //FileLoger.Info($"Send Sms Message = Receiver:{message.Receiver}, Content:{message.Content}", GlobalVariable.LogPath); var sendResult = _smsAdapter.SendMessage("mamirshahi", "jobTyw-5paqwi-byjciw", "50002210004039", message.Content, new ArrayOfString() { message.Receiver }, 1, null); if (sendResult[0] > 1000) { message.State = StateType.Accepted; result.IsSuccessful = true; } message.SendStatus = sendResult[0].ToString(); _uow.Entry(message).State = EntityState.Modified; var saveChange = _uow.SaveChanges(); result.Result = saveChange.ToSaveChangeResult(); //FileLoger.Info($"Send Sms Result = IsSuccessful:{result.IsSuccessful}, Result:{sendResult[0]}", GlobalVariable.LogPath); } catch (Exception e) { FileLoger.Error(e, GlobalVariable.LogPath); } return(result); }
public async Task <IEnumerable <Post> > GetAsync(string username, PagingParameter pagingParameter) { try { var query = "SELECT po.[PostId],[ViewCount],[LikeCount],[CommentCount],[IsAlbum],[CreateDateMi],po.[UniqueId],po.[Description],"+ "PostAssets = (SELECT [Type],[Dimension],[UniqueId],[FileUrl],[ThumbnailUrl]"+ " FROM [Instagram].[PostAsset]"+ " WHERE PostId = po.PostId"+ " For JSON AUTO) "+ "FROM [Instagram].[Page] p "+ "INNER JOIN [Instagram].[Post] po ON p.PageId = po.PageId "+ "WHERE p.Username = @Username "+ "ORDER BY po.PostId DESC "+ "OFFSET @PageSize * (@PageNumber - 1) ROWS "+ "FETCH NEXT @PageSize ROWS ONLY;"; return(await _sqlConnection.ExecuteQueryAsync <Post>(query, new { Username = username, pagingParameter.PageNumber, pagingParameter.PageSize })); } catch (Exception e) { FileLoger.Error(e); return(null); } }
public async Task <bool> AddAsync(Application model) { try { model.InsertDateMi = DateTime.Now; model.InsertDateSh = PersianDateTime.Now.ToString(PersianDateTimeFormat.Date); await _sqlConnection.ExecuteSpCommandAsync <int>("[Notifier].[InsertApplication]", new { EventMapper = model.ToTableValuedParameter("[dbo].[Tvp_Application]") }); return(true); } catch (Exception e) { FileLoger.Error(e); if (e.Message.Contains("unique index")) { return(true); } else { return(false); } } }
public IActionResponse <bool> VerifyCode(Guid userId, string code) { var result = new ActionResponse <bool>(); try { DateTime expireTime = DateTime.Now.AddMinutes(-20); var verificationCode = _verificationCode.FirstOrDefault(x => !x.IsUsed && x.Code == code && x.InsertDateMi >= expireTime); if (verificationCode.IsNull()) { result.Message = BusinessMessage.InvalidInputModelData; } else { Verify(verificationCode.UserId); verificationCode.IsUsed = true; _uow.SaveChanges(); result.Result = true; result.IsSuccessful = true; result.Message = BusinessMessage.Success; } return(result); } catch (Exception e) { FileLoger.Error(e, GlobalVariable.LogPath); result.Message = BusinessMessage.Exception; return(result); } }
public async Task <IResponse <List <PriceInquiryResult> > > PriceInquiry(LocationsDTO priceInquiry, bool cashed, bool hasReturn) { var result = new Response <List <PriceInquiryResult> >(); result.Result = new List <PriceInquiryResult>(); try { var peyk = await AloPeikProvider.PriceInquiry(priceInquiry.Source, priceInquiry.Destination, cashed, hasReturn); var post = await PostProvider.PriceInquiry(priceInquiry.Source, priceInquiry.Destination, cashed, hasReturn); if (peyk.IsNotNull()) { result.Result.Add(peyk); } if (post.IsNotNull()) { result.Result.Add(post); } result.IsSuccessful = true; result.Message = ServiceMessage.Success; return(result); } catch (Exception e) { FileLoger.Error(e); result.Message = ServiceMessage.Exception; return(result); } }
public static async Task <PriceInquiryResult> PriceInquiry(LocationDTO originLocation, LocationDTO destinationLocation, bool cashed, bool hasReturn) { try { var result = new PriceInquiryResult { DeliveryProviderId = 2, DeliveryType = "Post", DeliveryType_Fa = "پست", Price = 12000, Final_Price = 12000, Distance = "0", Discount = 0, Duration = "0", Delay = 0, Cashed = cashed, Has_Return = hasReturn, Price_With_Return = 15000, Addresses = null }; return(result); } catch (Exception e) { FileLoger.Error(e); return(null); } }
public async Task <IResponse <OrderResult> > RegisterPostOrder(DeliveryOrderDTO deliveryOrderDTO) { var result = new Response <OrderResult>(); try { var registerOrderResult = await AloPeikProvider.RegisterOrder(deliveryOrderDTO.Addresses.FirstOrDefault(x => x.Type == "origin"), deliveryOrderDTO.Addresses.FirstOrDefault(x => x.Type == "destination"), false, false, deliveryOrderDTO.ExtraParams); result.Result = new OrderResult { OrderId = registerOrderResult.Id, OrderToken = registerOrderResult.Order_Token, OrderDiscount = registerOrderResult.Order_Discount, Price = registerOrderResult.Final_Price, //ExtraParams = registerOrderResult.Extra_Param, PayAtDestination = registerOrderResult.Pay_At_Dest, Cashed = registerOrderResult.Cashed, Delay = registerOrderResult.Delay, Duration = registerOrderResult.Duration, Distance = registerOrderResult.Distance, Has_Return = registerOrderResult.Has_Return, Addresses = registerOrderResult.Addresses }; result.IsSuccessful = true; result.Message = ServiceMessage.Success; return(result); } catch (Exception e) { FileLoger.Error(e); result.Message = ServiceMessage.Exception; return(result); } }
public async Task <bool> AddAsync(CrawledPageDto model) { try { var instagramPage = new Page(); instagramPage.UpdateWith(model); instagramPage.InsertDateMi = instagramPage.ModifyDateMi = DateTime.Now; instagramPage.InsertDateSh = instagramPage.ModifyDateSh = PersianDateTime.Now.ToString(PersianDateTimeFormat.Date); await _sqlConnection.ExecuteSpCommandAsync <int>("[Instagram].[InsertPage]", new { Page = instagramPage.ToTableValuedParameter("[dbo].[Tvp_Page]") }); return(true); } catch (Exception e) { FileLoger.Error(e); if (e.Message.Contains("unique index")) { return(true); } else { return(false); } } }
public async Task <IResponse <bool> > DeleteAttachment(int attachmentId) { var response = new Response <bool>(); try { var attachment = await _appUow.RelativeAttachmentRepo.FindAsync(attachmentId); _appUow.RelativeAttachmentRepo.Delete(attachment); var deleteFileResult = await _appUow.ElkSaveChangesAsync(); if (deleteFileResult.IsSuccessful) { response.Result = true; response.IsSuccessful = true; response.Message = ServiceMessage.Success; } else { response.Result = false; response.IsSuccessful = true; response.Message = ServiceMessage.Error; } return(response); } catch (Exception e) { FileLoger.Error(e); response.Message = ServiceMessage.Exception; return(response); } }
public IActionResponse <bool> Send(Message message) { var result = new ActionResponse <bool>(); try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; var roboResponse = Bot.SendTextMessageAsync(message.Receiver, message.Content).Result; message.SendStatus = roboResponse.MessageId.ToString(); message.State = StateType.Accepted; _uow.Entry(message).State = EntityState.Modified; _uow.SaveChanges(); result.Result = true; result.IsSuccessful = true; result.Message = BusinessMessage.Success; return(result); //result.IsSuccessful = true; //return result; } catch (Exception e) { FileLoger.Error(e, GlobalVariable.LogPath); result.Message = BusinessMessage.Error; return(result); } }
public async Task <IResponse <List <Post> > > GetPosts(string username, int pageNumber) { try { using var getPostsHttp = new HttpClient(); var apiCall = await getPostsHttp.GetAsync($"{_configuration["CustomSettings:Crawler:GetPosts"]}?pageSize=6&username={username}&pageNumber={pageNumber}"); if (!apiCall.IsSuccessStatusCode) { return new Response <List <Post> > { Message = ServiceMessage.Error } } ; var getPosts = (await apiCall.Content.ReadAsStringAsync()).DeSerializeJson <Response <List <Post> > >(); if (!getPosts.IsSuccessful) { return new Response <List <Post> > { Message = getPosts.Message } } ; return(new Response <List <Post> > { IsSuccessful = true, Result = getPosts.Result }); } catch (Exception e) { FileLoger.Error(e); return(new Response <List <Post> > { Message = ServiceMessage.GetPostsFailed }); } }
public Task Execute(IJobExecutionContext context) { try { using (var db = new RasmiDbContext()) { db.Database.ExecuteSqlCommand("EXEC [Statistic].[User]"); Thread.Sleep(2000); db.Database.ExecuteSqlCommand("EXEC [Statistic].[Order]"); Thread.Sleep(2000); db.Database.ExecuteSqlCommand("EXEC [Statistic].[Payment]"); } return(Task.CompletedTask); } catch (Exception e) { FileLoger.Error(e); return(Task.CompletedTask); } }
private IEnumerable <LossDescriptionDTO> GetTypes() { try { return(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.ContentRootPath + "/LossDescription.json")).DeSerializeJson <List <LossDescriptionDTO> >()); } catch (Exception e) { FileLoger.Error(e); return(new List <LossDescriptionDTO>()); } }
public static void Initialize(string teleBotToken) { try { _client = new TelegramBotClient(teleBotToken); _client.OnMessage += TeleBot_ReceiveMessage; _client.StartReceiving(); } catch (Exception e) { FileLoger.Error(e); } }
private async Task <IResponse <bool> > CrawlNewPostAsync(IPostRepo postRepo, Page page, int newPostCount) { try { var postCount = 0; var haveNextPage = false; var cursor = string.Empty; var postList = new List <CrawledPostDto>(); do { #region Call Instagram Post Api var postInquiry = await CrawlPostFromInstagramAsync(page.UniqueId, newPostCount, cursor); if (postInquiry.status != "ok") { return new Response <bool> { IsSuccessful = false, Message = ServiceMessage.Error } } ; var postCollection = postInquiry.data.user.edge_Owner_To_Timeline_Media.edges; var totalPostCount = postInquiry.data.user.edge_Owner_To_Timeline_Media.count; cursor = postInquiry.data.user.edge_Owner_To_Timeline_Media.page_Info.end_cursor; haveNextPage = postInquiry.data.user.edge_Owner_To_Timeline_Media.page_Info.has_next_page; #endregion foreach (var post in postCollection) { postCount += 1; var newPost = ConvertToCrawledPostDto(post); newPost.PageId = page.PageId; await postRepo.AddAsync(newPost); } } while (haveNextPage == true && postCount < newPostCount); return(new Response <bool> { Result = true, IsSuccessful = true, Message = ServiceMessage.Success }); } catch (Exception e) { FileLoger.Error(e); return(new Response <bool> { IsSuccessful = false, Message = ServiceMessage.Exception }); } }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var cachePeriod = "0"; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseStaticFiles(); cachePeriod = "1"; } else { app.UseStaticFiles(); //cachePeriod = "604800"; //app.UseStaticFiles(new StaticFileOptions //{ // OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}"); } //}); app.UseExceptionHandler("/Home/Error"); app.UseHsts(); app.Use(async(context, next) => { await next.Invoke(); if (!context.Request.IsAjaxRequest()) { var handled = context.Features.Get <IStatusCodeReExecuteFeature>(); var exp = context.Features.Get <IExceptionHandlerFeature>(); var statusCode = context.Response.StatusCode; if (handled == null && statusCode >= 400) { FileLoger.Error(exp.Error); context.Response.Redirect($"/Error/Index?code={statusCode}"); } } }); } app.UseRouting(); app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}"); }); }
public async Task <bool> DeleteAsync(string pageId) { try { var query = "DELETE [Instagram].[Page] " + "WHERE [Username] = @Username"; return(await _sqlConnection.ExecuteQueryCommandAsync(query, new { Username = pageId })); } catch (Exception e) { FileLoger.Error(e); return(false); } }
public override int SaveChanges() { try { //try { AuditLoger.Log(this, (HttpContext.Current.User as ICurrentUserPrincipal).UserId); } catch { } BasePropertyInitializer.Initialize(this); return(base.SaveChanges()); } catch (DbEntityValidationException validationException) { string errorMessage = string.Empty; foreach (var errors in validationException.EntityValidationErrors) { errorMessage += $"Entity of type \"{errors.Entry.Entity.GetType().Name}\" in state \"{errors.Entry.State.ToString()}\" has the following validation errors:" + Environment.NewLine; foreach (var error in errors.ValidationErrors) { errorMessage += $"- Property: \"{error.PropertyName}\", Error: \"{error.ErrorMessage}\""; } } errorMessage += Environment.NewLine + Environment.NewLine; FileLoger.Error(new Exception(errorMessage), GlobalVariable.LogPath); return(-3); } catch (DbUpdateConcurrencyException concurrencyException) { FileLoger.Error(concurrencyException, GlobalVariable.LogPath); return(-2); } catch (DbUpdateException updateException) { FileLoger.Error(updateException, GlobalVariable.LogPath); if (updateException.InnerException.IsNotNull() && updateException.InnerException.InnerException.IsNotNull() && updateException.InnerException.InnerException.Message.Contains("Cannot insert duplicate key")) { return(-4); } return(-1); } catch (Exception e) { FileLoger.Error(e, GlobalVariable.LogPath); if (e.Message.ToLower().Contains("Cannot insert duplicate key")) { return(-4); } return(-10); } }
public async Task <bool> UpdateAsync(UpdateNotificationDto model) { try { await _sqlConnection.ExecuteSpCommandAsync <int>("[Notifier].[UpdateNotification]", new { NotificationId = model.NotificationId, Status = model.Status, SendStatus = model.SendStatus, SendDateMi = model.SendDateMi, IsLock = model.IsLock }); return(true); } catch (Exception e) { FileLoger.Error(e); return(false); } }
public static async Task <AloPeikOrderResult> RegisterOrder(DeliveryOrderLocationDTO origin, DeliveryOrderLocationDTO destination, bool cashed, bool hasReturn, string extraParams) { var result = new AloPeikOrderResult(); try { #region Create Request Bode var model = new { transport_type = AloPeikTransportType.motor_taxi.ToString(), addresses = new List <dynamic> { new { type = AloPeikAddressType.origin.ToString(), lat = origin.Lat, lng = origin.Lng, description = origin.Description, person_phone = origin.PersonPhone, person_fullname = origin.PersonFullName }, new { type = AloPeikAddressType.destination.ToString(), lat = destination.Lat, lng = destination.Lng, description = destination.Description, person_phone = destination.PersonPhone, person_fullname = destination.PersonFullName } }, has_return = hasReturn, cashed = cashed, extra_params = extraParams }; #endregion using (var httpClient = new HttpClient()) { var body = new StringContent(model.SerializeToJson(), Encoding.UTF8, "application/json"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GlobalVariables.DeliveryProviders.AloPeik.Token); var response = await httpClient.PostAsync($"{GlobalVariables.DeliveryProviders.AloPeik.Url}/orders", body); var responseBody = await response.Content.ReadAsStringAsync(); var responseResult = responseBody.DeSerializeJson <AloPeikResult <AloPeikOrderResult> >(); if (responseResult.Status == "success") { result = responseResult.Object; } else { result = null; } } return(result); } catch (Exception e) { FileLoger.Error(e); return(null); } }
public async Task <Page> FindAsync(string pageId) { try { var query = "SELECT * " + "FROM [Instagram].[Page] " + "WHERE [Username] = @Username"; return(await _sqlConnection.ExecuteQuerySingleAsync <Page>(query, new { Username = pageId })); } catch (Exception e) { FileLoger.Error(e); return(null); } }
public async Task <Notification> FindAsync(int notificationId) { try { var query = "SELECT * " + "FROM [Notifier].[Notification] " + "WHERE [NotificationId] = @NotificationId"; return(await _sqlConnection.ExecuteQuerySingleAsync <Notification>(query, new { NotificationId = notificationId })); } catch (Exception e) { FileLoger.Error(e); return(null); } }
public async Task <IEnumerable <EventMapper> > GetAsync(EventType eventType, int applicationId) { try { var query = "SELECT * "+ "FROM [Notifier].[EventMapper] e "+ "WHERE e.ApplicationId = @ApplicationId AND e.Type = @EventType "; return(await _sqlConnection.ExecuteQueryAsync <EventMapper>(query, new { ApplicationId = applicationId, EventType = (byte)eventType })); } catch (Exception e) { FileLoger.Error(e); return(null); } }
public async Task <IResponse <IList <LossAsset> > > SaveRange(string root, Guid userId, IList <IFormFile> files) { try { var items = new List <LossAsset>(); var id = userId.ToString().Replace("-", "_"); var pdt = PersianDateTime.Now; var dir = $"/Files/{id}/{pdt.Year}/{pdt.Month}"; if (!FileOperation.CreateDirectory(root + "/wwwroot" + dir)) { return new Response <IList <LossAsset> > { Message = ServiceMessage.SaveFileFailed } } ; foreach (var file in files) { var relativePath = $"{dir}/{Guid.NewGuid().ToString().Replace("-", "_")}{Path.GetExtension(file.FileName)}"; var physicalPath = (root + "/wwwroot" + relativePath).Replace("/", "\\"); items.Add(new LossAsset { Name = file.FileName, Extention = Path.GetExtension(file.FileName), FileType = FileOperation.GetFileType(file.FileName), FileUrl = "~" + relativePath, PhysicalPath = physicalPath }); using (var stream = File.Create(physicalPath)) await file.CopyToAsync(stream); } return(new Response <IList <LossAsset> > { IsSuccessful = true, Result = items }); } catch (Exception e) { FileLoger.Error(e); return(new Response <IList <LossAsset> > { Message = ServiceMessage.SaveFileFailed }); } }
public async Task <IResponse <int> > GetLossCount() { var result = new Response <int>(); try { result.Result = await _appUow.LossRepo.GetLossCount(); result.IsSuccessful = true; result.Message = ServiceMessage.Success; return(result); } catch (Exception e) { FileLoger.Error(e); return(result); } }
public async Task <IResponse <IList <ProductAsset> > > SaveRange(ProductAddModel model) { try { var items = new List <ProductAsset>(); var pdt = PersianDateTime.Now; var dir = $"/Files/{model.StoreId}/{pdt.Year}/{pdt.Month}"; if (!FileOperation.CreateDirectory(model.Root + dir)) { return new Response <IList <ProductAsset> > { Message = ServiceMessage.SaveFileFailed } } ; foreach (var file in model.Files) { var relativePath = $"{dir}/{Guid.NewGuid().ToString().Replace("-", "_")}{Path.GetExtension(file.FileName)}"; var physicalPath = (model.Root + relativePath).Replace("/", "\\"); items.Add(new ProductAsset { Name = file.FileName, Extention = Path.GetExtension(file.FileName), FileType = FileOperation.GetFileType(file.FileName), FileUrl = model.BaseDomain + relativePath, CdnFileUrl = physicalPath }); using (var stream = File.Create(physicalPath)) await file.CopyToAsync(stream); } return(new Response <IList <ProductAsset> > { IsSuccessful = true, Result = items }); } catch (Exception e) { FileLoger.Error(e); return(new Response <IList <ProductAsset> > { Message = ServiceMessage.SaveFileFailed }); } }