/// <summary> /// Создает событие <see cref="E:System.Windows.Application.Startup"/>. /// </summary> /// <param name="e">Объект <see cref="T:System.Windows.StartupEventArgs"/>, содержащий данные, которые относятся к событию.</param> protected override void OnStartup(StartupEventArgs e) { using (var ps = new PluginService()) { ps.FindPlugins(PluginDir); var c = ps.Plugins.Count(); ps.InitPlugins(); c = ps.Plugins.Count(); } base.OnStartup(e); }
private void ExecuteOkCommandCommand() { try { Check(); //乘机人姓名生僻字判断 var isstop = false; DispatcherHelper.UIDispatcher.Invoke(new Action(() => CommunicateManager.Invoke <IFlightDestineService>(service => { foreach (var item in _passengerInformationItems.Select(item => service.HasRare(item.Name)).Where(rback => rback.IsRare)) { isstop = item.IsRare; throw new Exception("乘机人姓名里含有生僻字(" + item.RareFontString + "),请用拼音代替"); } }, UIManager.ShowErr))); if (isstop) { return; } } catch (Exception ex) { UIManager.ShowErr(ex); return; } IsBusy = true; OkCommand.RaiseCanExecuteChanged(); //Func<string> action = () => Func <PolicyPack> action = () => { //string v = null; var pp = new PolicyPack(); var special = false; CommunicateManager.Invoke <IOrderService>(service => { var skyWay = Items.Select(p => new DestineSkyWayRequest { CarrayCode = p.FlightInfoModel.CarrayCode, FlightNumber = p.FlightInfoModel.FlightNumber, FromCityCode = p.FlightInfoModel.FromCityCode, Seat = p.FlightInfoModel.DefaultSite.SeatCode, StartDate = p.FlightInfoModel.StartDateTime, ToCityCode = p.FlightInfoModel.ToCityCode, EndDate = p.FlightInfoModel.ToDateTime, FromTerminal = p.FromTerminal, ToTerminal = p.ToTerminal, FlightModel = p.FlightInfoModel.Model, Discount = p.Discount, SeatPrice = p.IbeSeatPrice, TaxFee = p.IbeTaxFee, RQFee = p.IbeRQFee, //SeatPrice = p.SeatPrice, //TaxFee = p.TaxFee, //RQFee = p.RQFee,. PolicySpecialType = p.PolicySpecialType, SpecialPrice = p.SeatPrice, SpecialTax = p.TaxFee, SpecialFuelFee = p.RQFee, SpecialYPrice = p.YPrice }).ToArray(); //单程,往返,联程特价标示判断 special = skyWay.Any(p => p.PolicySpecialType != EnumPolicySpecialType.Normal); var passengers = _passengerInformationItems.Select(p => { p.Id = p.IdType == EnumIDType.BirthDate && p.Birthday != null ? p.Birthday.Value.ToString("yyyy-MM-dd") : p.Id; return(new PassengerRequest { CardNo = p.Id ?? "", ChdBirthday = p.AgeType != AgeType.Adult && p.Birthday != null ? p.Birthday.Value.Date : DateTime.Now.Date.AddYears(-12), MemberCard = p.BusinessCard ?? "", PassengerName = p.Passer.Name.Trim(), PassengerType = (int)(EnumPassengerType)p.AgeType, LinkPhone = p.AgeType == AgeType.Adult && p.Telephone != null ? p.Telephone.Trim() : string.Empty, IdType = p.IdType, SexType = p.SexType, Birth = p.Birthday }); }).ToArray(); try { //v = service.Destine(new DestineRequest() // { // Passengers = Passengers, // PnrType = (int)PnrType, // SkyWay = SkyWay, // Tel = CurrentUserInfo.Tel.Trim(), // }).TrimEx(); pp = service.Destine(new DestineRequest { Passengers = passengers, SkyWay = skyWay, Tel = CurrentUserInfo.Tel.Trim(), //关联成人订单号(只有单独儿童时关联) OldOrderId = passengers.Count(p => p.PassengerType == 2) > 0 ? OldOrderId : string.Empty, IsChangePnr = IsTransform, IsLowPrice = IsLowPrice, PolicySpecialType = special ? skyWay[0].PolicySpecialType : EnumPolicySpecialType.Normal, SpecialFuelFee = special ? skyWay[0].SpecialFuelFee : skyWay[0].RQFee, SpecialPrice = special ? skyWay[0].SpecialPrice : skyWay[0].SeatPrice, SpecialTax = special ? skyWay[0].SpecialTax : skyWay[0].TaxFee, SpecialYPrice = skyWay[0].SpecialYPrice, IbeRQFee = skyWay[0].RQFee, IbeTaxFee = skyWay[0].TaxFee, IbeSeatPrice = skyWay[0].SeatPrice }, EnumDestineSource.WhiteScreenDestine); if (!pp.INFPnrIsSame) { UIManager.ShowMessage("成人编码中婴儿项丢失,请补全婴儿信息"); } //政策列表显示 LocalUIManager.ShowPolicyList(pp, null); } catch (Exception ex) { UIManager.ShowErr(ex); return; } DispatcherHelper.UIDispatcher.Invoke(new Action(() => { //执行常旅客的添加操作 var fpdList = (from item in _list let f = new FrePasserDto { AirCardNo = item.BusinessCard ?? "", CertificateNo = item.Id ?? "", Mobile = item.Telephone ?? "", Name = item.Name ?? "", CertificateType = UIExt.Helper.EnumHelper.GetDescription(item.IdType), PasserType = UIExt.Helper.EnumHelper.GetDescription(item.AgeType), SexType = UIExt.Helper.EnumHelper.GetDescription(item.SexType), Birth = item.Birthday } where PassengerInformationItems.Contains(item) select f).ToList(); Action action2 = () => { IsBusy = true; CommunicateManager.Invoke <IFrePasserService>(service2 => { if (fpdList.Count > 0) { service2.Import(fpdList); } }, UIManager.ShowErr); }; Task.Factory.StartNew(action2).ContinueWith(task => { Action setBusyAction = () => { IsBusy = false; }; DispatcherHelper.UIDispatcher.Invoke(setBusyAction); }); //发送关闭查看返程窗口消息 Messenger.Default.Send(true, TicketBookingBackViewModel.c_CloseTicketBookingBackWindow); //发送关闭预定机票窗口消息 Messenger.Default.Send(true, CCloseWindow); if (this.FullWidowExt != null && this.FullWidowExt.IsFullScreen) { var uc = PluginManager.FindItem(Main.ProjectCode, Main.PnrControlCode); if (uc != null) { var control = uc.GetContent() as Control; this.FullWidowExt.SetContent(control); } } else { PluginService.Run(Main.ProjectCode, Main.PnrControlCode); } //Messenger.Default.Send<string>(v, cSearchPNR); })); Debug.WriteLine(""); }, UIManager.ShowErr); //return v; if (!string.IsNullOrWhiteSpace(OldOrderId)) { pp.OrderId = pp.ChdOrderId; } return(pp); }; try { if (_activeTask != null) { _activeTask.Wait(); } } catch (Exception exx) { Logger.WriteLog(LogType.ERROR, exx.Message, exx); } //_activeTask = Task.Factory.StartNew<string>(action) _activeTask = Task.Factory.StartNew(action) .ContinueWith(task => { DispatcherHelper.UIDispatcher.Invoke(new Action(() => { IsBusy = false; OkCommand.RaiseCanExecuteChanged(); } )); }); }
public new void SetUp() { _productService = new Mock <IProductService>(); _storeContext = new Mock <IStoreContext>(); _discountService = new Mock <IDiscountService>(); _categoryService = new Mock <ICategoryService>(); _manufacturerService = new Mock <IManufacturerService>(); _productAttributeParser = new Mock <IProductAttributeParser>(); _eventPublisher = new Mock <IEventPublisher>(); _localizationService = new Mock <ILocalizationService>(); _shippingMethodRepository = new Mock <IRepository <ShippingMethod> >(); _warehouseRepository = new Mock <IRepository <Warehouse> >(); _shipmentService = new Mock <IShipmentService>(); _paymentService = new Mock <IPaymentService>(); _checkoutAttributeParser = new Mock <ICheckoutAttributeParser>(); _giftCardService = new Mock <IGiftCardService>(); _genericAttributeService = new Mock <IGenericAttributeService>(); _geoLookupService = new Mock <IGeoLookupService>(); _countryService = new Mock <ICountryService>(); _stateProvinceService = new Mock <IStateProvinceService>(); _eventPublisher = new Mock <IEventPublisher>(); _addressService = new Mock <IAddressService>(); _rewardPointService = new Mock <IRewardPointService>(); _orderService = new Mock <IOrderService>(); _webHelper = new Mock <IWebHelper>(); _languageService = new Mock <ILanguageService>(); _priceFormatter = new Mock <IPriceFormatter>(); _productAttributeFormatter = new Mock <IProductAttributeFormatter>(); _shoppingCartService = new Mock <IShoppingCartService>(); _checkoutAttributeFormatter = new Mock <ICheckoutAttributeFormatter>(); _customerService = new Mock <ICustomerService>(); _encryptionService = new Mock <IEncryptionService>(); _workflowMessageService = new Mock <IWorkflowMessageService>(); _customerActivityService = new Mock <ICustomerActivityService>(); _currencyService = new Mock <ICurrencyService>(); _affiliateService = new Mock <IAffiliateService>(); _vendorService = new Mock <IVendorService>(); _pdfService = new Mock <IPdfService>(); _customNumberFormatter = new Mock <ICustomNumberFormatter>(); _rewardPointService = new Mock <IRewardPointService>(); _workContext = null; _store = new Store { Id = 1 }; _storeContext.Setup(x => x.CurrentStore).Returns(_store); _shoppingCartSettings = new ShoppingCartSettings(); _catalogSettings = new CatalogSettings(); var cacheManager = new TestCacheManager(); _currencySettings = new CurrencySettings(); //price calculation service _priceCalcService = new PriceCalculationService(_catalogSettings, _currencySettings, _categoryService.Object, _currencyService.Object, _discountService.Object, _manufacturerService.Object, _productAttributeParser.Object, _productService.Object, cacheManager, _storeContext.Object, _workContext, _shoppingCartSettings); _eventPublisher.Setup(x => x.Publish(It.IsAny <object>())); var loger = new Mock <ILogger>(); var pluginService = new PluginService(_catalogSettings, _customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, _webHelper.Object); _paymentPluginManager = new PaymentPluginManager(pluginService, null, _paymentSettings); _pickupPluginManager = new PickupPluginManager(pluginService, _shippingSettings); _shippingPluginManager = new ShippingPluginManager(pluginService, _shippingSettings); _taxPluginManager = new TaxPluginManager(pluginService, _taxSettings); //shipping _shippingSettings = new ShippingSettings { ActiveShippingRateComputationMethodSystemNames = new List <string>() }; _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod"); _logger = new NullLogger(); _customerSettings = new CustomerSettings(); _addressSettings = new AddressSettings(); _shippingService = new ShippingService(_addressService.Object, cacheManager, _checkoutAttributeParser.Object, _eventPublisher.Object, _genericAttributeService.Object, _localizationService.Object, _logger, _pickupPluginManager, _priceCalcService, _productAttributeParser.Object, _productService.Object, _shippingMethodRepository.Object, _warehouseRepository.Object, _shippingPluginManager, _storeContext.Object, _shippingSettings, _shoppingCartSettings); //tax _taxSettings = new TaxSettings { ShippingIsTaxable = true, PaymentMethodAdditionalFeeIsTaxable = true, DefaultTaxAddressId = 10 }; _addressService.Setup(x => x.GetAddressById(_taxSettings.DefaultTaxAddressId)).Returns(new Address { Id = _taxSettings.DefaultTaxAddressId }); _taxService = new TaxService(_addressSettings, _customerSettings, _addressService.Object, _countryService.Object, _genericAttributeService.Object, _geoLookupService.Object, _logger, _stateProvinceService.Object, cacheManager, _storeContext.Object, _taxPluginManager, _webHelper.Object, _workContext, _shippingSettings, _taxSettings); _rewardPointsSettings = new RewardPointsSettings(); _orderTotalCalcService = new OrderTotalCalculationService(_catalogSettings, _checkoutAttributeParser.Object, _discountService.Object, _genericAttributeService.Object, _giftCardService.Object, _paymentService.Object, _priceCalcService, _rewardPointService.Object, _shippingPluginManager, _shippingService, _shoppingCartService.Object, _storeContext.Object, _taxService, _workContext, _rewardPointsSettings, _shippingSettings, _shoppingCartSettings, _taxSettings); _paymentSettings = new PaymentSettings { ActivePaymentMethodSystemNames = new List <string> { "Payments.TestMethod" } }; _orderSettings = new OrderSettings(); _localizationSettings = new LocalizationSettings(); _eventPublisher.Setup(x => x.Publish(It.IsAny <object>())); _orderProcessingService = new OrderProcessingService(_currencySettings, _affiliateService.Object, _checkoutAttributeFormatter.Object, _countryService.Object, _currencyService.Object, _customerActivityService.Object, _customerService.Object, _customNumberFormatter.Object, _discountService.Object, _encryptionService.Object, _eventPublisher.Object, _genericAttributeService.Object, _giftCardService.Object, _languageService.Object, _localizationService.Object, _logger, _orderService.Object, _orderTotalCalcService, _paymentPluginManager, _paymentService.Object, _pdfService.Object, _priceCalcService, _priceFormatter.Object, _productAttributeFormatter.Object, _productAttributeParser.Object, _productService.Object, _rewardPointService.Object, _shipmentService.Object, _shippingPluginManager, _shippingService, _shoppingCartService.Object, _stateProvinceService.Object, _storeContext.Object, _taxService, _vendorService.Object, _webHelper.Object, _workContext, _workflowMessageService.Object, _localizationSettings, _orderSettings, _paymentSettings, _rewardPointsSettings, _shippingSettings, _taxSettings); }
/// <summary> /// Render the FAB /// </summary> /// <param name="entity">The current entity being viewed</param> /// <param name="guid">The guid of the current app or content type</param> /// <param name="insertUrl">The url to upload loca files to</param> /// <param name="allowdFunc">func for checking if content is allowed</param> /// <param name="permissionFunc">func for checking permission</param> /// <returns></returns> private static MvcHtmlString RenderFAB(IEntity entity, Guid guid, string insertUrl, Func <Guid, bool> allowdFunc, Func <Permission, User, bool> permissionFunc) { var url = entity.Url(); var container = new TagBuilder("div"); container.Attributes["class"] = "fabs"; // create fab var create = new TagBuilder("div"); create.Attributes["class"] = "fab create dropup filebrowser"; var createButton = new TagBuilder("button"); createButton.AddCssClass("btn btn-round btn-primary dropdown-toggle"); createButton.Attributes["type"] = "button"; createButton.Attributes["title"] = T["Create"]; createButton.Attributes["data-toggle"] = "dropdown"; createButton.Attributes["aria-haspopup"] = "true"; createButton.Attributes["aria-expanded"] = "false"; createButton.InnerHtml = Icon("plus").ToString(); var createMenu = new TagBuilder("div"); createMenu.Attributes["role"] = "menu"; createMenu.AddCssClass("dropdown-menu dropdown-menu-right"); // add fab var add = new TagBuilder("div"); add.Attributes["class"] = "fab add dropup filebrowser"; var addButton = new TagBuilder("button"); addButton.Attributes["type"] = "button"; addButton.Attributes["title"] = T["Add file"]; addButton.InnerHtml = Icon("attachment").ToString(); var addMenu = new TagBuilder("div"); // special for webview if (WeavyContext.Current.Browser.Mobile) { addButton.Attributes["class"] = "btn btn-round btn-secondary"; var input = new TagBuilder("input"); input.AddCssClass("file-ctrl"); input.Attributes["type"] = "file"; input.Attributes["accept"] = ConfigurationService.BlobWhitelist; input.Attributes["data-kind"] = entity.Type.ToString().ToLower(); input.Attributes["data-insert-url"] = insertUrl; input.MergeAttribute("multiple", string.Empty); addButton.InnerHtml += input.ToString(); } else { addButton.AddCssClass("btn btn-round btn-secondary dropdown-toggle"); addButton.Attributes["data-toggle"] = "dropdown"; addButton.Attributes["aria-haspopup"] = "true"; addButton.Attributes["aria-expanded"] = "false"; addMenu.Attributes["role"] = "menu"; addMenu.AddCssClass("dropdown-menu dropdown-menu-right"); } // create content if (permissionFunc(Permission.Content, null)) { // get allowed content types List <Content> allowed = new List <Content>(); foreach (var ct in PluginService.GetContentTypes()) { if (allowdFunc(ct.Id)) { var child = ContentService.New(ct.Id); if (child != null && child.MetaData().IsParentAllowed(guid)) { allowed.Add(child); } } } var createContent = new List <dynamic>(); createContent.AddRange(allowed.Where(x => x.MetaData().CreateMode != UpsertMode.None).Select(x => new { Url = x.MetaData().CreateMode == UpsertMode.Modal ? "#upsert-content-modal" : $"{url}/content/{x.ContentGuid}", Param = x.ContentGuid, x.MetaData().Icon, x.MetaData().Color, x.MetaData().Name, Title = x.MetaData().CreateVerb + " " + x.MetaData().Name?.ToLower(), Path = x.MetaData().CreateMode == UpsertMode.Modal ? $"{url}/content/{x.ContentGuid}" : "", SortOrder = 1 })); if (createContent.Any()) { foreach (var c in createContent.OrderBy(x => x.SortOrder)) { if (c.Url.StartsWith("#")) { createMenu.InnerHtml += $@"<a class=""dropdown-item"" href=""#"" data-toggle=""modal"" data-target=""{c.Url}"" data-param=""{c.Param}"" data-path=""{c.Path}"" data-title=""{c.Title}"">{Icon(c.Icon, c.Color)} {c.Name}</a>"; } else { createMenu.InnerHtml += $@"<a class=""dropdown-item"" href=""{c.Url}"" target=""overlay"">{Icon(c.Icon, c.Color)} {c.Name}</a>"; } } } // MS office createMenu.InnerHtml += $@"<a class=""dropdown-item"" href=""#"" data-toggle=""menu"" data-target=""office"">{Icon("office", "native")} Office <span>{Icon("chevron-right")}</span></a>"; createMenu.InnerHtml += $@"<a class=""d-none"" data-menu=""office"" href=""#""><h6 class=""dropdown-header"">{Icon("chevron-left")}Office</h6></a>"; createMenu.InnerHtml += $@"<a class=""dropdown-item d-none"" data-menu=""office"" href=""#"" data-toggle=""modal"" data-target=""#office-modal"" data-param="".docx"" data-type=""Word"">{Icon(FileUtils.GetIcon(".docx"), "native")} Word</a>"; createMenu.InnerHtml += $@"<a class=""dropdown-item d-none"" data-menu=""office"" href=""#"" data-toggle=""modal"" data-target=""#office-modal"" data-param="".xlsx"" data-type=""Excel"">{Icon(FileUtils.GetIcon(".xlsx"), "native")} Excel</a>"; createMenu.InnerHtml += $@"<a class=""dropdown-item d-none"" data-menu=""office"" href=""#"" data-toggle=""modal"" data-target=""#office-modal"" data-param="".pptx"" data-type=""Powerpoint"">{Icon(FileUtils.GetIcon(".pptx"), "native")} Powerpoint</a>"; // not available in webview or if google drive is not configured if (!WeavyContext.Current.Browser.Mobile && ConfigurationService.BlobProviders.Contains("Google Drive")) { // google docs createMenu.InnerHtml += $@"<a class=""dropdown-item"" href=""#"" data-toggle=""menu"" data-target=""google"">{Icon("google-drive", "native")} Google <span>{Icon("chevron-right")}</span></a>"; createMenu.InnerHtml += $@"<a class=""d-none"" data-menu=""google"" href=""#""><h6 class=""dropdown-header"">{Icon("chevron-left")}Google</h6></a>"; createMenu.InnerHtml += $@"<a class=""dropdown-item d-none"" data-menu=""google"" href=""#"" data-toggle=""modal"" data-target=""#google-drive-modal"" data-param=""document"" data-type=""Docs"">{Icon("file-document-box", "native")} Docs</a>"; createMenu.InnerHtml += $@"<a class=""dropdown-item d-none"" data-menu=""google"" href=""#"" data-toggle=""modal"" data-target=""#google-drive-modal"" data-param=""spreadsheet"" data-type=""Sheets"">{Icon("file-sheet-box", "native")} Sheets</a>"; createMenu.InnerHtml += $@"<a class=""dropdown-item d-none"" data-menu=""google"" href=""#"" data-toggle=""modal"" data-target=""#google-drive-modal"" data-param=""presentation"" data-type=""Slides"">{Icon("file-slide-box", "native")} Slides</a>"; } // local and cloud files var files = new List <dynamic>(); if (allowdFunc(typeof(File).GUID)) { foreach (var p in ConfigurationService.BlobProviders.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { files.Add(new { Url = "#", Icon = p.ToKebabCase(), Color = "native", Name = p, Provider = p.ToKebabCase(), Css = "d-desktop" }); } if (WeavyContext.Current.Browser.Desktop) { files.Add(new { Url = "upload", Icon = "laptop", Color = "theme-700", Name = T["Your computer"], Css = "" }); } else { files.Add(new { Url = "upload", Icon = "cellphone-android", Color = "theme-700", Name = T["Your device"], Css = "" }); } } if (files.Any() && !WeavyContext.Current.Browser.Mobile) { foreach (var c in files) { if (c.Url.StartsWith("#")) { addMenu.InnerHtml += $@"<a class=""dropdown-item"" href=""javascript:;"" data-chooser=""{c.Provider}"">{Icon(c.Icon, c.Color)} {c.Name}</a>"; } else if (c.Url == "upload") { addMenu.InnerHtml += $@"<div class=""dropdown-item fab-upload"">{Icon(c.Icon, c.Color)} {c.Name}<input type=""file"" data-kind=""{entity.Type.ToString().ToLower()}"" data-insert-url=""{insertUrl}"" data-dropzone=""html"" accept=""{ConfigurationService.BlobWhitelist}"" multiple /></div>"; } else { addMenu.InnerHtml += $@"<a class=""dropdown-item"" href=""{c.Url}"">{Icon(c.Icon, c.Color)} {c.Name}</a>"; } } } } if (createMenu.InnerHtml.IsNullOrEmpty() && addMenu.InnerHtml.IsNullOrEmpty()) { return(null); } create.InnerHtml += createButton.ToString(); create.InnerHtml += createMenu.ToString(); container.InnerHtml = create.ToString(); add.InnerHtml += addButton.ToString(); add.InnerHtml += addMenu.ToString(); container.InnerHtml += add.ToString(); return(MvcHtmlString.Create(container.ToString())); }
public void PluginServiceContructorWithNullXmlExpectedThrowsArgumentNullException() { var service = new PluginService(null); }
public override StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { var serializer = new Dev2JsonSerializer(); try { var pluginSource = serializer.Deserialize <PluginSourceDefinition>(values["source"]); var ns = serializer.Deserialize <INamespaceItem>(values["namespace"]); var services = new PluginServices(); var src = Resources.GetResource <PluginSource>(GlobalConstants.ServerWorkspaceID, pluginSource.Id); if (ns != null) { var svc = new PluginService { Namespace = ns.FullName, Source = src }; var serviceMethodList = services.MethodsWithReturns(svc); var methods = serviceMethodList.Select(a => new PluginAction { FullName = ns.FullName, Inputs = a.Parameters.Select(x => new ServiceInput(x.Name, x.DefaultValue ?? "") { Name = x.Name , EmptyIsNull = x.EmptyToNull , RequiredField = x.IsRequired , TypeName = x.TypeName , ShortTypeName = x.ShortTypeName , IsObject = x.IsObject , Dev2ReturnType = x.Dev2ReturnType, IntellisenseFilter = x.IsObject ? enIntellisensePartType.JsonObject : enIntellisensePartType.None } as IServiceInput).ToList(), Method = a.Name, Variables = a.Parameters.Select(x => new NameValue { Name = x.Name + " (" + x.TypeName + ")", Value = "" } as INameValue).ToList(), Dev2ReturnType = a.Dev2ReturnType, IsObject = a.IsObject, IsVoid = a.IsVoid, IsProperty = a.IsProperty } as IPluginAction).ToList(); return(serializer.SerializeToBuilder(new ExecuteMessage { HasError = false, Message = serializer.SerializeToBuilder(methods) })); } else { return(serializer.SerializeToBuilder(new ExecuteMessage { HasError = false, Message = serializer.SerializeToBuilder(new List <IPluginAction>()) })); } } catch (Exception e) { return(serializer.SerializeToBuilder(new ExecuteMessage { HasError = true, Message = new StringBuilder(e.Message) })); } }
private IMBotMessage DoShowUpcomingCommand(IMBotConversation conversation, ScheduleType type) { if (type == ScheduleType.Recording) { var upcomingRecordings = Proxies.ControlService.GetAllUpcomingRecordings(UpcomingRecordingsFilter.Recordings, false).Result; StringBuilder replyText = new StringBuilder(); if (upcomingRecordings.Count > 0) { int index = 0; foreach (UpcomingRecording upcomingRecording in upcomingRecordings) { if (replyText.Length > 0) { replyText.AppendLine(); } PluginService pluginService = null; if (upcomingRecording.CardChannelAllocation != null) { pluginService = RecorderTunersCache.GetRecorderTunerById(upcomingRecording.CardChannelAllocation.RecorderTunerId); } replyText.AppendFormat("{0,3}» ", ++index); Utility.AppendProgramDetails(replyText, upcomingRecording.Program.Channel, upcomingRecording.Program); replyText.AppendFormat(" [{0}]", pluginService == null ? "-" : pluginService.Name); } conversation.Session[SessionKey.Programs] = new Session.Programs(upcomingRecordings); return(new IMBotMessage(replyText.ToString(), true) { Footer = "Use 'cancel', 'uncancel' or 'delete schedule' with <number>." }); } } else { var upcomingPrograms = Proxies.SchedulerService.GetAllUpcomingPrograms(type, false).Result; StringBuilder replyText = new StringBuilder(); if (upcomingPrograms.Count > 0) { int index = 0; foreach (UpcomingProgram upcomingProgram in upcomingPrograms) { if (replyText.Length > 0) { replyText.AppendLine(); } replyText.AppendFormat("{0,3}» ", ++index); Utility.AppendProgramDetails(replyText, upcomingProgram.Channel, upcomingProgram); } conversation.Session[SessionKey.Programs] = new Session.Programs(upcomingPrograms); return(new IMBotMessage(replyText.ToString(), true) { Footer = "Use 'record', 'cancel', 'uncancel' or 'delete schedule' with <number>." }); } } return(new IMBotMessage("There are no upcoming " + type.ToString().ToLowerInvariant() + "s.")); }
public UnattendedResolver(ILogService log, IArgumentsService options, PluginService pluginService) { _log = log; _plugins = pluginService; _options = options; }
public Importer(ILogService log, IInputService input, ILegacyRenewalService legacyRenewal, IRenewalService currentRenewal, PluginService pluginService, LegacyTaskSchedulerService legacyTaskScheduler, TaskSchedulerService currentTaskScheduler, PasswordGenerator passwordGenerator) { _legacyRenewal = legacyRenewal; _currentRenewal = currentRenewal; _log = log; _input = input; _currentTaskScheduler = currentTaskScheduler; _legacyTaskScheduler = legacyTaskScheduler; _pluginService = pluginService; _passwordGenerator = passwordGenerator; }
private static void Main(string[] args) { Log = new LogService(); if (!TryParseOptions(args)) { return; } if (Options.Verbose) { Log.SetVerbose(); } Plugins = new PluginService(); Input = new InputService(Options); Input.ShowBanner(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if (Options.Test) { SetTestParameters(); } if (Options.ForceRenewal) { Options.Renew = true; } ParseRenewalPeriod(); ParseCertificateStore(); Log.Information("ACME Server: {BaseUri}", Options.BaseUri); ParseCentralSslStore(); CreateSettings(); CreateConfigPath(); SetAndCreateCertificatePath(); bool retry = false; do { try { using (var signer = new RS256Signer()) { signer.Init(); using (_client = new AcmeClient(new Uri(Options.BaseUri), new AcmeServerDirectory(), signer)) { ConfigureAcmeClient(_client); if (Options.Renew) { CheckRenewals(); } else if (!string.IsNullOrEmpty(Options.Plugin)) { CreateNewCertifcateUnattended(); } else { MainMenu(); } } retry = false; } } catch (AcmeClient.AcmeWebException awe) { Environment.ExitCode = awe.HResult; Log.Debug("AcmeWebException {@awe}", awe); Log.Error("ACME Server Returned: {acmeWebExceptionMessage} - Response: {acmeWebExceptionResponse}", awe.Message, awe.Response.ContentAsString); } catch (AcmeException ae) { Environment.ExitCode = ae.HResult; Log.Debug("AcmeException {@ae}", ae); Log.Error("AcmeException {@ae}", ae.Message); } catch (Exception e) { Environment.ExitCode = e.HResult; Log.Debug("Exception {@e}", e); Log.Error("Exception {@e}", e.Message); } if (!Options.CloseOnFinish && (!Options.Renew || Options.Test)) { if (Input.PromptYesNo("Would you like to start again?")) { Environment.ExitCode = 0; retry = true; } } } while (retry); }
public override RecordsetList FetchRecordset(PluginService pluginService, bool addFields) { FetchRecordsetHitCount++; FetchRecordsetAddFields = addFields; return(base.FetchRecordset(pluginService, addFields)); }
/// <summary> /// The main entry point of the program. /// </summary> /// <returns>A task.</returns> public static async Task Main() { // Configure logging const string configurationName = "DIGOS.Ambassador.log4net.config"; var logConfig = new XmlDocument(); await using (var configStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(configurationName)) { if (configStream is null) { throw new InvalidOperationException("The log4net configuration stream could not be found."); } logConfig.Load(configStream); } var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(Hierarchy)); XmlConfigurator.Configure(repo, logConfig["log4net"]); var hostBuilder = Host.CreateDefaultBuilder() .UseSystemd() .ConfigureServices(services => { var pluginService = new PluginService(); services .AddHostedService <AmbassadorBotService>() .AddSingleton(pluginService) .AddSingleton ( provider => new DiscordSocketClient(new DiscordSocketConfig { MessageCacheSize = 100 }) ) .AddSingleton <IDiscordClient>(s => s.GetRequiredService <DiscordSocketClient>()) .AddSingleton <BaseSocketClient>(s => s.GetRequiredService <DiscordSocketClient>()) .AddSingleton <CommandService>() .AddSingleton <BehaviourService>() .AddSingleton <ContentService>() .AddSingleton <DiscordService>() .AddSingleton <UserFeedbackService>() .AddSingleton <InteractivityService>() .AddSingleton <DelayedActionService>() .AddSingleton <SchemaAwareDbContextService>() .AddSingleton <ContextConfigurationService>() .AddSingleton(FileSystemFactory.CreateContentFileSystem()) .AddSingleton <Random>(); var plugins = pluginService.LoadAvailablePlugins(); foreach (var plugin in plugins) { plugin.ConfigureServices(services); } }) .ConfigureLogging(l => { l.ClearProviders(); l.AddLog4Net() .AddFilter("Microsoft.EntityFrameworkCore.Infrastructure", LogLevel.Warning) .AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning) .AddFilter("Microsoft.EntityFrameworkCore.Migrations", LogLevel.Warning); }); var host = hostBuilder.Build(); var logger = host.Services.GetRequiredService <ILogger <Program> >(); logger.LogInformation($"Running on {RuntimeInformation.FrameworkDescription}"); await host.RunAsync(); }
protected override void Run(ServiceContext context) { var plugin = PluginService.GetPlugin <SamplePlugin>("SampleType"); Console.WriteLine("Instance type: {0}", plugin.GetType()); }
internal static IContainer GlobalScope(string[] args) { var builder = new ContainerBuilder(); var logger = new LogService(); if (args.Contains("--verbose")) { logger.SetVerbose(); } var pluginService = new PluginService(logger); var argumentsParser = new ArgumentsParser(logger, pluginService, args); var argumentsService = new ArgumentsService(logger, argumentsParser); if (!argumentsService.Valid) { Environment.ExitCode = -1; return(null); } var settingsService = new SettingsService(logger, argumentsService); if (!settingsService.Valid) { Environment.ExitCode = -1; return(null); } logger.SetDiskLoggingPath(settingsService.Client.LogPath); _ = builder.RegisterInstance(argumentsService); _ = builder.RegisterInstance(argumentsParser); _ = builder.RegisterInstance(logger).As <ILogService>(); _ = builder.RegisterInstance(settingsService).As <ISettingsService>(); _ = builder.RegisterInstance(argumentsService).As <IArgumentsService>(); _ = builder.RegisterInstance(pluginService).As <IPluginService>(); _ = builder.RegisterType <UserRoleService>().SingleInstance(); _ = builder.RegisterType <InputService>().As <IInputService>().SingleInstance(); _ = builder.RegisterType <ProxyService>().SingleInstance(); _ = builder.RegisterType <PasswordGenerator>().SingleInstance(); _ = builder.RegisterType <RenewalService>().As <IRenewalStore>().SingleInstance(); pluginService.Configure(builder); _ = builder.RegisterType <DomainParseService>().SingleInstance(); _ = builder.RegisterType <IISClient>().As <IIISClient>().SingleInstance(); _ = builder.RegisterType <IISHelper>().SingleInstance(); _ = builder.RegisterType <ExceptionHandler>().SingleInstance(); _ = builder.RegisterType <UnattendedResolver>(); _ = builder.RegisterType <InteractiveResolver>(); _ = builder.RegisterType <AutofacBuilder>().As <IAutofacBuilder>().SingleInstance(); _ = builder.RegisterType <AcmeClient>().SingleInstance(); _ = builder.RegisterType <PemService>().SingleInstance(); _ = builder.RegisterType <EmailClient>().SingleInstance(); _ = builder.RegisterType <ScriptClient>().SingleInstance(); _ = builder.RegisterType <LookupClientProvider>().SingleInstance(); _ = builder.RegisterType <CertificateService>().As <ICertificateService>().SingleInstance(); _ = builder.RegisterType <TaskSchedulerService>().SingleInstance(); _ = builder.RegisterType <NotificationService>().SingleInstance(); _ = builder.RegisterType <RenewalExecutor>().SingleInstance(); _ = builder.RegisterType <RenewalManager>().SingleInstance(); _ = builder.Register(c => c.Resolve <IArgumentsService>().MainArguments).SingleInstance(); return(builder.Build()); }
public void DiscoverAndAddPlugins(PluginService pluginService) { DirectoryInfo pluginsDir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Larian Studios\\Divinity Original Sin\\EditorPlugins"); if (pluginsDir.Exists) { foreach (var file in pluginsDir.GetFiles("*Plugin.dll")) { try { Assembly assembly = Assembly.LoadFrom(file.FullName); foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(typeof(IPlugin)) && type.IsPublic && !type.IsAbstract) { IPlugin plugin = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, null) as IPlugin; pluginService.AddPlugin(plugin); } } } catch (Exception e) { MessageBox.Show("Failed to initialize plugin " + file.Name + ":" + Environment.NewLine + Environment.NewLine + e.ToString(), "Plugin load failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } }
public new void SetUp() { _shippingSettings = new ShippingSettings { ActiveShippingRateComputationMethodSystemNames = new List <string>() }; _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod"); _shippingMethodRepository = new Mock <IRepository <ShippingMethod> >(); _warehouseRepository = new Mock <IRepository <Warehouse> >(); _logger = new NullLogger(); _productAttributeParser = new Mock <IProductAttributeParser>(); _checkoutAttributeParser = new Mock <ICheckoutAttributeParser>(); var cacheManager = new TestCacheManager(); _productService = new Mock <IProductService>(); _eventPublisher = new Mock <IEventPublisher>(); _eventPublisher.Setup(x => x.Publish(It.IsAny <object>())); var customerService = new Mock <ICustomerService>(); var loger = new Mock <ILogger>(); var webHelper = new Mock <IWebHelper>(); _catalogSettings = new CatalogSettings(); var pluginService = new PluginService(_catalogSettings, customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, webHelper.Object); _pickupPluginManager = new PickupPluginManager(pluginService, _shippingSettings); _shippingPluginManager = new ShippingPluginManager(pluginService, _shippingSettings); _localizationService = new Mock <ILocalizationService>(); _addressService = new Mock <IAddressService>(); _genericAttributeService = new Mock <IGenericAttributeService>(); _priceCalcService = new Mock <IPriceCalculationService>(); _store = new Store { Id = 1 }; _storeContext = new Mock <IStoreContext>(); _storeContext.Setup(x => x.CurrentStore).Returns(_store); _shoppingCartSettings = new ShoppingCartSettings(); _shippingService = new ShippingService(_addressService.Object, cacheManager, _checkoutAttributeParser.Object, _eventPublisher.Object, _genericAttributeService.Object, _localizationService.Object, _logger, _pickupPluginManager, _priceCalcService.Object, _productAttributeParser.Object, _productService.Object, _shippingMethodRepository.Object, _warehouseRepository.Object, _shippingPluginManager, _storeContext.Object, _shippingSettings, _shoppingCartSettings); }
public ManualTests() { log = new Mock.Services.LogService(); iis = new Mock.Clients.MockIISClient(); plugins = new PluginService(log); }
private IMBotMessage DoStatusCommand(IMBotConversation conversation, IList <string> arguments) { bool fixedWidth = false; // Check if currently recording : var activeRecordings = Proxies.ControlService.GetActiveRecordings().Result; var liveStreams = Proxies.ControlService.GetLiveStreams().Result; var upcomingRecording = Proxies.ControlService.GetNextUpcomingRecording(false).Result; StringBuilder reply = new StringBuilder(); if (activeRecordings.Count > 0) { reply.Append("Currently recording:"); foreach (ActiveRecording activeRecording in activeRecordings) { PluginService pluginService = null; if (activeRecording.CardChannelAllocation != null) { pluginService = RecorderTunersCache.GetRecorderTunerById(activeRecording.CardChannelAllocation.RecorderTunerId); } reply.AppendLine(); Utility.AppendProgramDetails(reply, activeRecording.Program.Channel, activeRecording.Program); reply.AppendFormat(" [{0}]", pluginService == null ? "-" : pluginService.Name); } fixedWidth = true; if (liveStreams.Count > 0 || upcomingRecording != null) { reply.AppendLine(); } } if (liveStreams.Count > 0) { reply.Append("Currently streaming:"); foreach (LiveStream liveStream in liveStreams) { reply.AppendLine(); reply.AppendFormat("[{0}]", liveStream.Channel.DisplayName); } fixedWidth = true; if (upcomingRecording != null) { reply.AppendLine(); } } if (upcomingRecording != null) { if (reply.Length == 0) { reply.AppendLine("Idle, next scheduled recording:"); } else { reply.AppendLine("Next scheduled recording:"); } PluginService pluginService = null; if (upcomingRecording.CardChannelAllocation != null) { pluginService = RecorderTunersCache.GetRecorderTunerById(upcomingRecording.CardChannelAllocation.RecorderTunerId); } Utility.AppendProgramDetails(reply, upcomingRecording.Program.Channel, upcomingRecording.Program); reply.AppendFormat(" [{0}]", pluginService == null ? "-" : pluginService.Name); fixedWidth = true; } if (reply.Length == 0) { reply.Append("Idle"); } reply.AppendLine().AppendLine(); reply.Append("ARGUS TV Messenger " + Constants.ProductVersion + @", running on server \\").AppendLine(Dns.GetHostName()); reply.Append("http://www.argus-tv.com"); return(new IMBotMessage(reply.ToString(), fixedWidth)); }
public object TestExecuteService(PluginService service) { ErrorResultTO errors; return(base.Execute(out errors)); }
public UnattendedResolver(ScheduledRenewal renewal, ILogService log, PluginService pluginService) { _renewal = renewal; _log = log; _plugins = pluginService; }
public new void SetUp() { currencyUSD = new Currency { Id = 1, Name = "US Dollar", CurrencyCode = "USD", Rate = 1.2M, DisplayLocale = "en-US", CustomFormatting = "", Published = true, DisplayOrder = 1, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow, RoundingType = RoundingType.Rounding001 }; currencyEUR = new Currency { Id = 2, Name = "Euro", CurrencyCode = "EUR", Rate = 1, DisplayLocale = "", CustomFormatting = "€0.00", Published = true, DisplayOrder = 2, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow, RoundingType = RoundingType.Rounding001 }; currencyRUR = new Currency { Id = 3, Name = "Russian Rouble", CurrencyCode = "RUB", Rate = 34.5M, DisplayLocale = "ru-RU", CustomFormatting = "", Published = true, DisplayOrder = 3, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow, RoundingType = RoundingType.Rounding001 }; _currencyRepository = new Mock <IRepository <Currency> >(); _currencyRepository.Setup(x => x.Table).Returns(new List <Currency> { currencyUSD, currencyEUR, currencyRUR }.AsQueryable()); _currencyRepository.Setup(x => x.GetById(currencyUSD.Id)).Returns(currencyUSD); _currencyRepository.Setup(x => x.GetById(currencyEUR.Id)).Returns(currencyEUR); _currencyRepository.Setup(x => x.GetById(currencyRUR.Id)).Returns(currencyRUR); _storeMappingService = new Mock <IStoreMappingService>(); var cacheManager = new TestCacheManager(); _currencySettings = new CurrencySettings { PrimaryStoreCurrencyId = currencyUSD.Id, PrimaryExchangeRateCurrencyId = currencyEUR.Id }; _eventPublisher = new Mock <IEventPublisher>(); _eventPublisher.Setup(x => x.Publish(It.IsAny <object>())); var customerService = new Mock <ICustomerService>(); var loger = new Mock <ILogger>(); var webHelper = new Mock <IWebHelper>(); _catalogSettings = new CatalogSettings(); var pluginService = new PluginService(_catalogSettings, customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, webHelper.Object); _exchangeRatePluginManager = new ExchangeRatePluginManager(_currencySettings, pluginService); _currencyService = new CurrencyService(_currencySettings, _eventPublisher.Object, _exchangeRatePluginManager, _currencyRepository.Object, cacheManager, _storeMappingService.Object); }
public new void SetUp() { _discountRepo = new Mock <IRepository <Discount> >(); var discount1 = new Discount { Id = 1, DiscountType = DiscountType.AssignedToCategories, Name = "Discount 1", UsePercentage = true, DiscountPercentage = 10, DiscountAmount = 0, DiscountLimitation = DiscountLimitationType.Unlimited, LimitationTimes = 0 }; var discount2 = new Discount { Id = 2, DiscountType = DiscountType.AssignedToSkus, Name = "Discount 2", UsePercentage = false, DiscountPercentage = 0, DiscountAmount = 5, RequiresCouponCode = true, CouponCode = "SecretCode", DiscountLimitation = DiscountLimitationType.NTimesPerCustomer, LimitationTimes = 3 }; _discountRepo.Setup(x => x.Table).Returns(new List <Discount> { discount1, discount2 }.AsQueryable()); _eventPublisher = new Mock <IEventPublisher>(); _eventPublisher.Setup(x => x.Publish(It.IsAny <object>())); _storeContext = new Mock <IStoreContext>(); _customerService = new Mock <ICustomerService>(); _categoryRepo = new Mock <IRepository <Category> >(); _categoryRepo.Setup(x => x.Table).Returns(new List <Category>().AsQueryable()); _manufacturerRepo = new Mock <IRepository <Manufacturer> >(); _manufacturerRepo.Setup(x => x.Table).Returns(new List <Manufacturer>().AsQueryable()); _productRepo = new Mock <IRepository <Product> >(); _productRepo.Setup(x => x.Table).Returns(new List <Product>().AsQueryable()); var cacheManager = new TestCacheManager(); _discountRequirementRepo = new Mock <IRepository <DiscountRequirement> >(); _discountRequirementRepo.Setup(x => x.Table).Returns(new List <DiscountRequirement>().AsQueryable()); _discountUsageHistoryRepo = new Mock <IRepository <DiscountUsageHistory> >(); var loger = new Mock <ILogger>(); var webHelper = new Mock <IWebHelper>(); _catalogSettings = new CatalogSettings(); var pluginService = new PluginService(_catalogSettings, _customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, webHelper.Object); _localizationService = new Mock <ILocalizationService>(); _categoryService = new Mock <ICategoryService>(); _discountPluginManager = new DiscountPluginManager(pluginService); _discountService = new DiscountService(_categoryService.Object, _customerService.Object, _discountPluginManager, _eventPublisher.Object, _localizationService.Object, _categoryRepo.Object, _discountRepo.Object, _discountRequirementRepo.Object, _discountUsageHistoryRepo.Object, _manufacturerRepo.Object, _productRepo.Object, cacheManager, _storeContext.Object); }
public PluginController(PluginService service) { this.service = service; }
public void PluginServiceToXmlExpectedSerializesProperties() { var expected = new PluginService { Source = new PluginSource { ResourceID = Guid.NewGuid(), ResourceName = "TestWebSource", }, Namespace = "abc.pqr", }; expected.Method.Parameters.AddRange( new[] { new MethodParameter { Name = "Param1", DefaultValue = "123" }, new MethodParameter { Name = "Param2", DefaultValue = "456" } }); var rs1 = new Recordset { Name = "Recordset1()" }; rs1.Fields.AddRange(new[] { new RecordsetField { Name = "Field1", Alias = "Alias1" }, new RecordsetField { Name = "Field2", Alias = "Alias2", Path = new XmlPath("actual", "display", "outputExpression", "sampleData") }, new RecordsetField { Name = "Field3", Alias = null } }); expected.Recordsets.Add(rs1); var xml = expected.ToXml(); var actual = new PluginService(xml); Assert.AreEqual(expected.Source.ResourceType, actual.Source.ResourceType); Assert.AreEqual(expected.Source.ResourceID, actual.Source.ResourceID); Assert.AreEqual(expected.Source.ResourceName, actual.Source.ResourceName); Assert.AreEqual(expected.ResourceType, actual.ResourceType); Assert.AreEqual(expected.Namespace, actual.Namespace); foreach (var expectedParameter in expected.Method.Parameters) { var actualParameter = actual.Method.Parameters.First(p => p.Name == expectedParameter.Name); Assert.AreEqual(expectedParameter.DefaultValue, actualParameter.DefaultValue); } foreach (var expectedRecordset in expected.Recordsets) { // expect actual to have removed recordset notation ()... var actualRecordset = actual.Recordsets.First(rs => rs.Name == expectedRecordset.Name.Replace("()", "")); foreach (var expectedField in expectedRecordset.Fields) { var actualField = actualRecordset.Fields.FirstOrDefault(f => expectedField.Name == null ? f.Name == "" : f.Name == expectedField.Name); Assert.IsNotNull(actualField); Assert.AreEqual(expectedField.Alias ?? "", actualField.Alias); if (actualField.Path != null) { Assert.AreEqual(expectedField.Path.ActualPath, actualField.Path.ActualPath); Assert.AreEqual(expectedField.Path.DisplayPath, actualField.Path.DisplayPath); Assert.AreEqual(string.Format("[[{0}]]", expectedField.Alias), actualField.Path.OutputExpression); Assert.AreEqual(expectedField.Path.SampleData, actualField.Path.SampleData); } } } }
public MultipleInstallerTests() { plugins = new PluginService(log); log = new Mock.Services.LogService(false); }
internal static IContainer Global(string[] args, string clientName, PluginService pluginService) { var builder = new ContainerBuilder(); builder.RegisterType <LogService>(). As <ILogService>(). SingleInstance(); builder.RegisterType <OptionsService>(). As <IOptionsService>(). WithParameter(new TypedParameter(typeof(string[]), args)). SingleInstance(); builder.RegisterType <SettingsService>(). WithParameter(new TypedParameter(typeof(string), clientName)). SingleInstance(); builder.RegisterType <InputService>(). As <IInputService>(). SingleInstance(); builder.RegisterType <ProxyService>(). SingleInstance(); // Check where to load Renewals from var hive = Registry.CurrentUser; var key = hive.OpenSubKey($"Software\\{clientName}"); if (key == null) { hive = Registry.LocalMachine; key = hive.OpenSubKey($"Software\\{clientName}"); } if (key != null) { builder.RegisterType <RegistryRenewalService>(). As <IRenewalService>(). WithParameter(new NamedParameter("hive", hive.Name)). SingleInstance(); } else { builder.RegisterType <FileRenewalService>(). As <IRenewalService>(). SingleInstance(); } builder.RegisterType <DotNetVersionService>(). SingleInstance(); pluginService.Configure(builder); builder.RegisterInstance(clientName).Named <string>("clientName"); builder.Register(c => new DomainParser(new WebTldRuleProvider())).SingleInstance(); builder.RegisterType <IISClient>().SingleInstance(); builder.RegisterType <UnattendedResolver>(); builder.RegisterType <InteractiveResolver>(); builder.RegisterInstance(pluginService); return(builder.Build()); }
public void Start(PluginStartArguments pluginStartArgs) { //initialize static context StaticContext.Initialize(pluginStartArgs.Plugin, pluginStartArgs.ServiceProvider); var entMan = new EntityManager(); var relMan = new EntityRelationManager(); var recMan = new RecordManager(); var storeSystemSettings = DbContext.Current.SettingsRepository.Read(); var systemSettings = new SystemSettings(storeSystemSettings); using (SecurityContext.OpenSystemScope()) { //Create transaction using (var connection = DbContext.Current.CreateConnection()) { try { connection.BeginTransaction(); //Here we need to initialize or update the environment based on the plugin requirements. //The default place for the plugin data is the "plugin_data" entity -> the "data" text field, which is used to store stringified JSON //containing the plugin settings or version #region << 1.Get the current ERP database version and checks for other plugin dependencies >> if (systemSettings.Version > 0) { //Do something if database version is not what you expect } //This plugin needs the webvella-crm plugin to be installed, so we will check this here var installedPlugins = new PluginService().Plugins; var crmPluginFound = false; foreach (var plugin in installedPlugins) { switch (plugin.Name) { case "webvella-crm": crmPluginFound = true; break; default: break; } } if (!crmPluginFound) { throw new Exception("'webvella-crm' plugin is required for the 'webvella-project' to operate"); } #endregion #region << 2.Get the current plugin settings from the database >> var currentPluginSettings = new PluginSettings(); QueryObject pluginDataQueryObject = EntityQuery.QueryEQ("name", WEBVELLA_PROJECT_PLUGIN_NAME); var pluginDataQuery = new EntityQuery("plugin_data", "*", pluginDataQueryObject); var pluginDataQueryResponse = recMan.Find(pluginDataQuery); if (!pluginDataQueryResponse.Success) { throw new Exception("plugin 'webvella-project' failed to get its settings due to: " + pluginDataQueryResponse.Message); } if (pluginDataQueryResponse.Object == null || !pluginDataQueryResponse.Object.Data.Any() || pluginDataQueryResponse.Object.Data[0]["data"] == DBNull.Value) { //plugin was not installed currentPluginSettings.Version = 20160429; { string json = JsonConvert.SerializeObject(currentPluginSettings); var settingsEntityRecord = new EntityRecord(); settingsEntityRecord["id"] = WEBVELLA_PROJECT_PLUGIN_ID; settingsEntityRecord["name"] = WEBVELLA_PROJECT_PLUGIN_NAME; settingsEntityRecord["data"] = json; var settingsSaveReponse = recMan.CreateRecord("plugin_data", settingsEntityRecord); if (!settingsSaveReponse.Success) { throw new Exception("plugin 'webvella-project' failed to save its settings in the database due to: " + pluginDataQueryResponse.Message); } } } else { string json = (string)((List <EntityRecord>)pluginDataQueryResponse.Object.Data)[0]["data"]; currentPluginSettings = JsonConvert.DeserializeObject <PluginSettings>(json); } #endregion #region << 3. Run methods based on the current installed version of the plugin >> if (currentPluginSettings.Version < 20160430) { try { currentPluginSettings.Version = 20160430; Patch160430(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20160610) { try { currentPluginSettings.Version = 20160610; Patch160610(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20160613) { try { currentPluginSettings.Version = 20160613; Patch160613(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20160627) { try { currentPluginSettings.Version = 20160627; Patch160627(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20160707) { try { currentPluginSettings.Version = 20160707; Patch160707(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20161118) { try { currentPluginSettings.Version = 20161118; Patch161118(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20161119) { try { currentPluginSettings.Version = 20161119; Patch161119(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20170119) { try { currentPluginSettings.Version = 20170119; Patch170119(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20170328) { try { currentPluginSettings.Version = 20170328; Patch170328(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } if (currentPluginSettings.Version < 20170502) { try { currentPluginSettings.Version = 20170502; Patch20170502(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { throw ex; } } #endregion #region << 4. Save needed changes to the plugin setting data >> { string json = JsonConvert.SerializeObject(currentPluginSettings); var settingsEntityRecord = new EntityRecord(); settingsEntityRecord["id"] = WEBVELLA_PROJECT_PLUGIN_ID; settingsEntityRecord["name"] = WEBVELLA_PROJECT_PLUGIN_NAME; settingsEntityRecord["data"] = json; var settingsUpdateReponse = recMan.UpdateRecord("plugin_data", settingsEntityRecord); if (!settingsUpdateReponse.Success) { throw new Exception("plugin 'webvella-project' failed to update its settings in the database due to: " + pluginDataQueryResponse.Message); } } #endregion connection.CommitTransaction(); } catch (Exception ex) { connection.RollbackTransaction(); throw ex; } } } }
public new void SetUp() { _shippingSettings = new ShippingSettings { UseCubeRootMethod = true, ConsiderAssociatedProductsDimensions = true, ShipSeparatelyOneItemEach = false }; _shippingMethodRepository = new Mock <IRepository <ShippingMethod> >(); _warehouseRepository = new Mock <IRepository <Warehouse> >(); _logger = new NullLogger(); _productAttributeParser = new Mock <IProductAttributeParser>(); _checkoutAttributeParser = new Mock <ICheckoutAttributeParser>(); var cacheManager = new TestCacheManager(); _productService = new Mock <IProductService>(); _eventPublisher = new Mock <IEventPublisher>(); _eventPublisher.Setup(x => x.Publish(It.IsAny <object>())); var customerService = new Mock <ICustomerService>(); var loger = new Mock <ILogger>(); var webHelper = new Mock <IWebHelper>(); _catalogSettings = new CatalogSettings(); var pluginService = new PluginService(_catalogSettings, customerService.Object, loger.Object, CommonHelper.DefaultFileProvider, webHelper.Object); _pickupPluginManager = new PickupPluginManager(pluginService, _shippingSettings); _shippingPluginManager = new ShippingPluginManager(pluginService, _shippingSettings); _localizationService = new Mock <ILocalizationService>(); _addressService = new Mock <IAddressService>(); _genericAttributeService = new Mock <IGenericAttributeService>(); _priceCalcService = new Mock <IPriceCalculationService>(); _store = new Store { Id = 1 }; _storeContext = new Mock <IStoreContext>(); _storeContext.Setup(x => x.CurrentStore).Returns(_store); _shoppingCartSettings = new ShoppingCartSettings(); _shippingService = new ShippingService(_addressService.Object, cacheManager, _checkoutAttributeParser.Object, _eventPublisher.Object, _genericAttributeService.Object, _localizationService.Object, _logger, _pickupPluginManager, _priceCalcService.Object, _productAttributeParser.Object, _productService.Object, _shippingMethodRepository.Object, _warehouseRepository.Object, _shippingPluginManager, _storeContext.Object, _shippingSettings, _shoppingCartSettings); }
private static void OpenPluginLog(object sender, bool e) { Process.Start(PluginService.GetInstance().KaptureLog); }
public void AddBuiltinPlugins(PluginService pluginService) { pluginService.AddPlugin(new AutoSavePlugin()); pluginService.AddPlugin(new FrameworkPlugin()); pluginService.AddPlugin(new RootTemplatePlugin()); pluginService.AddPlugin(new EoCPluginClass()); pluginService.AddPlugin(new ModulePlugin()); pluginService.AddPlugin(new ResourceManagerPlugin()); pluginService.AddPlugin(new AtmospherePlugin()); pluginService.AddPlugin(new TerrainPlugin()); pluginService.AddPlugin(new AIPlugin()); pluginService.AddPlugin(new CharactersPlugin()); pluginService.AddPlugin(new ItemsPlugin()); pluginService.AddPlugin(new LightPlugin()); pluginService.AddPlugin(new InvalidObjectPlugin()); pluginService.AddPlugin(new DecalPlugin()); pluginService.AddPlugin(new DummyPlugin()); pluginService.AddPlugin(new ReferencePlugin()); pluginService.AddPlugin(new TriggersPlugin()); pluginService.AddPlugin(new WallConstructionPlugin()); pluginService.AddPlugin(new LevelPlugin()); pluginService.AddPlugin(new MaterialPlugin()); pluginService.AddPlugin(new ScriptPlugin()); pluginService.AddPlugin(new PrefabPlugin()); pluginService.AddPlugin(new InstancePlugin()); pluginService.AddPlugin(new StoryEditorPlugin()); pluginService.AddPlugin(new SelectDoubleVisuals()); pluginService.AddPlugin(new KeywordPluginClass()); pluginService.AddPlugin(new TranslatedStringKeyPlugin()); pluginService.AddPlugin(new TextureAtlasPlugin()); pluginService.AddPlugin(new ViewModePlugin()); pluginService.AddPlugin(new OBJExporterPlugin()); pluginService.AddPlugin(new EoCWorldMapRendererPlugin()); pluginService.AddPlugin(new PublishPlugin()); pluginService.AddPlugin(new ModPlugin()); pluginService.AddPlugin(new AutoTemplatePlacer()); pluginService.AddPlugin(new FixPlugin()); pluginService.AddPlugin(new SpeakerPlugin()); }
private void CheckForUpdates(object sender, bool e) { Task.Run(() => PluginService.GetInstance().UpdatePlugin(Configuration.General.CheckForBetaEnabled, true)); }
/// <summary> /// 监视中间件节点配置的远程插件 /// </summary> static void MonitorRemotePlugin() { if (WcfGlobal.IsRootMNode) { #region 加载mpList //从Mongodb加载节点服务配置 List <MNodePlugin> mpList = new List <MNodePlugin>(); foreach (var ps in npList) { MNodePlugin mp = new MNodePlugin(); mp.ServerIdentify = ps.identify; mp.PathStrategy = ps.pathstrategy; mp.LocalPlugin = ps.localplugin; mp.RemotePlugin = new List <RemotePlugin>(); foreach (var r in ps.remoteplugin) { RemotePlugin rp = new RemotePlugin(); rp.PluginName = r.pluginname; rp.MNodeIdentify = r.mnodeidentify; mp.RemotePlugin.Add(rp); } mp.LocalPinfoList = new List <MNPluginInfo>(); foreach (string p in mp.LocalPlugin) { PluginService pservice = psList.Find(x => x.pluginname == p); if (pservice != null) { MNPluginInfo pinfo = new MNPluginInfo(); pinfo.pluginname = pservice.pluginname; pinfo.title = pservice.title; pinfo.versions = pservice.versions; pinfo.author = pservice.author; pinfo.introduce = pservice.introduce; pinfo.updatenotes = pservice.updatenotes; pinfo.delflag = pservice.delflag; mp.LocalPinfoList.Add(pinfo); } } mpList.Add(mp); } #endregion //CoreFrame.Common.MiddlewareLogHelper.WriterLog(JsonConvert.SerializeObject(mpList)); #region 步mpList到分布式缓存 Dictionary <string, string> sync_adddata = new Dictionary <string, string>(); //需要同步的数据 Dictionary <string, string> sync_updatedata = new Dictionary <string, string>(); //需要同步的数据 List <string> sync_deldata = new List <string>(); //需要同步的数据 string cacheName = "mnodeplugin"; CacheObject cobj = DistributedCacheManage.GetLocalCache(cacheName); if (cobj != null) { List <CacheData> cdatalist = cobj.cacheValue; //新增的 foreach (var n in mpList) { if (cdatalist.FindIndex(x => x.key == n.ServerIdentify) == -1) { sync_adddata.Add(n.ServerIdentify, JsonConvert.SerializeObject(n)); } } //删除的 foreach (var o in cdatalist) { if (mpList.FindIndex(x => x.ServerIdentify == o.key) == -1) { sync_deldata.Add(o.key); } } //更新的 foreach (var o in cdatalist) { MNodePlugin mp = mpList.Find(x => x.ServerIdentify == o.key); if (mp != null && JsonConvert.SerializeObject(mp) != o.value) { sync_updatedata.Add(o.key, JsonConvert.SerializeObject(mp)); } } } else { //新增的 foreach (var n in mpList) { sync_adddata.Add(n.ServerIdentify, JsonConvert.SerializeObject(n)); } } //调试 //foreach(var i in sync_updatedata) //{ // CoreFrame.Common.MiddlewareLogHelper.WriterLog(i.Key); // CoreFrame.Common.MiddlewareLogHelper.WriterLog(i.Value); //} DistributedCacheManage.SetCache(cacheName, sync_adddata, sync_updatedata, sync_deldata); #endregion } }
/// <summary> /// Configure dependency injection /// </summary> /// <param name="args"></param> /// <returns></returns> internal static IContainer GlobalScope(string[] args) { var builder = new ContainerBuilder(); var logger = new LogService(); if (Verbose) { logger.SetVerbose(); } // Not used but should be called anyway because it // checks if we're not running as dotnet.exe and also // prints some verbose messages that are interesting // to know very early in the start up process var versionService = new VersionService(logger); var pluginService = new PluginService(logger); var argumentsParser = new ArgumentsParser(logger, pluginService, args); var argumentsService = new ArgumentsService(logger, argumentsParser); if (!argumentsService.Valid) { return(null); } var settingsService = new SettingsService(logger, argumentsService); if (!settingsService.Valid) { return(null); } logger.SetDiskLoggingPath(settingsService.Client.LogPath); _ = builder.RegisterInstance(argumentsService); _ = builder.RegisterInstance(argumentsParser); _ = builder.RegisterInstance(logger).As <ILogService>(); _ = builder.RegisterInstance(settingsService).As <ISettingsService>(); _ = builder.RegisterInstance(argumentsService).As <IArgumentsService>(); _ = builder.RegisterInstance(pluginService).As <IPluginService>(); _ = builder.RegisterType <UserRoleService>().As <IUserRoleService>().SingleInstance(); _ = builder.RegisterType <InputService>().As <IInputService>().SingleInstance(); _ = builder.RegisterType <ProxyService>().SingleInstance(); _ = builder.RegisterType <UpdateClient>().SingleInstance(); _ = builder.RegisterType <PasswordGenerator>().SingleInstance(); _ = builder.RegisterType <RenewalStoreDisk>().As <IRenewalStore>().SingleInstance(); pluginService.Configure(builder); _ = builder.RegisterType <DomainParseService>().SingleInstance(); _ = builder.RegisterType <IISClient>().As <IIISClient>().InstancePerLifetimeScope(); _ = builder.RegisterType <IISHelper>().SingleInstance(); _ = builder.RegisterType <ExceptionHandler>().SingleInstance(); _ = builder.RegisterType <UnattendedResolver>(); _ = builder.RegisterType <InteractiveResolver>(); _ = builder.RegisterType <AutofacBuilder>().As <IAutofacBuilder>().SingleInstance(); _ = builder.RegisterType <AccountManager>().SingleInstance(); _ = builder.RegisterType <AcmeClient>().SingleInstance(); _ = builder.RegisterType <ZeroSsl>().SingleInstance(); _ = builder.RegisterType <OrderManager>().SingleInstance(); _ = builder.RegisterType <PemService>().SingleInstance(); _ = builder.RegisterType <EmailClient>().SingleInstance(); _ = builder.RegisterType <ScriptClient>().SingleInstance(); _ = builder.RegisterType <LookupClientProvider>().SingleInstance(); _ = builder.RegisterType <CertificateService>().As <ICertificateService>().SingleInstance(); _ = builder.RegisterType <TaskSchedulerService>().SingleInstance(); _ = builder.RegisterType <NotificationService>().SingleInstance(); _ = builder.RegisterType <RenewalExecutor>().SingleInstance(); _ = builder.RegisterType <RenewalValidator>().SingleInstance(); _ = builder.RegisterType <RenewalManager>().SingleInstance(); _ = builder.RegisterType <RenewalCreator>().SingleInstance(); _ = builder.Register(c => c.Resolve <IArgumentsService>().MainArguments).SingleInstance(); _ = builder.RegisterType <Wacs>(); return(builder.Build()); }