public ActionResult Gets(string cmd)
        {
            cmd = $"./Scripts/iicDriver.sh {cmd}";
            var result = new ScriptService().Bash(cmd);

            return(Ok(result));
        }
예제 #2
0
        static MscClient()
        {
            DefaultResourceLocator.AddManifestResourceLoader(ManifestResourceLoader.GetResourceLoader(typeof(ClientResourceLocator).Assembly, "theori.Resources"));
            DefaultResourceLocator.AddManifestResourceLoader(ManifestResourceLoader.GetResourceLoader(typeof(MscClient).Assembly, "Museclone.Resources"));

            ScriptService.RegisterType <Highway>();
        }
예제 #3
0
        public void Given_service_set_When_adding_description_for_existing_services_When_can_get_it_back()
        {
            var set           = new ScriptServiceSet();
            var service       = new object();
            var scriptService = new ScriptService()
            {
                Name = "Test service", Version = 1
            };
            var scriptServiceSchema = new ScriptServiceSchema()
            {
                AccessName = "test",
                Language   = Language.JavaScriptEs5
            };

            set.Add(scriptService, service, scriptServiceSchema);

            IReadOnlyCollection <ScriptServiceSchema>?resolvedSchema = null;
            object?resolvedService = null;

            set.Inject((sc, s) =>
            {
                resolvedSchema  = sc;
                resolvedService = s;
            }, scriptService);

            resolvedService.Should().Be(service);
            resolvedSchema.Should().BeEquivalentTo(scriptServiceSchema);
        }
예제 #4
0
        public static void Run(string variableName)
        {
            NWObject self   = (NWGameObject.OBJECT_SELF);
            string   script = self.GetLocalString(variableName);

            using (new Profiler("ScriptEvent." + script))
            {
                string rootNamespace   = Assembly.GetExecutingAssembly().GetName().Name;
                string scriptNamespace = rootNamespace + ".Scripts." + script;

                // Check the script cache first. If it exists, we run it.
                if (ScriptService.IsScriptRegisteredByNamespace(scriptNamespace))
                {
                    ScriptService.RunScriptByNamespace(scriptNamespace);
                    return;
                }

                // Otherwise look for a script contained by the app.
                scriptNamespace = rootNamespace + "." + script;
                Type type = Type.GetType(scriptNamespace);

                if (type == null)
                {
                    Console.WriteLine("Unable to locate type for ScriptEvent: " + script);
                    return;
                }

                IRegisteredEvent @event = Activator.CreateInstance(type) as IRegisteredEvent;
                @event?.Run();
            }
        }
예제 #5
0
        public void SaveScripts_Test()
        {
            //Arrange
            var stubFactory  = new Mock <IPrompterDbContextFactory>();
            var dummyContext = new Mock <IPrompterDbContext>();

            stubFactory.Setup(f => f.Create())
            .Returns(dummyContext.Object);

            var dummyScripts = new List <Script>
            {
                new Script(),
                new Script()
            };

            //Act
            var service = new ScriptService(stubFactory.Object);

            service.SaveScripts(dummyScripts);

            //Assert
            stubFactory.Verify(f => f.Create(), Times.Exactly(1));

            dummyContext.Verify(c => c.Attach(dummyScripts[0])
                                , Times.Exactly(1));
            dummyContext.Verify(c => c.Attach(dummyScripts[1])
                                , Times.Exactly(1));
            dummyContext.Verify(c => c.SaveChanges()
                                , Times.Exactly(1));
        }
        public void ServiceMustGet()
        {
            var service = new ScriptService(this.context);
            var result  = service.Get();

            Assert.NotNull(result);
        }
        /// <summary>
        /// Authenticates user and then initializes important classes for using the Google API.
        /// Asynchonosly authorizes credentials, allocating 20 seconds before cancelling.
        /// If successful, then uses credentials to create ScriptService and ProjectsResource
        /// </summary>
        /// <exception cref="InfoException"></exception>
        /// <exception cref="Exception"></exception>
        private static async Task <string> initUser()
        {
            var cts = new CancellationTokenSource(waitTime);

            cts.Token.Register(() => Debug.WriteLine("Cancellation token invoked due to taking too long!"));

            Task <UserCredential> auth;
            Task delay;

            try
            {
                using (var stream = assembly.GetManifestResourceStream("AppScriptManager.credentials.json"))
                {
                    auth = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        scopes,
                        "user",
                        cts.Token,
                        new FileDataStore(credPath, true)
                        );
                }
            }
            catch (Exception)
            {
                throw;
            }

            delay = Task.Delay(waitTime, cts.Token);

            if (await Task.WhenAny(auth, delay).ConfigureAwait(true) == auth)
            {
                credential = await auth;
                cts.Dispose();
                if (credential != null)
                {
                    scriptService = new ScriptService(new BaseClientService.Initializer()
                    {
                        ApiKey = apiKeyUser,
                        HttpClientInitializer = credential,
                        ApplicationName       = applicationName
                    });

                    Debug.WriteLine("Credential file saved to: " + credPath);
                    CredentialsPath = Directory.GetCurrentDirectory() + "\\" + credPath;

                    projectResource = new ProjectsResource(scriptService);

                    return("User Authorization Succeeded!");
                }
                else
                {
                    throw new InfoException("Credentials failed!");
                }
            }
            else
            {
                cts.Cancel(); //only cancel if failure occured
                throw new InfoException("User Authorization Failed due to taking too long!");
            }
        }
예제 #8
0
        private void Initialize(string url)
        {
            _serializerSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Converters        = new JsonConverter[]
                {
                    new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter(),
                    new MaintenanceJsonConverter()
                }
            };

            Check.IsNotNullOrWhiteSpace(url, "ZabbixApi.url");

            _url        = url;
            _webClient  = new WebClient();
            _httpClient = new HttpClient();

            Actions            = new ActionService(this);
            Alerts             = new AlertService(this);
            ApiInfo            = new ApiInfoService(this);
            Applications       = new ApplicationService(this);
            Correlations       = new CorrelationService(this);
            DiscoveredHosts    = new DiscoveredHostService(this);
            DiscoveredServices = new DiscoveredServiceService(this);
            DiscoveryChecks    = new DiscoveryCheckService(this);
            DiscoveryRules     = new DiscoveryRuleService(this);
            Events             = new EventService(this);
            GraphItems         = new GraphItemService(this);
            GraphPrototypes    = new GraphPrototypeService(this);
            Graphs             = new GraphService(this);
            History            = new HistoryService(this);
            HostGroups         = new HostGroupService(this);
            HostInterfaces     = new HostInterfaceService(this);
            HostPrototypes     = new HostPrototypeService(this);
            Hosts               = new HostService(this);
            IconMaps            = new IconMapService(this);
            ServiceService      = new ServiceService(this);
            Images              = new ImageService(this);
            ItemPrototypes      = new ItemPrototypeService(this);
            Items               = new ItemService(this);
            LLDRules            = new LLDRuleService(this);
            Maintenance         = new MaintenanceService(this);
            Maps                = new MapService(this);
            MediaTypes          = new MediaTypeService(this);
            Proxies             = new ProxyService(this);
            ScreenItems         = new ScreenItemService(this);
            Screens             = new ScreenService(this);
            Scripts             = new ScriptService(this);
            TemplateScreenItems = new TemplateScreenItemService(this);
            TemplateScreens     = new TemplateScreenService(this);
            Templates           = new TemplateService(this);
            TriggerPrototypes   = new TriggerPrototypeService(this);
            Triggers            = new TriggerService(this);
            UserGroups          = new UserGroupService(this);
            GlobalMacros        = new GlobalMacroService(this);
            HostMacros          = new HostMacroService(this);
            Users               = new UserService(this);
            ValueMaps           = new ValueMapService(this);
        }
 public Click2CallScriptProcessor(ScriptService scriptService, string numberToDial, WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow callMakerExtension, TelecomScriptInterface callMakerInterface)
 {
     this.callMakerExtension = callMakerExtension;
     this.scriptService      = scriptService;
     this.numberToDial       = numberToDial;
     this.callMakerInterface = callMakerInterface;
 }
예제 #10
0
        public static void Run(string script)
        {
            if (!script.StartsWith("Item."))
            {
                script = "Item." + script;
            }

            using (new Profiler(nameof(ScriptEvent) + "." + script))
            {
                string rootNamespace   = Assembly.GetExecutingAssembly().GetName().Name;
                string scriptNamespace = rootNamespace + ".Scripts." + script;

                // Check the script cache first. If it exists, we run it.
                if (ScriptService.IsScriptRegisteredByNamespace(scriptNamespace))
                {
                    ScriptService.RunScriptByNamespace(scriptNamespace);
                    return;
                }

                // Otherwise look for a script contained by the app.
                scriptNamespace = rootNamespace + "." + script;
                Type type = Type.GetType(scriptNamespace);

                if (type == null)
                {
                    Console.WriteLine("Unable to locate type for ScriptItemEvent: " + script);
                    return;
                }

                IRegisteredEvent @event = Activator.CreateInstance(type) as IRegisteredEvent;
                @event?.Run();
            }
        }
예제 #11
0
        public MainViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _eventAggregator.GetEvent <ScriptInfoAddedEvent>().Subscribe(OnScriptInfoAdded);
            _eventAggregator.GetEvent <ScriptInfoChangedEvent>().Subscribe((scriptInfo) => ScriptInfo = scriptInfo);
            _eventAggregator.GetEvent <SettingsChangedEvent>().Subscribe((settings) => LoadSettings(settings));

            // Disable global hotkeys while user is changing hotkey
            _eventAggregator.GetEvent <SettingsWindowOpenEvent>().Subscribe(
                () => _winService.GlobalKeyDown -= OnGlobalHotkeyDown);
            _eventAggregator.GetEvent <SettingsWindowClosedEvent>().Subscribe(
                () => _winService.GlobalKeyDown += OnGlobalHotkeyDown);

            _settingsAccess = new SettingsAccess();
            _scriptAccess   = new ScriptAccess();

            _dialogService = new DialogService();
            _scriptService = new ScriptService();

            _winService = new WinService();
            _winService.GlobalKeyDown += OnGlobalHotkeyDown;
            _winService.GlobalKeyUp   += OnGlobalHotkeyUp;

            _automationService = new AutomationService();
            _automationService.RemoveFileModificationDetectedDialogOnCreated();

            _settings = _settingsAccess.LoadSettings();

            FormViewModel = new ScriptInfoViewModel(eventAggregator, SaveScriptInfoAction);

            LoadCommands();
            LoadSettings(_settings, firstTime: true);
            ScriptNames = _scriptAccess.GetScriptNames();
        }
예제 #12
0
        public async Task ApplyAsync_Query_Should_Filter_Results_Correctly_When_Invoked()
        {
            // Arrange
            var query        = "MOCK-QUERY";
            var listToSearch = new List <MockObject>()
            {
                new MockObject()
                {
                    Num = 1
                },
                new MockObject()
                {
                    Num = 2
                },
                new MockObject()
                {
                    Num = 3
                }
            };

            ParserService.Setup(x => x.ToSearchModel(query));
            ScriptService.Setup(x =>
                                x.EvaluateAsync <Func <MockObject, bool> >(It.IsAny <string>(), null, null, default(CancellationToken)))
            .ReturnsAsync(obj => obj.Num < 3);

            // Act
            var sut     = CreateSut();
            var results = await sut.ApplyAsync(query, listToSearch);

            // Assert
            Assert.Equal(2, results.Count());
        }
예제 #13
0
 public SchedulesController()
 {
     _projectService  = new ProjectService(new GhostRunnerContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString));
     _scheduleService = new ScheduleService(new GhostRunnerContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString));
     _sequenceService = new SequenceService(new GhostRunnerContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString));
     _scriptService   = new ScriptService(new GhostRunnerContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString));
 }
예제 #14
0
        private ScriptService CreateScriptService(GoogleAuthDTO authDTO)
        {
            var           flowData      = _googleAuth.CreateFlowMetadata(authDTO, "", CloudConfigurationManager.GetSetting("GoogleRedirectUri"));
            TokenResponse tokenResponse = new TokenResponse();

            tokenResponse.AccessToken  = authDTO.AccessToken;
            tokenResponse.RefreshToken = authDTO.RefreshToken;
            tokenResponse.Scope        = CloudConfigurationManager.GetSetting("GoogleScope");

            UserCredential userCredential;

            try
            {
                userCredential = new UserCredential(flowData.Flow, authDTO.AccessToken, tokenResponse);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            // Create Script API service.
            ScriptService driveService = new ScriptService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = userCredential,
                ApplicationName       = "Fr8",
            });

            return(driveService);
        }
예제 #15
0
        /// <summary>
        /// Runs a function in an Apps Script project. The project must be deployedfor use with the Apps Script Execution API.This method requires authorization with an OAuth 2.0 token that includes atleast one of the scopes listed in the [Authorization](#authorization)section; script projects that do not require authorization cannot beexecuted through this API. To find the correct scopes to include in theauthentication token, open the project in the script editor, then select**File > Project properties** and click the **Scopes** tab.
        /// Documentation https://developers.google.com/script/v1/reference/scripts/run
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Script service.</param>
        /// <param name="scriptId">The script ID of the script to be executed. To find the script ID, openthe project in the script editor and select **File > Project properties**.</param>
        /// <param name="body">A valid Script v1 body.</param>
        /// <returns>OperationResponse</returns>
        public static Operation Run(ScriptService service, string scriptId, ExecutionRequest body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (scriptId == null)
                {
                    throw new ArgumentNullException(scriptId);
                }

                // Make the request.
                return(service.Scripts.Run(body, scriptId).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Scripts.Run failed.", ex);
            }
        }
예제 #16
0
        public virtual void Initialize(string title = ":theori")
        {
            using var _            = Profiler.Scope("ClientHost::Initialize");
            GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;

            IsFirstLaunch = LoadConfig();

            Window.Create(this, title);
            Window.VSync              = TheoriConfig.VerticalSync;
            Window.ClientSizeChanged += Window_ClientSizeChanged;

            Mixer.Initialize(new AudioFormat(48000, 2));

            ScriptService.RegisterTheoriClrTypes();

            Logger.Log($"Window VSync: { Window.VSync }");

            UserInputService.RawKeyPressed += (keyInfo) =>
            {
                if (keyInfo.KeyCode == KeyCode.F11)
                {
                    m_updateQueue.Enqueue(() =>
                    {
                        Profiler.IsEnabled = true;
                        Profiler.BeginSession("Single Frame Session");
                    });
                }
            };
        }
예제 #17
0
        public void Step()
        {
            int row = StatementsGrid.Selection?.Row ?? -1;

            if (row != -1)
            {
                Logger.Info($"{nameof(Step)}");
                try
                {
                    var stmt    = Statements[row];
                    var command = ScriptService.BuildCommand(stmt);
                    var result  = command.Execute(NatsService, ExecutorService);
                    Logger.Info($"Success ! {result}");
                    Result      = result;
                    ResultClass = "d-block";
                    InvokeAsync(StateHasChanged);
                }
                catch (Exception e)
                {
                    Result      = $"Command failed ! {e.Message}";
                    ResultClass = "d-block";
                    InvokeAsync(StateHasChanged);
                    Logger.Error(Result);
                }
            }
            GoNext();
        }
예제 #18
0
 protected void NewScript()
 {
     Logger.Info("New Script.");
     ScriptService.SetCurrent(new Script());
     Init();
     InvokeAsync(StateHasChanged);
 }
예제 #19
0
        public void FetchAllScripts_Test()
        {
            //Arange
            var stubFactory = new Mock <IPrompterDbContextFactory>();
            var stubContext = new Mock <IPrompterDbContext>();
            var scriptDbSet = new Mock <IDbSet <Script> >();

            var script = new Script
            {
                ScriptId  = 1,
                Title     = "test",
                OptionsId = 1,
                Sections  = new List <Section>
                {
                    new Section
                    {
                        Order = 2,
                    },
                    new Section
                    {
                        Order = 1,
                    }
                }
            };

            var fakeScripts = new List <Script>
            {
                script,
                new Script
                {
                    Sections = new List <Section>()
                }
            }.AsQueryable();

            stubFactory.Setup(s => s.Create())
            .Returns(stubContext.Object);

            scriptDbSet.Setup(s => s.Provider)
            .Returns(fakeScripts.Provider);
            scriptDbSet.Setup(s => s.Expression)
            .Returns(fakeScripts.Expression);
            scriptDbSet.Setup(s => s.GetEnumerator())
            .Returns(fakeScripts.GetEnumerator());

            stubContext.Setup(s => s.Scripts)
            .Returns(scriptDbSet.Object);

            var service = new ScriptService(stubFactory.Object);

            //Act
            var actual = service.FetchAllScripts();

            //Assert
            Assert.That(actual.Count, Is.EqualTo(2));
            Assert.That(actual.Contains(script));
            Assert.That(SectionsAreOrdered(actual[0]), Is.True);
            Assert.That(actual[0].Title == "test");
            stubContext.Verify(s => s.Scripts, Times.Once);
        }
예제 #20
0
 public void SetScriptService(UserCredential credential)
 {
     ScriptService = new ScriptService(new BaseClientService.Initializer
     {
         HttpClientInitializer = credential,
         ApplicationName       = "ASP.NET MVC Sample"
     });
 }
예제 #21
0
 public Toolbar CreateToolbar(string name)
 {
     ScriptService.AssertIdentity(ScriptIdentity.Plugin);
     return(new Toolbar(name)
     {
         Parent = this, ParentLocked = true
     });
 }
예제 #22
0
 public Widget CreateWidget(string name)
 {
     ScriptService.AssertIdentity(ScriptIdentity.Plugin);
     return(new Widget(name)
     {
         Parent = this, ParentLocked = true
     });
 }
예제 #23
0
 public void SetTrackingId(string trackingId)
 {
     ScriptService.AssertIdentity(ScriptIdentity.Editor | ScriptIdentity.CoreScript);
     if (!trackingId.StartsWith("UA-"))
     {
         throw new FormatException("Tracking ID was not a valid Google Analytics ID.");
     }
 }
예제 #24
0
 public void SetActive(bool active)
 {
     ScriptService.AssertIdentity(ScriptIdentity.Plugin);
     Editor.Current.Dispatcher.InvokeAsync(() =>
     {
         IsChecked = active;
     });
 }
예제 #25
0
 public static ScriptService ScriptServiceInstance()
 {
     if (ss == null)
     {
         ss = new ScriptService();
     }
     return(ss);
 }
예제 #26
0
        public override void Execute(object parameter)
        {
            var typeName = (string)parameter;
            var sel      = SelectionService.First(x => x is Model);
            var parent   = sel ?? Game.Workspace;

            ScriptService.NewInstance(typeName, parent);
        }
예제 #27
0
 public Button CreateButton(string text, string tooltip, string iconName)
 {
     ScriptService.AssertIdentity(ScriptIdentity.Plugin);
     return(new Button(text, tooltip, iconName, this)
     {
         Parent = this, ParentLocked = true
     });
 }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AspNetTimer.Start();

            ScriptService.Init();
            EmailHtmlLoader.Init();
        }
예제 #29
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ScriptService.Init();
        }
예제 #30
0
 private IEnumerable <IScriptCommand> BuildCommands(List <IScriptCommand> commands)
 {
     foreach (var command in commands)
     {
         yield return(ScriptService.BuildCommand(new ScriptStatement {
             Name = command.Name, Param1 = command.Param1, Param2 = command.Param2
         }));
     }
 }
예제 #31
0
        /// <summary>
        /// Preparing to call the API service.
        /// </summary>
        /// <returns>The Operation representing the API call</returns>
        private async Task<Operation> ExecuteOperaionAsync()
        {
            var service = new ScriptService(new BaseClientService.Initializer
            {
                HttpClientInitializer = _credential,
                ApplicationName = _appName
            });

            var request = new ExecutionRequest
            {
                Function = _funcName,
                //DevMode = Debugger.IsAttached,
                Parameters = this.Parameters
            };

            ScriptsResource.RunRequest runReq = service.Scripts.Run(request, _projectKey);

            return await runReq.ExecuteAsync().ConfigureAwait(false);
        }