public async Task A_consumer_is_being_tested() { _loggerMock = LoggerUtils.LoggerMock<PersonSearchCompletedConsumer>(); _searchApiNotifierMock = new Mock<ISearchApiNotifier<PersonSearchAdapterEvent>>(); _harness = new InMemoryTestHarness(); _requestId = Guid.NewGuid(); var fakePersonSearchStatus = new FakePersonSearchCompleted { SearchRequestId = _requestId, TimeStamp = DateTime.Now }; _sut = _harness.Consumer(() => new PersonSearchCompletedConsumer(_searchApiNotifierMock.Object, _loggerMock.Object)); await _harness.Start(); await _harness.BusControl.Publish<PersonSearchCompleted>(fakePersonSearchStatus); }
public async Task A_consumer_is_being_tested() { _loggerMock = LoggerUtils.LoggerMock <PersonSearchSubmittedConsumer>(); _searchApiNotifierMock = new Mock <ISearchApiNotifier <PersonSearchAdapterEvent> >(); _harness = new InMemoryTestHarness(); _requestKey = "111111_000000"; var fakePersonSearchStatus = new FakePersonSearchSubmitted { SearchRequestKey = _requestKey, TimeStamp = DateTime.Now, Message = "fake person search submitted" }; _harness.Consumer(() => new PersonSearchSubmittedConsumer(_searchApiNotifierMock.Object, _loggerMock.Object)); await _harness.Start(); await _harness.BusControl.Publish <PersonSearchSubmitted>(fakePersonSearchStatus); }
/// <summary> /// 根据门店编号获取信息 /// </summary> /// <param name="shopId">门店编号</param> /// <returns>操作结果</returns> public Result <Shop> GetShopInfoById(int shopId) { Result <Shop> result = new Result <Shop>() { Status = false, Message = "没有获取到对应信息" }; try { if (shopId == 0) { throw new ArgumentException("查询门店信息,参数非法"); } IShopCache shopservice = ServiceObjectContainer.Get <IShopCache>(); ShopInfo shopcache = shopservice.GetshopInfoByShopId(shopId); if (shopcache != null) { result.Data = shopcache.Copy <Shop>(); result.Status = true; } else { result.Data = null; result.Status = false; result.Message = "没有获取到对应信息"; } } catch (Exception ex) { result.Data = null; result.Status = false; result.Message = "获取门店信息出错:" + ex.Message; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:GetShopInfoById() .ShopService"), LogType.ErrorLog); } return(result); }
/// <summary> /// Application startup hook. /// </summary> /// <param name="container"> /// The inversion of control container. /// </param> /// <param name="pipelines"> /// The pipelines. /// </param> protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines) { // No registrations should be performed in here, however you may resolve things that are needed during application startup. var cdp4WebServiceAuthentication = container.Resolve <ICDP4WebServiceAuthentication>(); // hook up the basic authentication cdp4WebServiceAuthentication.Enable( pipelines, new CDP4WebServiceAuthenticationConfiguration(container.Resolve <IUserValidator>(), Realm), new[] { SiteDirectoryRoute, EngineeringModelRoute }); // hook up the on error handler pipelines.OnError += (ctx, ex) => { // log any uncatched errors var credentials = ctx.CurrentUser as Credentials; var subject = credentials != null ? credentials.Person : null; var headerInforProvider = container.Resolve <IHeaderInfoProvider>(); var requestMessage = string.Format( "[{0}][{1}{2}]", ctx.Request.Method, ctx.Request.Url.Path, ctx.Request.Url.Query); Logger.Fatal(ex, LoggerUtils.GetLogMessage(subject, ctx.Request.UserHostAddress, false, requestMessage)); var errorResponse = new JsonResponse(string.Format("exception:{0}", ex.Message), new DefaultJsonSerializer()); headerInforProvider.RegisterResponseHeaders(errorResponse); return(errorResponse.WithStatusCode(HttpStatusCode.InternalServerError)); }; // clear all view location conventions (to save on irrelevant locations being visited) and supply the Views convention to use this.Conventions.ViewLocationConventions.Clear(); this.Conventions.ViewLocationConventions.Add( (viewName, model, context) => string.Format("Views/{0}", viewName)); // add the folder for the static content containing the compiled app this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("assets")); MigrationEngine.MigrateAllAtStartUp(); }
public async Task <Result <string> > Register(AccommodationBookingRequest bookingRequest, AgentContext agentContext, string languageCode) { Baggage.AddSearchId(bookingRequest.SearchId); _logger.LogCreditCardBookingFlowStarted(bookingRequest.HtId); var(_, isFailure, booking, error) = await GetCachedAvailability(bookingRequest) .Ensure(IsPaymentTypeAllowed, "Payment type is not allowed") .Bind(Register) .Check(SendEmailToPropertyOwner) .Finally(WriteLog); if (isFailure) { return(Result.Failure <string>(error)); } return(booking.ReferenceCode); async Task <Result <BookingAvailabilityInfo> > GetCachedAvailability(AccommodationBookingRequest bookingRequest) => await _evaluationStorage.Get(bookingRequest.SearchId, bookingRequest.HtId, bookingRequest.RoomContractSetId); bool IsPaymentTypeAllowed(BookingAvailabilityInfo availabilityInfo) => availabilityInfo.AvailablePaymentTypes.Contains(PaymentTypes.CreditCard); Task <Result <Booking> > Register(BookingAvailabilityInfo bookingAvailability) => _registrationService.Register(bookingRequest, bookingAvailability, PaymentTypes.CreditCard, agentContext, languageCode); async Task <Result> SendEmailToPropertyOwner(Booking booking) => await _bookingConfirmationService.SendConfirmationEmail(booking); Result <Booking> WriteLog(Result <Booking> result) => LoggerUtils.WriteLogByResult(result, () => _logger.LogBookingRegistrationSuccess(result.Value.ReferenceCode), () => _logger.LogBookingRegistrationFailure(bookingRequest.HtId, bookingRequest.ItineraryNumber, bookingRequest.MainPassengerName, result.Error)); }
/// <summary> /// 筛选门店热门食物 /// </summary> /// <param name="shopId">门店编号</param> /// <returns></returns> Result <IList <Dish> > IShakeService.ShakePopDishForShop(int shopId) { Result <IList <Dish> > result = new Result <IList <Dish> >() { Data = new List <Dish>(), Status = true, Message = "筛选门店热门单品成功", StatusCode = "SPD000" }; try { if (shopId == 0) { throw new ArgumentNullException("删选门店编号参数无法为0"); } //食谱缓存服务 IDishCache dishcache = ServiceObjectContainer.Get <IDishCache>(); //从缓存里加载所有单品 IList <Dish> dishlist = dishcache.GetDishInfoByShop(shopId).CopyList <DishInfo, Dish>(); if (dishlist != null && dishlist.Count > 0) { //降序修改时间排列 取前4 result.Data = dishlist.OrderByDescending(o => o.UpdateDate).Take(4).ToList(); } } catch (Exception ex) { result.Status = false; result.Message = "筛选门店热门单品失败," + ex.Message; result.StatusCode = "SPD001"; //记录日志 LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:ShakePopDishForShop() .ShakeService"), LogType.ErrorLog); } return(result); }
static void Main(string[] args) { Console.Title = "ArcticEmu | AuthServer."; LogManager.Configuration = LoggerUtils.GetConfig(); _logger.Warn("Starting up ArcticEmu.Auth.."); using (var server = new Server <ClientHandler>(new IPEndPoint(IPAddress.Any, 55999))) { server.StartAccepting(); while (_isRunning) { switch (Console.ReadLine()) { case "quit": _isRunning = false; server.Dispose(); break; } } } }
/// <summary> /// 根据手机号获取用户的食谱集 /// </summary> /// <param name="phone"></param> /// <returns></returns> public Result <IList <Recipes> > GetRecipesByPhone(long phone) { Result <IList <Recipes> > result = new Result <IList <Recipes> >() { Status = true, Message = "查找食谱成功" }; try { //食谱缓存服务 IRecipesCache recipesservice = ServiceObjectContainer.Get <IRecipesCache>(); if (phone == 0) { throw new ArgumentException("获取食谱,参数非法"); } IList <RecipesInfo> recipeslist = recipesservice.GetRecipesInfoByPhone(phone); if (recipeslist != null && recipeslist.Count > 0) { result.Data = recipeslist.CopyList <RecipesInfo, Recipes>(); } else { result.Status = false; result.Message = "获取食谱失败,未找到对应食谱"; result.Data = new List <Recipes>(); } } catch (Exception ex) { result.Status = false; result.Message = "查找食谱出错:" + ex.Message; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:GetRecipesByPhone() .RecipesService"), LogType.ErrorLog); } return(result); }
///<summary> /// 添加附件 ///</summary> ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param> public void AddAttachments(string attachmentsPath) { try { string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义 Attachment data; ContentDisposition disposition; for (int i = 0; i < path.Length; i++) { data = new Attachment(path[i], MediaTypeNames.Application.Octet); disposition = data.ContentDisposition; disposition.CreationDate = File.GetCreationTime(path[i]); disposition.ModificationDate = File.GetLastWriteTime(path[i]); disposition.ReadDate = File.GetLastAccessTime(path[i]); mMailMessage.Attachments.Add(data); } } catch (Exception ex) { LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At function:AddAttachments(string attachmentsPath) .OpporunMail 89 rows"), LogType.ErrorLog); } }
public HttpResponseMessage Get(string id) { try { LoggerUtils.WriteLog("CustomersController : GET BY ID - request received"); var customer = customerService.Get(id); if (customer != null) { return(Request.CreateResponse(HttpStatusCode.OK, customer)); } return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Customer not found for provided id.")); } catch (Exception ex) { LoggerUtils.WriteLog("ERROR : CustomersController : " + ex.Message + "\r" + "InnerException : " + ex.InnerException); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
/// <summary> /// 根据食谱编号获取单个食谱信息 /// </summary> /// <param name="recipesId"></param> /// <returns></returns> public Result <Recipes> GetRecipesById(int recipesId) { Result <Recipes> result = new Result <Recipes>() { Status = true, Message = "查找食谱成功" }; try { if (recipesId == 0) { throw new ArgumentException("获取食谱,参数非法"); } //食谱缓存服务 IRecipesCache recipesservice = ServiceObjectContainer.Get <IRecipesCache>(); RecipesInfo recipe = recipesservice.GetRecipesInfoById(recipesId); if (recipe != null) { result.Data = recipe.Copy <Recipes>(); } else { result.Status = false; result.Message = "获取食谱失败,未找到对应食谱"; } } catch (Exception ex) { result.Status = false; result.Message = "查找食谱出错:" + ex.Message; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:GetRecipesById() .RecipesService"), LogType.ErrorLog); } return(result); }
/// <summary> /// 根据食谱编号获取收藏的单品集合 /// </summary> /// <param name="recipesId"></param> /// <returns></returns> public Result <IList <Dish> > GetCollectDishList(int recipesId) { Result <IList <Dish> > result = new Result <IList <Dish> >() { Data = new List <Dish>(), Message = "查询单品信息集合成功", Status = true }; try { //获取分享关系集合 IRelationShareInfoCache relationcache = ServiceObjectContainer.Get <IRelationShareInfoCache>(); IList <RelationShareInfo> relationshares = relationcache.GetRelationShareByReceipId(recipesId); //查询单品信息 if (relationshares != null && relationshares.Count > 0) { IDishCache dishcache = ServiceObjectContainer.Get <IDishCache>(); IList <int> dishIds = new List <int>(); foreach (var share in relationshares) { DishInfo dish = dishcache.GetDishInfoById(share.DishId); result.Data.Add(dish.Copy <Dish>()); } } } catch (Exception ex) { result.Status = false; result.Message = "查询分享单品食物出错:" + ex.Message; result.StatusCode = "GSD001"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:GetCollectDishList() .DishService"), LogType.ErrorLog); } return(result); }
/// <summary> /// Loads all custom sprites /// </summary> private void LoadSprites() { bool spriteSuccess = true; //TODO: Replace with a loader function( JSON mapping available ) //We probably need this before we load any displays DynamicSignConfig.LoadVmsMsgList(); RouteShieldConfig.LoadRouteShieldInfo(); String[] files = Directory.GetFiles(FileUtils.GetModPath() + Path.DirectorySeparatorChar + "Icons"); foreach (string file in files) { string[] splitValues = file[0] == Path.DirectorySeparatorChar ? file.Substring(1).Split(Path.DirectorySeparatorChar) : file.Split(Path.DirectorySeparatorChar); string fileName = splitValues[splitValues.Length - 1]; string fileKey = fileName.Split('.')[0]; spriteSuccess = SpriteUtils.AddTexture(file, fileKey) && spriteSuccess; if (!RouteShieldConfig.Instance().routeShieldDictionary.ContainsKey(fileKey)) { RouteShieldConfig.Instance().routeShieldDictionary[fileKey] = new RouteShieldInfo(fileKey); } } //TODO: When we need it, load a json descriptor file for relevant shaders here ShaderUtils.AddShader("Shaders/font", "font"); //TODO: When we need it, load a json descriptor file for relevant fonts here FontUtils.AddFonts(); if (!spriteSuccess) { LoggerUtils.LogError("Failed to load some sprites!"); } else { RouteShieldConfig.SaveRouteShieldInfo(); } }
/// <summary> /// 更改背景图 /// </summary> /// <param name="backCoverbase64str"></param> /// <param name="account"></param> /// <returns></returns> public Result UpdateBackCover(string backCoverbase64str, string account) { Result result = new Result() { Status = true, Message = "更改背景图成功", StatusCode = "UB001" }; try { result.Status = DBConnectionManager.Instance.Writer.Update(new AccountUpdateImageSpefication(backCoverbase64str, account, 1).Satifasy()); if (result.Status) { //更新缓存 IAccountInfoCache service = ServiceObjectContainer.Get <IAccountInfoCache>(); IOnlineAccountCache onlineservice = ServiceObjectContainer.Get <IOnlineAccountCache>(); AccountInfo accountcache = service.SearchInfoByKey(string.Format("DB_AI_{0}", account)); if (accountcache != null) { accountcache.BackCorver = backCoverbase64str; //保存 service.SaveInfo(accountcache); onlineservice.SaveInfo(accountcache.Copy <OnlineAccountInfo>()); } } } catch (Exception ex) { result.Status = false; result.Message = "修改背景图出错" + ex.Message; result.StatusCode = "UB000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:UpdateBackCover() .AccountService"), LogType.ErrorLog); } return(result); }
/// <summary> /// 检查手机是否被注册 /// </summary> /// <param name="phone"></param> /// <returns></returns> public Result CheckPhoneRegisted(string phone) { Result result = new Result() { Status = true, }; try { //检验缓存是否存在 IAccountInfoCache service = ServiceObjectContainer.Get <IAccountInfoCache>(); //存在,返回结果为false result.Status = !service.CheckPhoneExists(phone); } catch (Exception ex) { result.Status = false; result.Message = "手机验证出错" + ex.Message; result.StatusCode = "CMR000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:CheckPhoneRegisted() .AccountService"), LogType.ErrorLog); } return(result); }
private async Task UninstallProgramsAsync(DataGrid uninstallDataGrid) { if ((uint)uninstallDataGrid.SelectedItems.Count <= 0U) { return; } try { ObservableCollection <NameObject> selectedItemsList = new ObservableCollection <NameObject>(); this.CopyListToList(uninstallDataGrid.SelectedItems, (IList)selectedItemsList); this.UninstallBarInProgress = true; if (this.IsDependencyFound(selectedItemsList)) { this.UninstallBarInProgress = false; } else { LoggerUtils.LogMessage("Uninstall opperation will start", (LogLevel)LogLevel.Info, UninstallerViewModel.logger); Stopwatch watch = Stopwatch.StartNew(); await this.UninstallListOfPrograms(selectedItemsList); watch.Stop(); DateTime elapsedTime = DateTime.MinValue.AddMilliseconds((double)watch.ElapsedMilliseconds); Dialogs.ElapsedTime("Uninstall opperation", elapsedTime, UninstallerViewModel.logger); selectedItemsList = (ObservableCollection <NameObject>)null; watch = (Stopwatch)null; } } catch (Exception ex) { Dialogs.UnknownError(ex.Message, UninstallerViewModel.logger); } finally { this.UninstallBarInProgress = false; } }
/// <summary> /// 更新账户信息 (不包括背景图像和头像) /// </summary> /// <param name="account"></param> /// <returns></returns> public Result UpdateAccountInfo(Account account) { Result result = new Result() { Status = true, Message = "更新账户信息成功", StatusCode = "UA001" }; try { AccountInfo info = account.Copy <AccountInfo>(); result.Status = DBConnectionManager.Instance.Writer.Update(new AccountUpdateInfoSpefication(info).Satifasy()); if (result.Status) { DBConnectionManager.Instance.Writer.Commit(); //更新缓存 IAccountInfoCache service = ServiceObjectContainer.Get <IAccountInfoCache>(); service.UpdateAccount(info); IOnlineAccountCache onlineservice = ServiceObjectContainer.Get <IOnlineAccountCache>(); onlineservice.UpdateOnlineAccount(info.Copy <OnlineAccountInfo>()); } } catch (Exception ex) { result.Status = false; result.Message = "修改账户信息出错" + ex.Message; result.StatusCode = "UA000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:UpdateAccountInfo() .AccountService"), LogType.ErrorLog); } return(result); }
public async Task A_consumer_is_being_tested() { _loggerMock = LoggerUtils.LoggerMock <PersonSearchInformationConsumer>(); _searchApiNotifierMock = new Mock <ISearchApiNotifier <PersonSearchAdapterEvent> >(); _harness = new InMemoryTestHarness(); _requestKey = "111111_000000"; var fakePersonSearchStatus = new FakePersonSearchInformation { SearchRequestKey = _requestKey, TimeStamp = DateTime.Now, Message = "code : fake person search information recieved", ProviderProfile = new FakeProviderProfile { Name = "JCA", SearchSpeedType = SearchSpeedType.Slow } }; _harness.Consumer(() => new PersonSearchInformationConsumer(_searchApiNotifierMock.Object, _loggerMock.Object)); await _harness.Start(); await _harness.BusControl.Publish <PersonSearchInformation>(fakePersonSearchStatus); }
protected override void Awake() { base.Awake(); LoggerUtils.Log("Initialising RoadRenderingManager"); if (!LoadPropMeshes()) { LoggerUtils.LogError("Failed to load some props!"); } else { LoggerUtils.Log("Props loaded!"); } replaceProp(ModSettings.Instance().settings.Contains("loadMotorwaySigns") ? (bool)ModSettings.Instance().settings["loadMotorwaySigns"] : true); DistrictManager districtManager = DistrictManager.instance; ShaderUtils.m_shaderStore.Add("fallback", districtManager.m_properties.m_areaNameShader); //Only start dynamic signs after everything's loaded RenderingManager.instance.initTimer(); }
public void AddRunningLog(string category, object message) { Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(category)); try { //XmlSerializer xs = new XmlSerializer(); // 使用基础设施框架层面重写提供的序列化工具(不可第三方) /* * 先注明本算法支持深层次嵌套类型序列化 你需要值得注意与有趣之处在于 * 1、它是对于.NET/XML序列化的扩充(支持.NET/XML序列化的特性) * 2、它的设计目的是架设于XML/DI技术层面(与Spring相类似) * 3、它可以序列化对象型数组并加以反向序列化 */ //string messagestr = string.Empty; // var lgr = xs.Deserialize<Logger>(message); //if (message != null) //{ // messagestr = xs.Serializable(message); //} AddSystemLoggerSpeficaiton logger = new AddSystemLoggerSpeficaiton(); DBConnectionManager.Instance.Writer.Insert(logger.Satifasy(), DBConnectionManager.Instance.Writer.CreateParameter("@category", category, DbType.String), DBConnectionManager.Instance.Writer.CreateParameter("@message", message, DbType.String), DBConnectionManager.Instance.Writer.CreateParameter("@createdate", DateTime.Now, DbType.DateTime)); { DBConnectionManager.Instance.Writer.Commit(); // 提交更改 } } catch (Exception ex) // { LoggerUtils.ColectExceptionMessage(ex, "At service:AddRunningLog() .LoggerService"); //DBConnectionManager.Instance.Writer.Rollback(); // 回滚更改 } }
/// <summary> /// 登陆 /// </summary> /// <param name="signInCode"></param> /// <param name="securityCode"></param> /// <returns></returns> public Result <Account> SignIn(string signInCode, string securityCode) { Result <Account> result = new Result <Account>() { Status = false }; try { //1.检查是否已经登录 IOnlineAccountCache service = ServiceObjectContainer.Get <IOnlineAccountCache>(); IAccountInfoCache accountservice = ServiceObjectContainer.Get <IAccountInfoCache>(); string phonekey = string.Format("OnlineAI_{0}_*", signInCode); string emailkey = string.Format("OnlineAI_*_{0}", signInCode); string securityCodeMD5 = MD5Engine.ToMD5String(securityCode); OnlineAccountInfo onlineinfo = null; onlineinfo = service.SearchInfoByKey(phonekey); if (onlineinfo == null) { onlineinfo = service.SearchInfoByKey(emailkey); } if (onlineinfo == null) { //2.直接从数据库拿数据 IList <AccountInfo> inforesult = DBConnectionManager.Instance.Reader.Select <AccountInfo>(new AccountSelectSpefication(3, signInCode, securityCodeMD5).Satifasy()); if (inforesult != null && inforesult.Count > 0) { result.Status = true; result.Data = inforesult[0].Copy <Account>(); //保存到缓存 service.SaveInfo(inforesult[0].Copy <OnlineAccountInfo>()); accountservice.SaveInfo(inforesult[0]); } else { result.Message = "用户名或密码错误"; result.StatusCode = "LG000"; } } else { //校验密码 if (onlineinfo.SecurityCode != securityCodeMD5) { result.Message = "密码错误"; result.StatusCode = "LG000"; result.Data = null; } else { //返回结果 result.Status = true; result.Data = onlineinfo.Copy <Account>(); } } } catch (Exception ex) { result.Status = false; result.Data = null; result.Message = ex.Message; result.StatusCode = "EX000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:SignIn() .AccountService"), LogType.ErrorLog); } return(result); }
private static void Main(string[] args) { var logger = LoggerUtils.GetLogger("QuizizzHack"); LoggerUtils.PrintSystemInformation(); LoggerUtils.RegisterExceptionHandler(); if (File.Exists("answers.txt")) { File.Delete("answers.txt"); } var id = logger.GetInput("Quizizz id:"); var wc = new WebClient(); var jsonData = wc.DownloadString("https://quizizz.com/quiz/" + id); var data = QuizizzData.FromJson(jsonData); if (!data.Success) { logger.Error("Failed to fetch data from quizizz!"); Environment.Exit(-1); } logger.Success("Data fetched successfully!"); var quizData = $"Quiz name: {data.Data.Quiz.Info.Name}\nLast update date: {data.Data.Quiz.Info.Updated}"; var creatorInfo = $"Creator username: {data.Data.Quiz.CreatedBy.Local.CasedUsername}\nName: {data.Data.Quiz.CreatedBy.FirstName + " " + data.Data.Quiz.CreatedBy.LastName}"; var playedTimes = $"Times played: {data.Data.Quiz.Stats.Played} ({data.Data.Quiz.Stats.TotalPlayers})"; var totalQuestions = "\n\nTotal questions: {0}"; logger.Info(quizData); logger.Info(creatorInfo); logger.Info(playedTimes); File.AppendAllText("answers.txt", quizData + "\n" + creatorInfo + "\n\n\nAnswers:\n\n\n"); logger.Warn("\n\nPrinting answers...\n\n"); var re = new Regex(@"<[/\w]+>"); var i = 0; foreach (var question in data.Data.Quiz.Info.Questions) { var q = re.Replace(question.Structure.Query.Text, ""); var b = new StringBuilder(); if (question.Structure.Answer.IntegerArray?.Any() == true) { var end = question.Structure.Answer.IntegerArray.LastOrDefault(); foreach (var l in question.Structure.Answer.IntegerArray) { b.Append(question.Structure.Options[(int)l].Text); if (l != end) { b.Append(", "); } } } else { b.Append(question.Structure.Settings.HasCorrectAnswer ? question.Structure.Options[(int)(question.Structure.Answer.Integer ?? 0)].Text : "no correct answer"); } var ans = re.Replace(b.ToString(), ""); var str = ">>> " + q + " <<< === >>> " + ans + " <<<"; logger.Info(str); File.AppendAllText("answers.txt", str + "\n"); ++i; } totalQuestions = string.Format(totalQuestions, i); File.AppendAllText("answers.txt", totalQuestions); logger.Warn("\n{0}\n\n\nEverything is done!", totalQuestions); }
void Application_End(object sender, EventArgs e) { LoggerUtils.GetLogger().Debug("Application is shutting down."); }
Result <PaymentResponse> WriteLog(Result <PaymentResponse> result) { return(LoggerUtils.WriteLogByResult(result, () => _logger.LogCreditCardAuthorizationSuccess(request.ReferenceCode), () => _logger.LogCreditCardAuthorizationFailure(request.ReferenceCode, result.Error))); }
public void HideConsole() { isConsoleVisible = false; LoggerUtils.FreeConsole(); initialized = false; }
public async Task <Result <AccommodationBookingInfo, ProblemDetails> > Finalize(string referenceCode, AgentContext agentContext, string languageCode) { var(_, isGetBookingFailure, booking, getBookingError) = await GetAgentsBooking() .Ensure(b => agentContext.AgencyId == b.AgencyId, ProblemDetailsBuilder.Build("The booking does not belong to your current agency")) .Bind(CheckBookingIsPaid) .OnFailure(WriteLogFailure); if (isGetBookingFailure) { return(Result.Failure <AccommodationBookingInfo, ProblemDetails>(getBookingError)); } return(await BookOnProvider(booking, referenceCode, languageCode) .Tap(ProcessResponse) .Bind(CaptureMoneyIfDeadlinePassed) .OnFailure(VoidMoneyAndCancelBooking) .Bind(GenerateInvoice) .Tap(NotifyOnCreditCardPayment) .Bind(GetAccommodationBookingInfo) .Finally(WriteLog)); Task <Result <Data.Booking.Booking, ProblemDetails> > GetAgentsBooking() => _bookingRecordsManager.GetAgentsBooking(referenceCode, agentContext).ToResultWithProblemDetails(); Result <Data.Booking.Booking, ProblemDetails> CheckBookingIsPaid(Data.Booking.Booking bookingFromPipe) { if (bookingFromPipe.PaymentStatus == BookingPaymentStatuses.NotPaid) { _logger.LogBookingFinalizationPaymentFailure($"The booking with reference code: '{referenceCode}' hasn't been paid"); return(ProblemDetailsBuilder.Fail <Data.Booking.Booking>("The booking hasn't been paid")); } return(bookingFromPipe); } Task ProcessResponse(Booking bookingResponse) => _bookingResponseProcessor.ProcessResponse(bookingResponse, booking); async Task <Result <EdoContracts.Accommodations.Booking, ProblemDetails> > CaptureMoneyIfDeadlinePassed(EdoContracts.Accommodations.Booking bookingInPipeline) { var daysBeforeDeadline = Infrastructure.Constants.Common.DaysBeforeDeadlineWhenPayForBooking; var now = _dateTimeProvider.UtcNow(); var deadlinePassed = booking.CheckInDate <= now.AddDays(daysBeforeDeadline) || (booking.DeadlineDate.HasValue && booking.DeadlineDate.Value.Date <= now.AddDays(daysBeforeDeadline)); if (!deadlinePassed) { return(bookingInPipeline); } var(_, isPaymentFailure, _, paymentError) = await _bookingPaymentService.Capture(booking, agentContext.ToUserInfo()); if (isPaymentFailure) { return(ProblemDetailsBuilder.Fail <EdoContracts.Accommodations.Booking>(paymentError)); } return(bookingInPipeline); } Task VoidMoneyAndCancelBooking(ProblemDetails problemDetails) => this.VoidMoneyAndCancelBooking(booking, agentContext); async Task <Result <Booking, ProblemDetails> > NotifyOnCreditCardPayment(Booking details) { await _bookingMailingService.SendCreditCardPaymentNotifications(details.ReferenceCode); return(details); } Task <Result <Booking, ProblemDetails> > GenerateInvoice(Booking details) => this.GenerateInvoice(details, referenceCode, agentContext); Task <Result <AccommodationBookingInfo, ProblemDetails> > GetAccommodationBookingInfo(Booking details) => _bookingRecordsManager.GetAccommodationBookingInfo(details.ReferenceCode, languageCode) .ToResultWithProblemDetails(); void WriteLogFailure(ProblemDetails problemDetails) => _logger.LogBookingByAccountFailure($"Failed to finalize a booking with reference code: '{referenceCode}'. Error: {problemDetails.Detail}"); Result <T, ProblemDetails> WriteLog <T>(Result <T, ProblemDetails> result) => LoggerUtils.WriteLogByResult(result, () => _logger.LogBookingFinalizationSuccess($"Successfully finalized a booking with reference code: '{referenceCode}'"), () => _logger.LogBookingFinalizationFailure( $"Failed to finalize a booking with reference code: '{referenceCode}'. Error: {result.Error.Detail}")); }
/// <summary> /// 注册账户信息 /// </summary> /// <param name="account"></param> /// <returns></returns> public Result <Account> RegistInfo(RegistRequest request) { Result <Account> result = new Result <Account>() { Status = true, Message = "注册账户成功", Data = null, StatusCode = "RR000" }; AccountInfo account = new AccountInfo(); account.Phone = Int64.Parse(request.Phone); account.Email = request.Email; account.SecurityCode = MD5Engine.ToMD5String(request.SecurityCode); account.CreatDate = DateTime.Now; account.BirthdayDate = DateTime.Parse("2000-01-01"); account.Avator = ConstInfo.DefaultHeadBase64; account.BackCorver = ConstInfo.DefaultBackCover; account.Sex = Model.Enum.AccountSex.Male.GetHashCode(); account.RequiredStatus = Model.Enum.AccountRequiredStatus.UnRequired.GetHashCode(); account.Description = ""; account.NickName = request.Phone; //加入数据库 try { IAccountInfoCache service = ServiceObjectContainer.Get <IAccountInfoCache>(); if (service.SearchInfoByKey(account.GetKeyName()) == null) { //入库 result.Status = DBConnectionManager.Instance.Writer.Insert(new AccountAddSpefication(account).Satifasy()); if (result.Status) { DBConnectionManager.Instance.Writer.Commit(); //加入缓存 service.SaveInfo(account); result.Data = account.Copy <Account>(); } } else { result.Status = false; result.Message = "当前账户已存在"; result.StatusCode = "RR001"; } } catch (Exception ex) { DBConnectionManager.Instance.Writer.Rollback(); result.Status = false; result.Message = ex.Message; result.StatusCode = "EX000"; LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:RegistInfo() .AccountService"), LogType.ErrorLog); } return(result); }
public void Initialize() { if (initialized) { return; } IntPtr hwnd = LoggerUtils.GetConsoleWindow(); initialized = true; // Console app if (hwnd != IntPtr.Zero) { buffer = LoggerUtils.GetStdHandle(LoggerUtils.STD_OUTPUT_HANDLE); return; } // Windows app bool success = LoggerUtils.AllocConsole(); handleRoutine = new HandlerRoutine(Handler); LoggerUtils.SetConsoleCtrlHandler(handleRoutine, true); this.Visible = false; if (!success) { return; } buffer = LoggerUtils.CreateConsoleScreenBuffer(LoggerUtils.GENERIC_READ | LoggerUtils.GENERIC_WRITE, LoggerUtils.FILE_SHARE_READ | LoggerUtils.FILE_SHARE_WRITE, IntPtr.Zero, LoggerUtils.CONSOLE_TEXTMODE_BUFFER, IntPtr.Zero); bool result = LoggerUtils.SetConsoleActiveScreenBuffer(buffer); //Set console output buffer size IntPtr handle = LoggerUtils.CreateFile( "CONOUT$", // name LoggerUtils.GENERIC_WRITE | LoggerUtils.GENERIC_READ, // desired access LoggerUtils.FILE_SHARE_WRITE | LoggerUtils.FILE_SHARE_READ, // share access null, // no security attributes LoggerUtils.OPEN_EXISTING, // device already exists 0, // no flags or attributes IntPtr.Zero); // no template file. consoleHandle = new SafeFileHandle(handle, true); const UInt16 conWidth = 256; const UInt16 conHeight = 2500; Coord dwSize = new Coord(conWidth, conHeight); LoggerUtils.SetConsoleScreenBufferSize(consoleHandle.DangerousGetHandle(), dwSize); LoggerUtils.SetStdHandle(LoggerUtils.STD_OUTPUT_HANDLE, buffer); LoggerUtils.SetStdHandle(LoggerUtils.STD_ERROR_HANDLE, buffer); Title = "Logger Console"; Stream s = Console.OpenStandardInput(LoggerUtils._DefaultConsoleBufferSize); StreamReader reader = null; if (s == Stream.Null) { reader = StreamReader.Null; } else { reader = new StreamReader(s, Encoding.GetEncoding(LoggerUtils.GetConsoleCP()), false, LoggerUtils._DefaultConsoleBufferSize); } Console.SetIn(reader); // Set up Console.Out StreamWriter writer = null; s = Console.OpenStandardOutput(LoggerUtils._DefaultConsoleBufferSize); if (s == Stream.Null) { writer = StreamWriter.Null; } else { writer = new StreamWriter(s, Encoding.GetEncoding(LoggerUtils.GetConsoleOutputCP()), LoggerUtils._DefaultConsoleBufferSize); writer.AutoFlush = true; } Console.SetOut(writer); s = Console.OpenStandardError(LoggerUtils._DefaultConsoleBufferSize); if (s == Stream.Null) { writer = StreamWriter.Null; } else { writer = new StreamWriter(s, Encoding.GetEncoding(LoggerUtils.GetConsoleOutputCP()), LoggerUtils._DefaultConsoleBufferSize); writer.AutoFlush = true; } Console.SetError(writer); // // Disable Close as this would close the main app also // hwnd = LoggerUtils.GetConsoleWindow(); IntPtr hMenu = LoggerUtils.GetSystemMenu(hwnd, false); LoggerUtils.DeleteMenu(hMenu, LoggerUtils.SC_CLOSE, LoggerUtils.MF_BYCOMMAND); NativeMethods.SetWindowPos(hwnd, new IntPtr(-1), 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE); }
public async Task <Result <AccommodationBookingInfo, ProblemDetails> > BookByAccount(AccommodationBookingRequest bookingRequest, AgentContext agentContext, string languageCode, string clientIp) { string availabilityId = default; DateTime?availabilityDeadline = default; DateTime availabilityCheckIn = default; string referenceCode = default; var wasPaymentMade = false; var settings = await _accommodationBookingSettingsService.Get(agentContext); // TODO Remove lots of code duplication in account and card purchase booking var(_, isRegisterFailure, booking, registerError) = await GetCachedAvailability(bookingRequest, agentContext) .Ensure(AreAprSettingsSuitable, ProblemDetailsBuilder.Build("You can't book the restricted contract without explicit approval from a Happytravel.com officer.")) .Ensure(AreDeadlineSettingsSuitable, ProblemDetailsBuilder.Build("You can't book the contract within deadline without explicit approval from a Happytravel.com officer.")) .Tap(FillAvailabilityLocalVariables) .Map(ExtractBookingAvailabilityInfo) .BindWithTransaction(_context, info => Result.Success <BookingAvailabilityInfo, ProblemDetails>(info) .Map(RegisterBooking) .Bind(GetBooking) .Bind(PayUsingAccountIfDeadlinePassed)) .OnFailure(WriteLogFailure); if (isRegisterFailure) { return(Result.Failure <AccommodationBookingInfo, ProblemDetails>(registerError)); } return(await BookOnProvider(booking, booking.ReferenceCode, languageCode) .Tap(ProcessResponse) .OnFailure(VoidMoneyAndCancelBooking) .Bind(GenerateInvoice) .Bind(SendReceiptIfPaymentMade) .Bind(GetAccommodationBookingInfo) .Finally(WriteLog)); void FillAvailabilityLocalVariables((Suppliers, DataWithMarkup <RoomContractSetAvailability> Result) responseWithMarkup) { availabilityId = responseWithMarkup.Result.Data.AvailabilityId; availabilityDeadline = responseWithMarkup.Result.Data.RoomContractSet.Deadline.Date; availabilityCheckIn = responseWithMarkup.Result.Data.CheckInDate; } bool AreAprSettingsSuitable( (Suppliers, DataWithMarkup <RoomContractSetAvailability>) bookingData) => BookingRegistrationService.AreAprSettingsSuitable(bookingRequest, bookingData, settings); bool AreDeadlineSettingsSuitable( (Suppliers, DataWithMarkup <RoomContractSetAvailability>) bookingData) => this.AreDeadlineSettingsSuitable(bookingRequest, bookingData, settings); async Task <string> RegisterBooking(BookingAvailabilityInfo bookingAvailability) { var bookingRequestWithAvailabilityId = new AccommodationBookingRequest(bookingRequest, availabilityId); var registeredReferenceCode = await _bookingRecordsManager.Register(bookingRequestWithAvailabilityId, bookingAvailability, agentContext, languageCode); referenceCode = registeredReferenceCode; return(registeredReferenceCode); } async Task <Result <Data.Booking.Booking, ProblemDetails> > GetBooking(string referenceCode) => await _bookingRecordsManager.Get(referenceCode).ToResultWithProblemDetails(); async Task <Result <Data.Booking.Booking, ProblemDetails> > PayUsingAccountIfDeadlinePassed(Data.Booking.Booking bookingInPipeline) { var daysBeforeDeadline = Infrastructure.Constants.Common.DaysBeforeDeadlineWhenPayForBooking; var now = _dateTimeProvider.UtcNow(); var deadlinePassed = availabilityCheckIn <= now.AddDays(daysBeforeDeadline) || (availabilityDeadline.HasValue && availabilityDeadline <= now.AddDays(daysBeforeDeadline)); if (!deadlinePassed) { return(bookingInPipeline); } var(_, isPaymentFailure, _, paymentError) = await _accountPaymentService.Charge(bookingInPipeline, agentContext, clientIp); if (isPaymentFailure) { return(ProblemDetailsBuilder.Fail <Data.Booking.Booking>(paymentError)); } wasPaymentMade = true; return(bookingInPipeline); } Task ProcessResponse(EdoContracts.Accommodations.Booking bookingResponse) => _bookingResponseProcessor.ProcessResponse(bookingResponse, booking); Task VoidMoneyAndCancelBooking(ProblemDetails problemDetails) => this.VoidMoneyAndCancelBooking(booking, agentContext); Task <Result <EdoContracts.Accommodations.Booking, ProblemDetails> > GenerateInvoice(EdoContracts.Accommodations.Booking details) => this.GenerateInvoice(details, booking.ReferenceCode, agentContext); async Task <Result <EdoContracts.Accommodations.Booking, ProblemDetails> > SendReceiptIfPaymentMade(EdoContracts.Accommodations.Booking details) => wasPaymentMade ? await SendReceipt(details, booking, agentContext) : details; Task <Result <AccommodationBookingInfo, ProblemDetails> > GetAccommodationBookingInfo(EdoContracts.Accommodations.Booking details) => _bookingRecordsManager.GetAccommodationBookingInfo(details.ReferenceCode, languageCode) .ToResultWithProblemDetails(); void WriteLogFailure(ProblemDetails problemDetails) => _logger.LogBookingByAccountFailure($"Failed to book using account. Reference code: '{referenceCode}'. Error: {problemDetails.Detail}"); Result <T, ProblemDetails> WriteLog <T>(Result <T, ProblemDetails> result) => LoggerUtils.WriteLogByResult(result, () => _logger.LogBookingFinalizationSuccess($"Successfully booked using account. Reference code: '{referenceCode}'"), () => _logger.LogBookingFinalizationFailure( $"Failed to book using account. Reference code: '{referenceCode}'. Error: {result.Error.Detail}")); }
//Produces a simple beep. public void Beep() { LoggerUtils.MessageBeep(-1); }