public ActionResult RemoveMember(EnterpriseGroupMemberViewModel viewModel) { ViewBag.ViewModel = viewModel; var item = models.GetTable <EnterpriseCourseMember>().Where(m => m.ContractID == viewModel.ContractID && m.UID == viewModel.UID).FirstOrDefault(); if (item == null) { return(Json(new { result = false, message = "資料錯誤!!" })); } try { models.ExecuteCommand(@"DELETE FROM RegisterLesson FROM EnterpriseCourseContract INNER JOIN RegisterLessonEnterprise ON EnterpriseCourseContract.ContractID = RegisterLessonEnterprise.ContractID INNER JOIN RegisterLesson ON RegisterLessonEnterprise.RegisterID = RegisterLesson.RegisterID WHERE (EnterpriseCourseContract.ContractID = {0}) AND (RegisterLesson.UID = {1})", item.ContractID, item.UID); models.DeleteAny <EnterpriseCourseMember>(m => m.ContractID == viewModel.ContractID && m.UID == viewModel.UID); return(Json(new { result = true })); } catch (Exception ex) { ApplicationLogging.CreateLogger <EnterpriseProgramController>().LogError(ex, ex.Message);; return(Json(new { result = false, message = ex.Message })); } }
public async Task <ActionResult> SearchWord(etymincParams incp, etymfilter f, int count, int maxpage) { try { var dps = new etymdictParams() { incp = incp, f = f }; dps.count = count; dps.maxpage = maxpage; dps.entry = await db.getEntry(incp.idclass); dps.w = dps.entry != null?dps.entry.e_classes.Where(c => c.id == incp.idclass).FirstOrDefault().etymons.Where(c => c.id == incp.wid).FirstOrDefault().word : ""; ViewBag.dp = new dictParams() { etym = dps, vtype = viewtype.etym }; return(View("Index", dps)); } catch (Exception ex) { ApplicationLogging.CreateLogger <etymController>().LogError(new EventId(0), ex, ex.Message); return(BadRequest("Зверніться до розробника")); } }
// GET: Error public async Task <ActionResult> GetBarCode39Async(String code) { Response.ContentType = "image/Jpeg"; //response.Buffer = true; //response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0); //response.Expires = 0; if (!String.IsNullOrEmpty(code)) { try { using (Bitmap img = code.GetCode39(false)) { img.SetResolution(_dpi, _dpi); using (FileBufferingWriteStream output = new FileBufferingWriteStream()) { img.Save(output, ImageFormat.Jpeg); //output.Seek(0, SeekOrigin.Begin); await output.DrainBufferAsync(Response.Body); } } } catch (Exception ex) { ApplicationLogging.CreateLogger <PublishedController>().LogError(ex, ex.Message); } } //context.Response.CacheControl = "no-cache"; //context.Response.AppendHeader("Pragma", "No-Cache"); return(new EmptyResult()); }
//public ActionResult InquireProjectCourse(LessonPriceQueryViewModel viewModel) //{ // IQueryable<LessonPriceType> items = models.GetTable<LessonPriceType>() // .Where(p => !p.SeriesID.HasValue) // .Where(p => p.BranchID.HasValue) // .Where(p => p.IsInternalLesson == null) // .Where(p => p.IsWelfareGiftLesson == null) // .Where(p => p.Status == (int)Naming.LessonPriceStatus.一般課程 || p.Status == (int)Naming.LessonPriceStatus.已刪除); // if (viewModel.Status.HasValue) // { // items = items.Where(p => p.Status == viewModel.Status); // } // if (viewModel.BranchID.HasValue) // { // items = items.Where(p => p.BranchID == viewModel.BranchID); // } // return View("~/Views/LessonPrice/Module/ProjectCourseList.ascx", items); //} public ActionResult DeleteLessonPrice(LessonPriceQueryViewModel viewModel) { LessonPriceType item; try { item = models.DeleteAny <LessonPriceType>(p => p.PriceID == viewModel.PriceID); if (item != null) { return(Json(new { result = true })); } return(Json(new { result = false, message = "資料錯誤!!" })); } catch (Exception ex) { ApplicationLogging.CreateLogger <LessonPriceController>().LogError(ex, ex.Message); } item = models.GetTable <LessonPriceType>().Where(l => l.PriceID == viewModel.PriceID).FirstOrDefault(); if (item == null) { return(Json(new { result = false, message = "資料錯誤!!" })); } item.Status = (int)Naming.LessonSeriesStatus.已停用; models.SubmitChanges(); return(Json(new { result = true, message = "價目已使用,無法刪除,已改為停用!!" })); }
public ActionResult UploadResource(int id) { var item = models.GetTable <Article>().Where(a => a.DocID == id).FirstOrDefault(); if (item == null) { return(Json(new { result = false, message = "文章不存在!!" })); } if (Request.Form.Files.Count <= 0) { return(Json(new { result = false, message = "檔案上載失敗!!" })); } try { String storePath = Path.Combine(FileLogger.Logger.LogDailyPath, Guid.NewGuid().ToString() + Path.GetExtension(Request.Form.Files[0].FileName)); Request.Form.Files[0].SaveAs(storePath); models.GetTable <Attachment>().InsertOnSubmit(new Attachment { DocID = item.DocID, StoredPath = storePath }); models.SubmitChanges(); return(Json(new { result = true })); } catch (Exception ex) { ApplicationLogging.CreateLogger <InformationController>().LogError(ex, ex.Message); return(Json(new { result = false, message = ex.Message })); } }
public ActionResult UpdateBonusPromotionStatus(PromotionViewModel viewModel, bool?tryToDelete) { var item = loadPromotionItem(viewModel); if (item == null) { return(View("~/Views/Shared/JsAlert.cshtml", model: "活動方案資料錯誤!!")); } item.PDQQuestion.First().PDQQuestionExtension.Status = (int?)viewModel.Status; models.SubmitChanges(); if (tryToDelete == true) { try { models.ExecuteCommand("delete PDQGroup where GroupID = {0}", item.GroupID); return(Json(new { result = true })); } catch (Exception ex) { ApplicationLogging.CreateLogger <PromotionController>().LogError(ex, ex.Message); return(Json(new { result = false, message = ex.Message })); } } else { return(Json(new { result = true })); } }
/// <summary> /// Serialize the object to xml. Returns true if successful, false if failed. The out property is set to null on a failure, otherwise it contains the XML /// This code is designed to produce an XML Fragment suitable for use with a REST API. It omits the <xml/> declaration in the output /// </summary> /// <typeparam name="T"></typeparam> /// <param name="domainObject">The domain object.</param> /// <param name="body">The body.</param> /// <returns><c>true</c> if serialized, <c>false</c> otherwise.</returns> public static bool TryBuild <T>(T domainObject, out string body) { var ns = new XmlSerializerNamespaces(); ns.Add("", ""); var serializer = new XmlSerializer(typeof(T)); var textWriter = new StringWriter(); var writer = XmlWriter.Create(textWriter, new XmlWriterSettings { OmitXmlDeclaration = true }); try { serializer.Serialize(writer, domainObject, ns); body = textWriter.ToString(); return(true); } catch (Exception e) { var logger = ApplicationLogging.CreateLogger <XmlRequestBuilder>(); logger.LogTrace(e.Message); body = null; return(false); } finally { writer.Dispose(); textWriter.Dispose(); } }
public async Task <ActionResult> SearchWord(synincParams incp, synsetsfilter f, int count, int maxpage) { try { var dps = new syndictParams() { incp = incp, f = f, id_lang = db.lid.id_lang }; dps.count = count; dps.maxpage = maxpage; dps.entry = await db.getEntry(incp.idset); dps.w = dps.entry != null ? (from c in dps.entry._wlist where c.id == incp.wid select c.word).FirstOrDefault() : ""; ViewBag.dp = new dictParams() { syn = dps, vtype = viewtype.synsets }; return(View("Index", dps)); } catch (Exception ex) { ApplicationLogging.CreateLogger <synsetsController>().LogError(new EventId(0), ex, ex.Message); return(BadRequest("Зверніться до розробника")); } }
public static IQueryable <T> Sort <T>(this IQueryable <T> source, QuerySet querySet, IDictionary <string, IEnumerable <Expression <Func <T, object> > > > selectors) { // TODO add better support to filter on multiple fields. // Now we assume all fields are sorted ASC or DESC. But actually querySet.Sort should support multiple fields IEnumerable <Expression <Func <T, object> > > selectorsForField; var field = querySet.Sort.Field; if (field != null && selectors.TryGetValue(field, out selectorsForField)) { int i = 0; foreach (Expression <Func <T, object> > selector in selectorsForField) { if (i == 0) { source = querySet.Sort.IsAscending ? source.OrderBy(selector) : source.OrderByDescending(selector); } else { var orderedQueryable = (IOrderedQueryable <T>)source; source = querySet.Sort.IsAscending ? orderedQueryable.ThenBy(selector) : orderedQueryable.ThenByDescending(selector); } i++; } } else if (field != null) { ApplicationLogging.CreateLogger(typeof(BaseQueryExtensions).AssemblyQualifiedName) .LogWarning("'{Value}' is not supported as sort value on type {Type}", field, typeof(T).AssemblyQualifiedName); } return(source); }
public ActionResult ContactUs(String email, String userName, String subject, String comment) { ThreadPool.QueueUserWorkItem(t => { try { StringBuilder body = new StringBuilder(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.ReplyToList.Add(Startup.Properties["WebMaster"]); message.From = new System.Net.Mail.MailAddress(email, userName); message.To.Add(Startup.Properties["WebMaster"]); message.Subject = subject; message.IsBodyHtml = true; message.Body = HttpUtility.HtmlDecode(comment); System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient(Startup.Properties["SmtpServer"]); //smtpclient.Credentials = CredentialCache.DefaultNetworkCredentials; smtpclient.Send(message); } catch (Exception ex) { ApplicationLogging.CreateLogger <InformationController>().LogError(ex, ex.Message); } }); ViewBag.Success = "Your comment was successfully added!"; return(View("Success")); }
public async Task <IActionResult> Index(incParams incp, filter f, pclsfilter pclsf) { try { var dp = new dictParams() { gr = new grdictParams() { f = f, incp = incp }, pcls = new pclsdictParams() { indents = db.indent, f = pclsf, pclsinfo = await db.getPClass(pclsf.pclassPcls) }, vtype = viewtype.pclass }; if (pclsf.ispofsPcls) { dp.pcls.indents = (from c in db.indents where c.gr_id == pclsf.pofsPcls select c).ToArray(); } ViewBag.dp = dp; return(View(dp.pcls.pclsinfo)); } catch (Exception ex) { ApplicationLogging.CreateLogger <flexesController>().LogError(new EventId(0), ex, ex.Message); return(BadRequest("Зверніться до розробника")); } }
public async Task <ActionResult> SearchWord(incParams incp, filter f, int count, int maxpage) { //global::System.Resources.ResourceManager rm = new global::System.Resources.ResourceManager("mphdeck.Resources.idispl", typeof(Resources.idispl).GetTypeInfo().Assembly); //System.Resources.ResourceManager rm = new System.Resources.ResourceManager(typeof(mphdeck.Resources.idispl)); //System.Resources.ResourceManager rm = System.Resources.ResourceManager("mphdeck.Resources.idispl", typeof(Resources.idispl).GetTypeInfo().Assembly); //string test2 = mphdeck.Resources.idispl.ResourceManager.GetString("bname_ua", new System.Globalization.CultureInfo("uk")); //string test1 = mphdeck.Resources.idispl.ResourceManager.GetString("bname_ua", new System.Globalization.CultureInfo("en")); //System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("MyResource", Assembly.GetExecutingAssembly //string test2 = rm.GetString("bname_ua", new System.Globalization.CultureInfo("uk")); //string test1 = rm.GetString("bname_ua", new System.Globalization.CultureInfo("en")); try { var dpg = new grdictParams() { incp = incp, f = f, id_lang = db.lid.id_lang }; dpg.count = count; dpg.maxpage = maxpage; dpg.entry = await db.getEntry(incp.wid); ViewBag.dp = new dictParams() { gr = dpg, vtype = viewtype.dict }; return(View("Index", dpg)); } catch (Exception ex) { ApplicationLogging.CreateLogger <inflectionController>().LogError(new EventId(0), ex, ex.Message); return(BadRequest("Зверніться до розробника")); } }
public ActionResult MakeTheme(int docID, int attachmentID) { var item = models.GetTable <Article>().Where(a => a.DocID == docID).FirstOrDefault(); if (item == null) { return(Json(new { result = false, message = "文章不存在!!" })); } var attachment = models.GetTable <Attachment>().Where(a => a.AttachmentID == attachmentID).FirstOrDefault(); if (attachment == null) { return(Json(new { result = false, message = "圖檔不存在!!" })); } try { item.Illustration = attachment.AttachmentID; models.SubmitChanges(); return(Json(new { result = true, message = "資料已更新!!" })); } catch (Exception ex) { ApplicationLogging.CreateLogger <InformationController>().LogError(ex, ex.Message); return(Json(new { result = false, message = ex.Message })); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { ApplicationLogging.ConfigureLogger(loggerFactory); Util._logger = ApplicationLogging.CreateLogger("Util"); EntityHelper._logger = ApplicationLogging.CreateLogger("EntityHelper"); if (env.IsDevelopment()) { app.UseExceptionHandler("/error-local-development"); } else { app.UseExceptionHandler("/error"); } app.UseRouting(); // global cors policy app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public void DoJob() { using (ModelSource <UserProfile> models = new ModelSource <UserProfile>()) { try { models.RegisterMonthlyGiftLesson(); } catch (Exception ex) { ApplicationLogging.CreateLogger <MonthlyJob>() .LogError(ex, ex.Message); } } using (ModelSource <UserProfile> models = new ModelSource <UserProfile>()) { try { models.ClearUnpaidOverdueContract(); } catch (Exception ex) { ApplicationLogging.CreateLogger <MonthlyJob>() .LogError(ex, ex.Message); } } }
public void Run() { var logger = ApplicationLogging.CreateLogger <GCController>(); logger.LogInformation("GC.Collect()"); GC.Collect(); }
public void TestGetLoggerByType() { ILogger logger = ApplicationLogging.CreateLogger(typeof(Program)); Type type = logger.GetType(); Assert.Equal("Logger", type.Name); Assert.Equal("Microsoft.Extensions.Logging.Logger", type.FullName); }
public BotLogic(ITaskRepository _taskRepository, IUserRequestRepository _userRequestRepository, IEmailScenarioDecider _EmailScenarioFactory) { _logger = ApplicationLogging.CreateLogger(); UserRequestRepository = _userRequestRepository; TaskRepository = _taskRepository; Configurations = new BotConfiguration(); EmailScenarioFactory = _EmailScenarioFactory; }
protected BaseTest(ITestOutputHelper output) { ConfigureSerilog(output); ConfigureDefaultServices(); UpdateServiceLocator(); TestConsole = ApplicationLogging.CreateLogger <T>(); }
protected SpaceObject(Point leftTopPosition) { CollisionsList = new List <IColliding>(); LeftTopPosition = leftTopPosition; Logger = ApplicationLogging.CreateLogger(GetType()); }
public MsSqlTests() { ViewModelBindable.isUnitTests = true; InitLogging(this); _logger = ApplicationLogging.CreateLogger <MsSqlTests>(); }
private static void HandleExceptionAsync(HttpContext context, Exception exception) { ILogger _logger = ApplicationLogging.CreateLogger <ExceptionMiddleware>() as ILogger <ExceptionMiddleware>; _logger.LogError($"Something went wrong: {exception}"); context.Response.Redirect("/Error"); }
internal InterprocessLockProxy(string indexPath, string lockName, bool deleteOnClose) { m_Logger = ApplicationLogging.CreateLogger <InterprocessLock>(); m_IndexPath = indexPath; m_LockName = lockName; m_DeleteOnClose = deleteOnClose; m_LockFullFileNamePath = GetLockFileName(indexPath, lockName); }
public ApiService(string PAT) { _logger = ApplicationLogging.CreateLogger <ApiService>(); _client = new HttpClient(); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var bytes = Encoding.ASCII.GetBytes($"{string.Empty}:{PAT}"); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes)); }
public async Task <ActionResult> GetQRCodeAsync(String text, QRCodeEncoder.ENCODE_MODE?enc, int?scale, int?ver, QRCodeEncoder.ERROR_CORRECTION?ec, float?dpi) { Response.ContentType = "image/Jpeg"; //response.Buffer = true; //response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0); //response.Expires = 0; if (!enc.HasValue) { enc = QRCodeEncoder.ENCODE_MODE.BYTE; } if (!scale.HasValue) { scale = 4; } if (!ver.HasValue) { ver = 6; } if (!ec.HasValue) { ec = QRCodeEncoder.ERROR_CORRECTION.L; } if (!dpi.HasValue) { dpi = 600f; } try { using (Bitmap img = text.CreateQRCode(enc.Value, scale.Value, ver.Value, ec.Value)) { img.SetResolution(_dpi, _dpi); using (FileBufferingWriteStream output = new FileBufferingWriteStream()) { img.Save(output, ImageFormat.Jpeg); //output.Seek(0, SeekOrigin.Begin); await output.DrainBufferAsync(Response.Body); } } } catch (Exception ex) { ApplicationLogging.CreateLogger <PublishedController>().LogError(ex, ex.Message); } //context.Response.CacheControl = "no-cache"; //context.Response.AppendHeader("Pragma", "No-Cache"); return(new EmptyResult()); }
public ActionResult PushMessage(LineMessageViewModel viewModel) { ViewBag.ViewModel = viewModel; viewModel.Message = viewModel.Message.GetEfficientString(); if (viewModel.Message == null) { return(Content("Message is empty !")); } var item = models.GetTable <UserProfile>() .Where(u => u.UID == viewModel.UID) .FirstOrDefault(); if (item == null) { return(Content("User not found !")); } if (item.UserProfileExtension?.LineID != null) { using (WebClient client = new WebClient()) { var encoding = new UTF8Encoding(false); client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); client.Headers.Add("Authorization", $"Bearer {Startup.Properties["ChannelToken"]}"); var jsonData = new { to = item.UserProfileExtension.LineID, messages = new[] { new { type = "text", text = viewModel.Message } } }; var dataItem = JsonConvert.SerializeObject(jsonData); var result = client.UploadData(Startup.Properties["LinePushMessage"], encoding.GetBytes(dataItem)); ApplicationLogging.CreateLogger <LineEventsController>().LogInformation($"push:{dataItem},result:{(result != null ? encoding.GetString(result) : "")}"); } } else { ApplicationLogging.CreateLogger <LineEventsController>().LogWarning($"device without line ID:{item.PID}"); } return(Content("OK!")); }
public void TestConstructorNullCheck() { ILogger <HttpDataService> logger = ApplicationLogging.CreateLogger <HttpDataService>(); var options = new Mock <IOptions <AppSettings> >(MockBehavior.Strict); options.Setup(m => m.Value).Returns(new AppSettings() { Contact = "*****@*****.**" }); Assert.Throws <ArgumentNullException>(() => { var x = new HttpDataService(null, logger); }); Assert.Throws <ArgumentNullException>(() => { var x = new HttpDataService(options.Object, null); }); }
protected override async Task OnAfterRenderAsync(bool firstRender) { var logger = ApplicationLogging.CreateLogger <App>(); logger.LogInformation("Initializing App component..."); await ReduxDevToolsInterop.InitAsync(); await JsonRequestHandler.InitAsync(); logger.LogInformation("Initializing App component...done"); }
public ActionResult CommitMember(EnterpriseGroupMemberViewModel viewModel) { if (!viewModel.UID.HasValue) { return(View("~/Views/Shared/JsAlert.cshtml", model: "請選擇學員!!")); } var item = models.GetTable <EnterpriseCourseContract>().Where(c => c.ContractID == viewModel.ContractID).FirstOrDefault(); if (item == null) { return(View("~/Views/Shared/JsAlert.cshtml", model: "合約資料錯誤!!")); } try { var member = item.EnterpriseCourseMember.Where(m => m.UID == viewModel.UID).FirstOrDefault(); if (member == null) { member = new EnterpriseCourseMember { ContractID = item.ContractID, UID = viewModel.UID.Value }; models.GetTable <EnterpriseCourseMember>().InsertOnSubmit(member); models.SubmitChanges(); } checkMemberLesson(member); var groupMember = item.EnterpriseCourseMember.Where(m => m.UID == viewModel.GroupUID).FirstOrDefault(); if (groupMember != null) { if (groupMember.GroupingLesson == null) { groupMember.GroupingLesson = new GroupingLesson { }; } member.GroupingLesson = groupMember.GroupingLesson; models.SubmitChanges(); matchGroup(groupMember, member); } return(Json(new { result = true })); } catch (Exception ex) { ApplicationLogging.CreateLogger <EnterpriseProgramController>().LogError(ex, ex.Message);; return(Json(new { result = false, message = ex.Message })); } }
public async Task <ActionResult> DeleteCourseContractAsync(CourseContractViewModel viewModel) { ViewBag.ViewModel = viewModel; if (viewModel.KeyID != null) { viewModel.ContractID = viewModel.DecryptKeyValue(); } var profile = await HttpContext.GetUserAsync(); bool result = false; try { var item = models.GetTable <CourseContract>().Where(d => d.ContractID == viewModel.ContractID).FirstOrDefault(); if (item != null) { if (item.CourseContractRevision != null && item.FitnessConsultant != profile.UID) { if (item.CourseContractRevision.Reason == "展延") { var jsonData = await this.RenderViewToStringAsync("~/Views/LineEvents/Message/NotifyCoachToRejectExtend.cshtml", item.CourseContractRevision.SourceContract); jsonData.PushLineMessage(); } else if (item.CourseContractRevision.Reason == "終止") { var jsonData = await this.RenderViewToStringAsync("~/Views/LineEvents/Message/NotifyCoachToRejectTermination.cshtml", item.CourseContractRevision.SourceContract); jsonData.PushLineMessage(); } else if (item.CourseContractRevision.Reason == "轉換體能顧問") { var jsonData = await this.RenderViewToStringAsync("~/Views/LineEvents/Message/NotifyCoachToRejectAssignment.cshtml", item); jsonData.PushLineMessage(); } } models.ExecuteCommand("delete CourseContract where ContractID = {0}", item.ContractID); result = true; ClearPreliminaryMember(); } } catch (Exception ex) { ApplicationLogging.CreateLogger <CourseContractController>().LogError(ex, ex.Message); } return(Json(new { result })); }