public override Control AddTo(Control container, PluginContext context) { if(!ActiveFor(container, context.State)) return null; if (context.Selected == null) return null; if (context.Selected.VersionOf.HasValue) return null; IEngine engine = Context.Current; //TODO: fixme, cause items to be deserialized always //ContentItem latestVersion = engine.Resolve<IVersionManager>().GetVersionsOf(context.Selected, 0, 1)[0]; var draft = engine.Resolve<DraftRepository>().GetDraftInfo(context.Selected); if (draft == null) return null; var latestVersion = engine.Resolve<DraftRepository>().FindDrafts(context.Selected).Select(v => v.Version).FirstOrDefault(); if (latestVersion == null) return null; Url versionPreviewUrl = engine.GetContentAdapter<NodeAdapter>(latestVersion).GetPreviewUrl(latestVersion); versionPreviewUrl = versionPreviewUrl.SetQueryParameter("edit", context.HttpContext.Request["edit"]); HyperLink hl = new HyperLink(); hl.NavigateUrl = versionPreviewUrl; hl.Text = GetInnerHtml(context, latestVersion.State == ContentState.Waiting ? "{IconsUrl}/clock_play.png".ResolveUrlTokens() : IconUrl, ToolTip, Title); hl.CssClass = "preview"; hl.ToolTip = Utility.GetResourceString(GlobalResourceClassName, Name + ".ToolTip") ?? context.Format(ToolTip, false); container.Controls.Add(hl); return hl; }
public static void OnGameLoad(PluginContext context) { foreach (var plugin in plugins) { plugin.OnGameLoad(context); } }
public PluginVirtualPathProvider(PluginContext pluginContext) { if(pluginContext == null) throw new ArgumentNullException("pluginContext"); _pluginContext = pluginContext; }
/// <summary/> public PluginManager( MSExcel.Application application ) { myApplication = application; myPluginContext = new PluginContext( myApplication ); myPlugins = new List<AbstractPlugin>(); }
public static void Initialize(PluginContext context) { foreach (var plugin in plugins) { plugin.Initialize(context); } }
public DebuggerWindow(PluginContext context, string hackPath) { this.InitializeComponent(); Trace.Listeners.Add(this.listener); CompositionTarget.Rendering += CompositionTarget_Rendering; }
public static void Start(PluginContext context, String hackPath) { Context = context; HackPath = hackPath; var thread = new Thread(new ThreadStart(Thread)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
public void Initialize(PluginContext pluginContext) { Func<IEnumerable<Type>, IEnumerable<Type>> clientCompaniesManagementTypesFilter = c => c.Where(t => t.GetCustomAttributes(false).Any(a => a is ClientCompaniesManagementTabAttribute)); pluginContext.MapToTypes<CurrentMenuControllerPlugin>(clientCompaniesManagementTypesFilter). MapToTypes<BottomButtonsControllerPlugin>(clientCompaniesManagementTypesFilter). MapToTypes<RouteSaveCollectionControllerPlugin>(clientCompaniesManagementTypesFilter). MapToTypes<CurrentControllerPlugin>(clientCompaniesManagementTypesFilter). MapToTypes<UserAccessControllerPlugin>(clientCompaniesManagementTypesFilter); }
public override System.Web.UI.Control AddTo(System.Web.UI.Control container, PluginContext context) { Literal l = new Literal(); l.Text = string.Format(@" <form target='navigation' method='get' action='{1}'> <input type='text' name='query' class='tb' value='{0}' onfocus='if(this.value==""{0}""){{this.value=""""}}' onblur='if(this.value==""""){{this.value=""{0}"";}}'/> <button type='submit' name='submit' class='s'>{0}</button> </form>", Utility.GetResourceString(GlobalResourceClassName, Name + ".Title") ?? Title, Url.ResolveTokens("{ManagementUrl}/Content/Navigation/Search.aspx")); container.Controls.Add(l); return l; }
protected PluginViewEngine(PluginContext pluginContext) { if(pluginContext == null) throw new ArgumentNullException("pluginContext"); _pluginContext = pluginContext; if(HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled) _viewLocationCache = DefaultViewLocationCache.Null; else _viewLocationCache = new DefaultViewLocationCache(); }
public PluginWebFormView(PluginContext pluginContext, string viewPath, string masterPath) { if(pluginContext == null) throw new ArgumentNullException("pluginContext"); if(string.IsNullOrEmpty(viewPath)) throw new ArgumentNullException("viewPath"); _pluginContext = pluginContext; _viewPath = viewPath; _masterPath = masterPath ?? string.Empty; }
public override Control AddTo(Control container, PluginContext context) { HtmlGenericControl div = new HtmlGenericControl("div"); div.Attributes["class"] = "sort"; container.Controls.Add(div); HtmlAnchor up = AddSortAnchor(div, context.Rebase(context.Format("Navigation/sortUp.ashx?selected={Selected.Path}", true)), "~/N2/Resources/icons/bullet_arrow_up.png", "up"); RegisterToolbarUrl(container, up.ClientID, context.Rebase("Content/Navigation/sortUp.ashx?selected={selected}")); HtmlAnchor down = AddSortAnchor(div, context.Rebase(context.Format("Navigation/sortDown.ashx?selected={Selected.Path}", true)), "~/N2/Resources/icons/bullet_arrow_down.png", "down"); RegisterToolbarUrl(container, down.ClientID, context.Rebase("Content/Navigation/sortDown.ashx?selected={selected}")); return div; }
public override System.Web.UI.Control AddTo(System.Web.UI.Control container, PluginContext context) { try { if (System.Web.Security.Membership.Providers.Count == 0) return null; } catch (System.Configuration.Provider.ProviderException) { return null; } return base.AddTo(container, context); }
protected virtual HtmlAnchor AddSortAnchor(Control container, PluginContext context, string url, string iconUrl, string key) { HtmlAnchor a = new HtmlAnchor(); a.ID = key + Name; a.HRef = context.Rebase(url); a.Target = Target; a.Attributes["class"] = "templatedurl " + key; a.Title = Utility.GetResourceString(GlobalResourceClassName, key + Name + ".ToolTip") ?? ToolTip; a.Style[HtmlTextWriterStyle.BackgroundImage] = context.Rebase(iconUrl); container.Controls.Add(a); return a; }
public EntryPoint(RemoteHooking.IContext hookingContext, PluginContext context, Boolean isDebugging, String hackPath, String installPath) { try { this.context = context; } catch (Exception exception) { MessageBox.Show( "Fatal exception!" + Environment.NewLine + exception + Environment.NewLine + "Aborting execution!", this.GetType() + ".ctor(...)", MessageBoxButton.OK, MessageBoxImage.Error); Process.GetCurrentProcess().Kill(); } }
private void PersonalArtefactManagerControl_Load(object sender, EventArgs e) { //OpenLogFile(); //ShowInfoNotification("This is a notification that can lead to XrmToolBox repository", new Uri("http://github.com/MscrmTools/XrmToolBox")); // Loads or creates the settings for the pluginCtx if (!SettingsManager.Instance.TryLoad(GetType(), out _pluginSettings)) { _pluginSettings = new Settings(); LogWarning("Settings not found => a new settings file has been created!"); } else { LogInfo("Settings found and loaded"); } _pluginCtx = new PluginContext(this); _userManager = new UserManager(_pluginCtx); _userListViewBuilder = new UserListViewBuilder(); _artefactManagerFactory = new ArtefactManagerFactory(_pluginCtx); // Initialize controls lvCrmArtefacts.Visible = true; cbArtefactTypeSelector.Items.AddRange(new object[] { new ComboBoxItem("Personal Views", PersonalArtefactType.UserQuery), new ComboBoxItem("Personal Dashboards", PersonalArtefactType.UserForm), new ComboBoxItem("Personal Diagrams", PersonalArtefactType.UserQueryVisualization), }); cbOperationSelector.Items.AddRange(new object[] { new ComboBoxItem("Copy + Assign", PluginOperation.Duplicate), new ComboBoxItem("Assign", PluginOperation.Assign), new ComboBoxItem("Delete", PluginOperation.Delete), }); // Wire up application event handlers _userManager.UserListUpdated += OnUserManagerOnUserListUpdated; _artefactManagerFactory.ArtefactListUpdated += OnArtefactListUpdated; PersonalArtifactTypeSelected += OnArtefactTypeSelected; SourceUserSelected += OnSourceUserSelected; // Initially load user list btnLoadUsers.PerformClick(); ResetFormState(); _isPluginLoaded = true; }
public void ActivatePlugins_PluginRuleViolations_ShouldCallReporter() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_one.dll"); var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { filePath1, new MockFileData(string.Empty) } }); var assemblyWrapper = new TestAssemblyWrapper(); var pluginPaths = new Dictionary <string, string> { { "my-plugin", filePath1 } }; var reporter = Substitute.For <IReporter>(); var textReader = ParsingUtility.CreateTextReaderFromString("\tSELECT * FROM FOO"); var scriptPath = TestHelper.GetTestFilePath(@"c:\scripts\foo.sql"); var context = new PluginContext(scriptPath, new List <IRuleException>(), textReader); var versionWrapper = Substitute.For <IFileversionWrapper>(); versionWrapper.GetVersion(Arg.Any <Assembly>()).Returns("1.2.3"); // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); // assert Assert.AreEqual(1, pluginHandler.Plugins.Count); Assert.DoesNotThrow(() => pluginHandler.ActivatePlugins(context)); reporter.Received().ReportViolation(Arg.Is <IRuleViolation>(x => x.FileName == context.FilePath && x.RuleName == "prefer-tabs" && x.Text == "Should use spaces rather than tabs" && x.Line == 1 && x.Column == 0 && x.Severity == RuleViolationSeverity.Warning)); }
public override async Task <string> Handle(HttpRequest request, HttpResponse response) { string pluginKey = ParsePluginKey(request); if (!string.IsNullOrEmpty(pluginKey)) { var plugin = PluginManager.Instance.GetPlugin(pluginKey); if (plugin != null) { Log.LogDebug("Execute: {0}", plugin.ToString()); try { Playlist pluginResponse = null; await Task.Run((() => { var query = request.Query.ConvertToNameValue(); var context = new PluginContext(pluginKey, request, query); pluginResponse = plugin.Instance.GetList(context); })); if (pluginResponse != null) { if (!string.IsNullOrEmpty(pluginResponse.source)) { Log.LogDebug( "Plugin Playlist.source not null! Write to response Playlist.source and ignore other methods. Plugin: {0}", pluginKey); return(pluginResponse.source); //} else if (!string.IsNullOrEmpty(pluginResponse.IsIptv) && pluginResponse.IsIptv == "True") { //return ResponseSerializer.PlaylistToM3U8(pluginResponse); } else { return(ResponseSerializer.PlaylistToXml(pluginResponse)); } } } catch (Exception exception) { Log.LogError(exception); response.StatusCode = (int)HttpStatusCode.BadRequest; return($"Plugin: {pluginKey}"); } } } response.StatusCode = (int)HttpStatusCode.NotFound; return($"Plugin is not defined in request. Plugin: {pluginKey}"); }
protected override void ExecuteBusinessLogic(PluginContext pluginContext) { var taskRef = pluginContext.TargetImageEntityReference; if (taskRef == null) { return; } var taskEntity = pluginContext.OrganizationService.Retrieve(taskRef.LogicalName, taskRef.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("ylv_outlookid")); if (taskEntity.Contains("ylv_outlookid")) { DeleteTaskInOutlook(new TaskEntity { OutlookId = taskEntity["ylv_outlookid"].ToString() }, serviceUrl); } }
public void ReturnsPostImage() { var serviceProvider = default(IServiceProvider); var context = default(IPluginContext); var image = new Entity(Schema.AccountEntity.TypeName, Guid.NewGuid()); serviceProvider = CreateServiceProvider(postImage: image); context = new PluginContext(serviceProvider); Assert.AreSame(image, context.GetEntityImage(EntityImageType.PostImage)); Assert.IsNull(context.GetEntityImage(EntityImageType.PreImage)); serviceProvider = CreateServiceProvider(); context = new PluginContext(serviceProvider); Assert.IsNull(context.GetEntityImage(EntityImageType.PostImage)); }
private TcpipUnapiPlugin(PluginContext context, IDictionary <string, object> pluginConfig) { slotNumber = new SlotNumber((byte)pluginConfig["NestorMSX.slotNumber"]); cpu = context.Cpu; slots = context.SlotsSystem; cpu.BeforeInstructionFetch += Cpu_BeforeInstructionFetch; bool hasIp(NetworkInterface iface, string ip) { return(iface.GetIPProperties().UnicastAddresses.Any(a => a.Address.ToString() == ip)); } bool hasIpv4Address(NetworkInterface iface) { return(iface.GetIPProperties().UnicastAddresses.Any(a => IsIPv4(a.Address))); } var ipAddress = pluginConfig.GetValueOrDefault("ipAddress", ""); var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() .Where(i => i.Supports(NetworkInterfaceComponent.IPv4)); if (ipAddress == "") { networkInterface = networkInterfaces.FirstOrDefault(i => hasIpv4Address(i) && i.NetworkInterfaceType != NetworkInterfaceType.Loopback) ?? networkInterfaces.FirstOrDefault(i => hasIpv4Address(i)); ipInfo = networkInterface?.GetIPProperties().UnicastAddresses.First(a => IsIPv4(a.Address)); } else { networkInterface = networkInterfaces.FirstOrDefault(i => hasIp(i, ipAddress)); ipInfo = networkInterface?.GetIPProperties().UnicastAddresses.First(a => a.Address.ToString() == ipAddress); } if (networkInterface == null) { throw new Exception(ipAddress == "" ? "No IPv4 network interfaces available" : $"There is no network interface with the IP address {ipAddress}"); } dnsServersAvailable = networkInterface.GetIPProperties().DnsAddresses.Any(); mtu = (short)Math.Min(32767, networkInterface.GetIPProperties().GetIPv4Properties().Mtu); InitRoutinesArray(); }
public void ConvertsPowerShellSource() { var records = new List <Envelope <JObject> > { new Envelope <JObject>(JObject.Parse("{\"ComputerName\":\"MyComputer\",\"Name\":\"TrustedInstaller\",\"Status\":\"Running\"}")), new Envelope <JObject>(JObject.Parse("{\"ComputerName\":\"MyComputer\",\"Name\":\"WinRM\",\"Status\":\"Stopped\"}")) }; var config = TestUtility.GetConfig("Pipes", "PSEMFTestPipe"); using (var logger = new MemoryLogger(nameof(EMFPipeTests))) { var context = new PluginContext(config, logger, null); var source = new MockEventSource <JObject>(context); var sink = new MockEventSink(context); context.ContextData[PluginContext.SOURCE_TYPE] = source.GetType(); context.ContextData[PluginContext.SOURCE_OUTPUT_TYPE] = source.GetOutputType(); context.ContextData[PluginContext.SINK_TYPE] = sink.GetType(); var pipe = new EMFPipe <JObject>(context); source.Subscribe(pipe); pipe.Subscribe(sink); foreach (var r in records) { source.MockEvent(r.Data); } Assert.Equal(2, sink.Records.Count); var jo = JObject.Parse(sink.Records.First()); Assert.Equal("PSNamespace", jo["_aws"]["CloudWatchMetrics"][0]["Namespace"].ToString()); Assert.Equal("ServiceStatus", jo["_aws"]["CloudWatchMetrics"][0]["Metrics"][0]["Name"].ToString()); Assert.Equal(1, jo["ServiceStatus"].ToObject <int>()); Assert.Equal("Running", jo["Status"].ToString()); Assert.Equal("TrustedInstaller", jo["Name"].ToString()); var dims = jo["_aws"]["CloudWatchMetrics"][0]["Dimensions"][0].ToArray().Select(i => i.ToString()).ToList(); Assert.Equal(3, dims.Count); Assert.Contains("Name", dims); Assert.Contains("ComputerName", dims); Assert.Contains("Status", dims); jo = JObject.Parse(sink.Records.Last()); Assert.Equal("Stopped", jo["Status"].ToString()); Assert.Equal("WinRM", jo["Name"].ToString()); } }
private static void Main(string[] args) { List <IPlugin> plugins = PluginManager.GetExecutePlugin(); PluginCollection configs = PluginManager.GetPlugins(); for (int i = 0; i < plugins.Count; i++) { PluginContext context = PluginManager.GetExecutePluginContext(configs[i].Name); context.Config = PluginManager.GetPluginConfig(configs[i].Name); Console.WriteLine(configs[i].Name + " running ....."); plugins[i].Execute(context); Console.WriteLine(configs[i].Name + " complete ....."); } Console.WriteLine("complete"); Console.ReadKey(); }
public void Route_JsonConfig_ClaimedMethodsExecuted() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("test.json"); var configurationRoot = builder.Build(); var configuration = configurationRoot.Get <ExtensibilityConfiguration>(); var context = new PluginContext(_strategy); var hostAdapter = new HostAdapter <ISegmentedContract>(context, configuration); var proxy = RoutableProxy.Create <ISegmentedContract>(hostAdapter); Assert.Equal(ISegmentedContract.FirstSomeMethod, proxy.SomeMethod()); Assert.Equal(ISegmentedContract.SecondSomeOtherMethod, proxy.SomeOtherMethod()); }
public void TestStoreProcedure(string testFile) { var currentConsoleOut = Console.Out; string path = Path.Combine(_testDirectoryPath, testFile); var ruleExceptions = new List <IRuleException>(); var reporter = new ConsoleReporter(); var startTime = DateTime.Now; using (TextReader textReader = File.OpenText(path)) { var pluginContext = new PluginContext(path, ruleExceptions, textReader); IPlugin plugin = new MyPlugin(); plugin.PerformAction(pluginContext, reporter); } var endtime = DateTime.Now; var duration = startTime - endtime; using (var consoleOutput = new ConsoleOutput()) { reporter.ReportResults(duration, 4); NonBlockingConsole.Consumer(); var consoleOutputValues = consoleOutput.GetOuput().Split('\n'); var result = consoleOutputValues?.Where(x => x.Trim().EndsWith("Errors.")) .FirstOrDefault(); switch (testFile) { case "usp_GetCurrency1.sql": Assert.AreEqual("2 Errors.", result); break; case "usp_GetCurrency2.sql": Assert.AreEqual("0 Errors.", result); break; case "usp_GetCurrency.sql": Assert.AreEqual("1 Errors.", result); break; case "usp_GetCurrency3.sql": Assert.AreEqual("2 Errors.", result); break; } } Assert.AreEqual(currentConsoleOut, Console.Out); }
public PluginAssemblyLoadContext(PluginInfo info, PluginContext alcContext) : base($"{nameof(LazyMan)}:Plugin:{info.PluginName}", true) { PluginInfo = info ?? throw new ArgumentNullException(nameof(info)); ALCContext = alcContext ?? throw new ArgumentNullException(nameof(alcContext)); try { // resolver have bug for fileName Resolver = new AssemblyDependencyResolver(info.PluginDll); } catch (Exception e) { Debug.WriteLine(e); } // if this load fail, then throw EntryAssemlby = this.LoadFromAssemblyPath(info.PluginDll); }
public override Control AddTo(Control container, PluginContext context) { if (!ActiveFor(container, context.State)) { return(null); } if (context.Selected == null) { return(null); } if (context.Selected.VersionOf.HasValue) { return(null); } IEngine engine = Context.Current; //TODO: fixme, cause items to be deserialized always //ContentItem latestVersion = engine.Resolve<IVersionManager>().GetVersionsOf(context.Selected, 0, 1)[0]; var draft = engine.Resolve <DraftRepository>().GetDraftInfo(context.Selected); if (draft == null) { return(null); } var drafts = engine.Resolve <DraftRepository>(); var latestVersion = drafts.FindDrafts(context.Selected).Select(v => drafts.Versions.DeserializeVersion(v)).FirstOrDefault(); if (latestVersion == null) { return(null); } Url versionPreviewUrl = engine.GetContentAdapter <NodeAdapter>(latestVersion).GetPreviewUrl(latestVersion); versionPreviewUrl = versionPreviewUrl.SetQueryParameter("edit", context.HttpContext.Request["edit"]); HyperLink hl = new HyperLink(); hl.NavigateUrl = versionPreviewUrl; hl.Text = GetInnerHtml(context, latestVersion.State == ContentState.Waiting ? "{IconsUrl}/clock_play.png".ResolveUrlTokens() : IconUrl, ToolTip, Title); hl.CssClass = "preview"; hl.ToolTip = Utility.GetResourceString(GlobalResourceClassName, Name + ".ToolTip") ?? context.Format(ToolTip, false); container.Controls.Add(hl); return(hl); }
public bool EditAccountForm(string name, PluginContext context) { var path = GetPath(name); if (File.Exists(path)) { var account = AccountInfo.Parse(File.ReadAllLines(path, Encoding.Unicode)); using (var form = new AccountForm(name, account)) { if (form.ShowDialog() == DialogResult.OK) { Save(path, form.AccountInfo); return(true); } } } return(false); }
public override Control AddTo(Control container, PluginContext context) { HtmlGenericControl div = new HtmlGenericControl("div"); div.Attributes["class"] = "sort"; container.Controls.Add(div); HtmlAnchor up = AddSortAnchor(div, context, context.Format("{ManagementUrl}/Content/Navigation/sortUp.ashx?{Selection.SelectedQueryKey}={Selected.Path}", true), "{ManagementUrl}/Resources/icons/bullet_arrow_up.png", "up"); up.Attributes["data-url-template"] = context.Rebase("{ManagementUrl}/Content/Navigation/sortUp.ashx?" + SelectionUtility.SelectedQueryKey + "={selected}"); HtmlAnchor down = AddSortAnchor(div, context, context.Format("{ManagementUrl}/Content/Navigation/sortDown.ashx?{Selection.SelectedQueryKey}={Selected.Path}", true), "{ManagementUrl}/Resources/icons/bullet_arrow_down.png", "down"); down.Attributes["data-url-template"] = context.Rebase("{ManagementUrl}/Content/Navigation/sortDown.ashx?" + SelectionUtility.SelectedQueryKey + "={selected}"); return div; }
public static User LoadByUsername(string username) { User userObject = null; using (var entities = new PluginContext()) { var entity = entities.Users //.Include(e => e.Stats) e.g. .FirstOrDefault(e => e.Username == username); if (entity != null) { // Load data and extra data, such as linked objects or XML data, etc... userObject = new User(entity.Id, entity.Username, entity.Hash, entity.Salt, entity.Email, entity.Souls, entity.Skulls); } } return(userObject); }
protected PluginViewEngine(PluginContext pluginContext) { if (pluginContext == null) { throw new ArgumentNullException("pluginContext"); } _pluginContext = pluginContext; if (HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled) { _viewLocationCache = DefaultViewLocationCache.Null; } else { _viewLocationCache = new DefaultViewLocationCache(); } }
/// <summary> /// 获取 <see cref="ContactShare"/> 实例的内容。 /// </summary> /// <param name="share">要操作的 <see cref="ContactShare"/> 实例。</param> /// <param name="context">要使用的 <see cref="PluginContext"/>。</param> public static IChattable?GetContent(this ContactShare share, PluginContext context) { if (share is null) { throw new ArgumentNullException(nameof(share)); } if (context is null) { throw new ArgumentNullException(nameof(context)); } return(share.ContentType switch { "qq" => context.GetUser(share.ContentNumber), "group" => context.GetGroup(share.ContentNumber), _ => null });
public void ThrowsErrorForMissingImage() { this.ExpectedException <InvalidPluginExecutionException>(() => { var serviceProvider = CreateServiceProvider(); var context = new PluginContext(serviceProvider); context.GetEntityImage(EntityImageType.PreImage, throwIfNull: true); }); this.ExpectedException <InvalidPluginExecutionException>(() => { var serviceProvider = CreateServiceProvider(); var context = new PluginContext(serviceProvider); context.GetEntityImage(EntityImageType.PostImage, throwIfNull: true); }); }
public override void Execute(TriggerBase trigger) { PluginContext plugin = Singleton <PluginManager> .Instance.GetPlugin(trigger.Get <string>("name"), trigger.Get <bool>("case")); if (plugin == null) { trigger.ReplyError("Plugin not found"); } else { Singleton <PluginManager> .Instance.UnLoadPlugin(plugin); trigger.Reply("Plugin {0} unloaded", new object[] { plugin.Plugin.Name }); } }
protected override User Fetch(long id) { User userObject = null; using (var entities = new PluginContext()) { var entity = entities.Users //.Include(e => e.Stats) e.g. .FirstOrDefault(e => e.Id == id); if (entity != null) { // Load data and extra data, such as linked objects or XML data, etc... userObject = new User(entity.Id, entity.Username, entity.Hash, entity.Salt, entity.Email, entity.Souls, entity.Skulls); } } return(userObject); }
protected override void ExecuteBusinessLogic(PluginContext pluginContext) { var appointment = pluginContext.TargetImageEntity; if (appointment == null) { return; } if (appointment.Contains("description") || appointment.Contains("scheduledstart") || appointment.Contains("scheduledend")) { if (pluginContext.PluginExecutionContext.Depth > 1) { throw new InvalidPluginExecutionException("Depth"); } AppointmentEntity updateAppointment = new AppointmentEntity(); Entity oldAppointment = pluginContext.OrganizationService.Retrieve("appointment", appointment.Id, new ColumnSet(true)); if (oldAppointment == null) { throw new InvalidPluginExecutionException("Error then try get old appointment data"); } updateAppointment.CrmId = appointment.Id; updateAppointment.Body = oldAppointment["description"].ToString(); updateAppointment.Start = DateTime.Parse(oldAppointment["scheduledstart"].ToString()); updateAppointment.End = DateTime.Parse(oldAppointment["scheduledend"].ToString()); if (appointment.Contains("description")) { updateAppointment.Body = appointment["description"].ToString(); } if (appointment.Contains("scheduledstart")) { updateAppointment.Start = DateTime.Parse(appointment["scheduledstart"].ToString()); } if (appointment.Contains("scheduledend")) { updateAppointment.End = DateTime.Parse(appointment["scheduledend"].ToString()); } var data = UpdateTaskInOutlook(updateAppointment, serviceUrl); } }
public CustomerScreenPlugin() { var screenHelper = new ScreenHelper(); if (!screenHelper.IsSecondMonitorExists) { PluginContext.Shutdown("Can't show customer screen. There is no second monitor."); return; } try { CustomerScreenConfig.Init(PluginContext.Integration.GetConfigsDirectoryPath()); InitializeUiDispatcher(PluginContext.Operations.GetHostTerminalCultureInfo()); CurrencySettings = PluginContext.Operations.GetHostRestaurant().Currency; Application.Current.Dispatcher.Invoke(() => { vmOrder = new Order(); unsubscribe.Add(PluginContext.Notifications.ScreenChanged .ObserveOn(DispatcherScheduler.Current) .Subscribe(OnScreenChanged)); unsubscribe.Add(PluginContext.Notifications .ChangeSumChanged.ObserveOn(DispatcherScheduler.Current) .Subscribe(OnChangeSumChanged)); unsubscribe.Add(PluginContext.Notifications.OrderChanged .ObserveOn(DispatcherScheduler.Current) .Where(e => Equals(vmOrder.OrderSource, e.Entity)) .Select(e => e.Entity) .Subscribe(vmOrder.Update)); unsubscribe.Add(PluginContext.Notifications.RestaurantChanged .ObserveOn(DispatcherScheduler.Current) .Subscribe(r => OnRestaurantChanged(r.Currency))); ShowCustomerScreen(screenHelper); }); } catch { Dispose(); throw; } }
public override void Execute(TriggerBase trigger) { PluginContext[] plugins = Singleton <PluginManager> .Instance.GetPlugins(); if (plugins.Length == 0) { trigger.Reply("No plugin loaded"); } PluginContext[] array = plugins; for (int i = 0; i < array.Length; i++) { PluginContext pluginContext = array[i]; trigger.Reply("- {0} : {1}", new object[] { pluginContext.Plugin.Name, pluginContext.Plugin.Description }); } }
public void ManageStackTraces(Command command) { var stackTrace = GetStackTrace(command); if (stackTrace == null) { return; } stackTrace.ApplicationIdentity = command.ApplicationIdentity; if (stackTrace.ApplicationIdentity.Equals(GuiModelData.SelectedApplicationIdentity)) { GuiModelData.RelatedStackTraces.Add(stackTrace); } _localCallingMethodStackTraces.Add(stackTrace); PluginContext.NotifyPluginsHost(NotificationType.Update, 1); UpdateAppIdentityNotificationsCount(stackTrace.ApplicationIdentity); }
public override void Start(PluginContext pluginContext) { Context = pluginContext; YibaoSetting = pluginContext.GetSetting <YibaoSetting>(); // 注册 webapi pluginContext.Container.Resolve <IWebComponentService>().Register <YiBaoController>(pluginContext); pluginContext.Container.Resolve <IWebComponentService>().Register <WisdomController>(pluginContext); // 注册 配置 pluginContext.Container.Resolve <IUserSettingComponentService>().RegisterSetting <YibaoSetting>(pluginContext, (o) => { var setting = (YibaoSetting)o; YibaoSetting = setting; YiBaoController.CreateService(setting); Context.Logger.Info($"{{cookiecutter.display_name}}医保配置更新: " + Newtonsoft.Json.JsonConvert.SerializeObject(setting)); }); }
protected override void ExecuteBusinessLogic(PluginContext pluginContext) { var task = pluginContext.TargetImageEntity; if (task == null) { return; } TaskEntity updateTask = new TaskEntity(); Entity oldTask = pluginContext.OrganizationService.Retrieve("task", task.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true)); if (oldTask == null) { throw new InvalidPluginExecutionException("Error then try get old task data"); } updateTask.CrmId = task.Id; updateTask.Subject = oldTask["subject"].ToString(); updateTask.Body = oldTask["description"].ToString(); updateTask.DuoDate = DateTime.Parse(oldTask["scheduledend"].ToString()); updateTask.NewTaskOwnerId = Guid.Empty; //updateTask.OwnerId = pluginContext.UserId; if (task.Contains("subject")) { updateTask.Subject = task["subject"].ToString(); } if (task.Contains("description")) { updateTask.Body = task["description"].ToString(); } if (task.Contains("scheduledend")) { updateTask.DuoDate = DateTime.Parse(task["scheduledend"].ToString()); } if (task.Contains("ownerid")) { updateTask.NewTaskOwnerId = ((EntityReference)task["ownerid"]).Id; } UpdateTaskInOutlook(updateTask, serviceUrl); }
public override void Execute(TriggerBase trigger) { PluginContext plugin = Singleton <PluginManager> .Instance.GetPlugin(trigger.Get <string>("name"), trigger.Get <bool>("case")); if (plugin == null) { trigger.ReplyError("Plugin not found"); } else { trigger.Reply("Plugin {0} v.{1} from {2} : {3}", new object[] { plugin.Plugin.Name, plugin.Plugin.Version, plugin.Plugin.Author, plugin.Plugin.Description }); } }
private void CommandResults_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (CommandResult item in e.NewItems) { if (item.CommandId != null && item.RowsReturned != null) { AddDataPoint(item.ApplicationIdentity, item.CommandId.Value, item.RowsReturned.Value); PluginContext.NotifyPluginsHost(NotificationType.Update, 1); CallbacksManagerBase.UpdateAppIdentityNotificationsCount(item); } } break; } }
public static IObservable <Thickness <Points> > GetThickness(this PluginContext context, IObservable <object> observableUnoObject, string property) { return(context.ObservePerFrame(observableUnoObject, obj => { var vector = context.Reflection.GetPropertyValue(obj, property) as dynamic; float l = vector.X; float t = vector.Y; float r = vector.Z; float b = vector.W; return Thickness.Create <Points>(l, t, r, b); }) .Catch((Exception e) => { Console.WriteLine(e); return Observable.Return(Thickness.Create <Points>(0, 0, 0, 0)); }) .DistinctUntilChanged() .Replay(1).RefCount()); }
public void ConvertsIISLogs() { var logs = new string[] { "2017-05-31 06:00:30 W3SVC1 EC2AMAZ-HCNHA1G 10.10.10.10 POST /DoWork - 443 EXAMPLE\\jonsmith 11.11.11.11 HTTP/1.1 SEA-HDFEHW23455/1.0.9/jonsmith - - localhost 500 2 0 1950 348 158", "2017-05-31 06:00:30 W3SVC1 EC2AMAZ-HCNHA1G ::1 GET / - 80 - ::1 HTTP/1.1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko - - localhost 200 0 0 950 348 128", "2017-05-31 06:00:30 W3SVC1 EC2AMAZ-HCNHA1G ::1 GET / - 80 - ::1 HTTP/1.1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko - - localhost 401 1 0 50 348 150", "2017-05-31 06:00:30 W3SVC1 EC2AMAZ-HCNHA1G ::1 GET / - 80 - ::1 HTTP/1.1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko - - localhost 503 7 0 550 348 192", "2017-05-31 06:00:30 W3SVC1 EC2AMAZ-HCNHA1G ::1 GET /iisstart.png - 80 - ::1 HTTP/1.1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko - http://localhost/ localhost 200 0 0 99960 317 3" }; var config = TestUtility.GetConfig("Pipes", "IISEMFTestPipe"); var context = new PluginContext(config, NullLogger.Instance, null); var sink = new MockEventSink(context); context.ContextData[PluginContext.SINK_TYPE] = sink.GetType(); var pipe = new EMFPipe <IDictionary <string, string> >(context); pipe.Subscribe(sink); var records = ParseW3SVCLogs(logs); foreach (var record in records) { pipe.OnNext(new Envelope <IDictionary <string, string> >(record)); } Assert.Equal(5, sink.Records.Count); var jo = JObject.Parse(sink.Records.First()); Assert.Equal("10.10.10.10", jo["s-ip"].ToString()); Assert.Equal("POST", jo["cs-method"].ToString()); Assert.Equal("/DoWork", jo["cs-uri-stem"].ToString()); Assert.Equal("443", jo["s-port"].ToString()); Assert.Equal("11.11.11.11", jo["c-ip"].ToString()); Assert.Equal(@"EXAMPLE\jonsmith", jo["cs-username"].ToString()); Assert.Equal(@"SEA-HDFEHW23455/1.0.9/jonsmith", jo["cs-User-Agent"].ToString()); Assert.Equal("500", jo["sc-status"].ToString()); Assert.Equal("2", jo["sc-substatus"].ToString()); Assert.Equal("IISNamespace", jo["_aws"]["CloudWatchMetrics"][0]["Namespace"].ToString()); Assert.Equal("time-taken", jo["_aws"]["CloudWatchMetrics"][0]["Metrics"][0]["Name"].ToString()); }
static void LoadPlugins(PluginContextProvider provider) { var asmList = PluginManager.GetPluginFiles().Select(asmFile => { try { var asmName = AssemblyName.GetAssemblyName(asmFile); return(Assembly.Load(asmName)); } catch (Exception ex) { return(null); } }).OfType <Assembly>().ToList(); var context = new PluginContext(provider); asmList.SelectMany(asm => PluginManager.LoadPlugin(asm, context)).ToList(); }
public DebuggerWindow(PluginContext context, String hackPath) { this.InitializeComponent(); Trace.Listeners.Add(this.listener); var compilerSettings = new CompilerSettings { Unsafe = true, }; compilerSettings.AssemblyReferences.Add("System.dll"); compilerSettings.AssemblyReferences.Add("System.Core.dll"); compilerSettings.AssemblyReferences.Add(typeof(MessageBox).Assembly.CodeBase); // PresentationFramework.dll compilerSettings.AssemblyReferences.Add(Path.Combine(hackPath, "SharpCraft.dll")); var compilerContext = new CompilerContext(compilerSettings, new DebuggerReportPrinter()); evaluator = new Evaluator(compilerContext); evaluator.Compile("using System;"); evaluator.Compile("using TinkerWorX.SharpCraft;"); CompositionTarget.Rendering += CompositionTarget_Rendering; }
public override Control AddTo(Control container, PluginContext context) { if(!ActiveFor(container, context.State)) return null; if (context.Selected == null) return null; if (context.Selected.VersionOf.HasValue) return null; IEngine engine = Context.Current; ContentItem latestVersion = engine.Resolve<IVersionManager>().GetVersionsOf(context.Selected, 1)[0]; if (latestVersion == context.Selected) return null; Url versionPreviewUrl = engine.GetContentAdapter<NodeAdapter>(latestVersion).GetPreviewUrl(latestVersion); versionPreviewUrl = versionPreviewUrl.AppendQuery("preview", latestVersion.ID); versionPreviewUrl = versionPreviewUrl.AppendQuery("original", context.Selected.ID); versionPreviewUrl = versionPreviewUrl.AppendQuery("returnUrl=" + engine.GetContentAdapter<NodeAdapter>(context.Selected).GetPreviewUrl(context.Selected)); HyperLink hl = new HyperLink(); hl.NavigateUrl = versionPreviewUrl; hl.Text = GetInnerHtml(context, IconUrl, ToolTip, Title); hl.CssClass = "preview"; hl.ToolTip = Utility.GetResourceString(GlobalResourceClassName, Name + ".ToolTip") ?? context.Format(ToolTip, false); container.Controls.Add(hl); return hl; }
public void Run(RemoteHooking.IContext hookingContext, PluginContext context, Boolean isDebugging, String hackPath, String installPath) { try { if (isDebugging) { DebuggerApplication.Start(context, hackPath); while (!DebuggerApplication.IsReady) Thread.Sleep(1); // Sleep(0) is a nono. } Trace.IndentSize = 2; // We autoflush our trace, so we get everything immediately. This // makes tracing a bit more expensive, but means we still get a log // even if there's a fatal crash. Trace.AutoFlush = true; // Everything traced will be written to "debug.log". Trace.Listeners.Add(new TextWriterTraceListener(Path.Combine(hackPath, "debug.log"))); Trace.WriteLine("-------------------"); Trace.WriteLine(DateTime.Now); Trace.WriteLine("-------------------"); AppDomain.CurrentDomain.AssemblyResolve += (Object sender, ResolveEventArgs args) => { var path = String.Empty; // extract the file name var file = String.Empty; if (args.Name.IndexOf(',') >= 0) file = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll"; else if (args.Name.IndexOf(".dll") >= 0) file = Path.GetFileName(args.Name); else return null; // locate the actual file path = Directory.GetFiles(hackPath, file, SearchOption.AllDirectories).FirstOrDefault(); if (!String.IsNullOrEmpty(path)) return Assembly.LoadFrom(path); path = Directory.GetFiles(pluginsFolder, file, SearchOption.AllDirectories).FirstOrDefault(); if (!String.IsNullOrEmpty(path)) return Assembly.LoadFrom(path); return null; }; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (Object sender, ResolveEventArgs args) => { var path = String.Empty; // extract the file name var file = String.Empty; if (args.Name.IndexOf(',') >= 0) file = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll"; else if (args.Name.IndexOf(".dll") >= 0) file = Path.GetFileName(args.Name); else return null; // locate the actual file path = Directory.GetFiles(hackPath, file, SearchOption.AllDirectories).FirstOrDefault(); if (!String.IsNullOrEmpty(path)) return Assembly.ReflectionOnlyLoadFrom(path); path = Directory.GetFiles(pluginsFolder, file, SearchOption.AllDirectories).FirstOrDefault(); if (!String.IsNullOrEmpty(path)) return Assembly.ReflectionOnlyLoadFrom(path); return null; }; var sw = new Stopwatch(); Trace.WriteLine("Preparing folders . . . "); Trace.Indent(); sw.Restart(); this.pluginsFolder = Path.Combine(hackPath, "plugins"); if (!Directory.Exists(this.pluginsFolder)) Directory.CreateDirectory(this.pluginsFolder); sw.Stop(); Trace.WriteLine("Install Path: " + installPath); Trace.WriteLine("Hack Path: " + hackPath); if (installPath.Equals(hackPath, StringComparison.OrdinalIgnoreCase)) Trace.WriteLine("WARNING: Install Path and Hack Path are the same. This is not supported."); if (File.Exists(Path.Combine(installPath, "Launcher.exe"))) Trace.WriteLine("WARNING: Launcher.exe detected in the Warcraft III folder. This is not supported."); if (File.Exists(Path.Combine(installPath, "SharpCraft.dll"))) Trace.WriteLine("WARNING: SharpCraft.dll detected in the Warcraft III folder. This is not supported."); Trace.WriteLine("Done! (" + sw.Elapsed.TotalMilliseconds.ToString("0.00") + " ms)"); Trace.Unindent(); Trace.WriteLine("Loading plugins from '" + this.pluginsFolder + "' . . ."); Trace.Indent(); sw.Restart(); PluginSystem.LoadPlugins(pluginsFolder, this.context); sw.Stop(); Trace.WriteLine("Done! (" + sw.Elapsed.TotalMilliseconds.ToString("0.00") + " ms)"); Trace.Unindent(); // Prepare the OnGameLoad hook. this.LoadLibraryA = Memory.InstallHook(LocalHook.GetProcAddress("kernel32.dll", "LoadLibraryA"), new Kernel32.LoadLibraryAPrototype(this.LoadLibraryAHook), false, true); // Everyone has had their chance to inject stuff, // time to wake up the process. RemoteHooking.WakeUpProcess(); // Let the thread stay alive, so all hooks stay alive as well. // This might need to be shutdown properly on exit. Thread.Sleep(Timeout.Infinite); } catch (Exception exception) { MessageBox.Show( "Fatal exception!" + Environment.NewLine + exception + Environment.NewLine + "Aborting execution!", this.GetType() + ".Run(...)", MessageBoxButton.OK, MessageBoxImage.Error); Process.GetCurrentProcess().Kill(); } }
public FMGPluginMenuGenerator( PluginContext pluginContext ) { _pluginContext = pluginContext; }
public PluginWebFormView(PluginContext pluginContext, string viewPath) : this(pluginContext, viewPath, null) { }
public void OnEnable(PluginContext context) { Context = context; OnEnable(); }
public void Stop(PluginContext pluginContext) { throw new System.NotImplementedException(); }
public abstract void Execute(PluginContext context);
public void Initialize(PluginContext pluginContext) { pluginContext.AddPlugin<GlobalPluginMapperController, CurrentUserDetailsControllerPlugin>(); }
public virtual void Initialize(PluginContext context) { }
public virtual void OnGameLoad(PluginContext context) { }
public void Initialize(PluginContext pluginContext) { pluginContext.AddPlugin<NewRequestsController, CurrentAppraiserDetailsControllerPlugin>(); }
public void Register(PluginContext context) { throw new NotImplementedException(); }
/// <summary> /// When a plugin item is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void pluginItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; IPlugin plugin = (IPlugin)item.Tag; PluginContext context = new PluginContext(); // OPTIONAL: add context options here: plugin.PerformAction(context); }