public void Run(IJob obj, HandlerOptions handler) { Console.WriteLine($"服务{handler.ActionName}已经启动"); Action <Schedule> runSchedule = new Action <Schedule>(r => r.WithName(handler.ActionName).NonReentrant().ToRunNow().AndEvery(handler.Times).Seconds()); JobManager.AddJob(obj, runSchedule); }
internal void Register() { HandlerOptions internalOption = new HandlerOptions() { SkipRequestFilters = true }; Handle.POST("/signin/partial/signin", (Request request) => { NameValueCollection values = HttpUtility.ParseQueryString(request.Body); string username = values["username"]; string password = values["password"]; string rememberMe = values["rememberMe"]; HandleSignIn(username, password, rememberMe); Session.Current?.CalculatePatchAndPushOnWebSocket(); return(200); }, internalOption); Handle.GET("/signin/partial/signin-form", (Request request) => { return(new SignInFormPage() { Data = null, CanCreateAdminUser = SystemAdminUser.GetCanCreateAdminUser(request.ClientIpAddress) }); }, internalOption); Handle.GET("/signin/partial/createadminuser", (Request request) => { return(new CreateAdminUserViewModel() { Data = SystemAdminUser.Create(request.ClientIpAddress) }); }, new HandlerOptions() { SkipRequestFilters = true }); Handle.GET("/signin/partial/alreadyin-form", () => new AlreadyInPage() { Data = null }, internalOption); Handle.GET("/signin/partial/restore-form", () => new RestorePasswordFormPage(), internalOption); Handle.GET("/signin/partial/profile-form", () => new ProfileFormPage() { Data = null }, internalOption); Handle.GET("/signin/partial/accessdenied-form", () => new AccessDeniedPage(), internalOption); Handle.GET("/signin/partial/main-form", () => new MainFormPage() { Data = null }, internalOption); Handle.GET("/signin/partial/user/image", () => new UserImagePage()); Handle.GET("/signin/partial/user/image/{?}", (string objectId) => new Json(), internalOption); Handle.GET("/signin/partial/signout", HandleSignOut, internalOption); //Handle.GET("/signin/partial/usersignout", HandlePartialSignOut, internalOption); }
public HandlerResult Do(string fileName, HandlerOptions options) { return(new HandlerResult() { Value = "Test Value" }); }
private static void ProcessHandler(int userId) { //获取待处理的流程 DbContext dbcontext = new DbContext(); var lst = dbcontext.FlowInfo.Where(x => x.RowState == RowStates.正常) .Where(x => x.HandlerId == userId) .ToList(); if (lst.Count <= 0) { Console.WriteLine("没有待处理的流程"); return; } int indexTMP = 0; lst.ForEach(x => Console.WriteLine(string.Format("索引:{0},流程ID:{1},处理人ID:{2},处理人:{3},表单:{4}", indexTMP++, x.WFInstanceId, x.HandlerId, x.HandlerName, x.FlowContext))); Console.WriteLine("请输入流程索引"); int index = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("请输入审批意见"); Console.WriteLine(string.Format("{0}---{1}", (int)HandlerOptions.意, HandlerOptions.意.ToString())); Console.WriteLine(string.Format("{0}---{1}", (int)HandlerOptions.驳回, HandlerOptions.驳回.ToString())); HandlerOptions opt = (HandlerOptions)Convert.ToInt32(Console.ReadLine()); //组织表单数据 var formData = Newtonsoft.Json.Linq.JObject.Parse(lst[index].FlowContext); formData["HandlerOption"] = Newtonsoft.Json.Linq.JToken.FromObject(opt);//demo,这个键写死 //启动流程 System.Activities.WorkflowApplication wfa = new System.Activities.WorkflowApplication(new LeaveFlow()); InitWF(wfa); wfa.Load(lst[index].WFInstanceId); wfa.ResumeBookmark(lst[index].BookmarkName, formData); }
public void RunAction1(HandlerOptions handler) { string assemblyPath = AppContext.BaseDirectory + @"\Hyc.App.Actions.dll"; string Name = handler.Name; string asmName = handler.Handler; var asl = new AssemblyLoader(asmName); var asm = asl.LoadFromAssemblyPath(@assemblyPath); var type = asm.GetType(handler.Handler); dynamic obj = Activator.CreateInstance(type); obj.Execute(); }
public void GetModel_ExpectedModel_Model_Exists() { // Arrange var options = new HandlerOptions(); options.AddModel("test", typeof(MessageTest)); // Act var modelType = options.GetModel("test"); // Assert Assert.IsInstanceOfType(new MessageTest(), modelType); }
private void singletonInstance() { //Singleton instance if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(gameObject); } //Dont destroy on load to persevere this object in all scenes //DontDestroyOnLoad(gameObject); }
public WrapperProcess(HandlerOptions options) { Port = Helper.GetFreeTcpPort(); ID = IdGenerator.GetId(this, out _); _cts = new CancellationTokenSource(); _process = new Process { StartInfo = new ProcessStartInfo(_serviceOptions.DotnetPath) { Arguments = $"{_serviceOptions.WrapperPath} " + $"{nameof(WrapperProcessArgs.ServicePID)}={ServiceOptions.ServicePID} " + $"{nameof(WrapperProcessArgs.HandlerPort)}={Port} " + options, CreateNoWindow = true } }; }
/** * Method to check first time in the game, add basic config and show the panel * to enter the user's name. */ public void ShowNameMenu() { //TODO: need to change FIRSTIMEOPENING ¿User name in PlayerPrefs? if (PlayerPrefs.GetInt("FIRSTIMEOPENING", 1) == 1) { //Set first parameters HandlerOptions ho = HandlerOptions.Instance; ho.MusicOn = true; ho.MusicVolumen = 0.3f; ho.MusicEffectOn = true; ho.MusicEffectVolumen = 0.2f; ho.LanguageInt = 2; ho.CrossHairString = "white"; //Ask for name namePanel.SetActive(true); panelAnimator.SetTrigger("smallBox"); panelShadow.SetActive(true); PlayerPrefs.SetInt("FIRSTIMEOPENING", 0); } }
protected override async Task Init() { Log.Information("Starting initialization"); Start(_processArgs.HandlerPort); // In this case, the service will not be able to find this handler if (Port != _processArgs.HandlerPort) { throw new Exception("Cannot run on required TCP port"); } Log.Information("Listening on: {0}", Port); _waitForServiceDeath = Process.GetProcessById(_processArgs.ServicePID).WaitForExitAsync(); if (File.Exists(_processArgs.Schedule)) { string json = await File.ReadAllTextAsync(_processArgs.Schedule); _handlerOptions = JsonConvert.DeserializeObject <HandlerOptions>(json); Log.Information("Used schedule file: \"{0}\"", _processArgs.Schedule); } else { _handlerOptions = new HandlerOptions(); Log.Warning("Cannot load schedule file: \"{0}\"", _processArgs.Schedule); } await _handler.Init(_processArgs.HandlerPath, _handlerOptions.InitArgs); _schedulerSub = _scheduler.TickStream.Subscribe(x => _ = _handler.HandleSchedulerTick(x)); _scheduler.AddRange(_handlerOptions.Triggers.All); }
/// <summary> /// The LogStreamer sample application allows simple transaction log /// streaming between Starcounter databases. It accepts three kinds /// of command line parameters. /// /// An URI or file path ending with ".logstreamer.xml" is taken to be /// the source of a LogStreamer configuration to use. If it is a local /// file path, the file will be created if necessary. /// /// Any other string not starting with '@' will be taken as the /// upstream URI to use. Either or both of these parameters may be /// omitted. /// /// Parameters starting with '@' are documented in code, but should /// not be needed for general use. /// /// Usually when starting LogStreamer, you'll want to launch it into /// a specific database. If you prefer, you can do that from the /// command line using something like this: /// /// star.exe -d=DBNAME LogStreamer.exe /// /// </summary> /// <param name="args">Command line parameters.</param> static void Main(string[] args) { string upstreamUri = null; bool streamingEnabled = true; bool generateConfigFile = false; bool useFileLog = false; var options = new HandlerOptions() { SkipRequestFilters = true }; // Provide a host local handler for the default config. // Don't move this one - it must be present for the configuration loader // if default configuration is in effect. Handle.GET(DefaultRelativeUri, HandleGETDefaultConfigFile, options); // Provide a handler for some more throughout sample configuration Handle.GET(SampleRelativeUri, HandleGETSampleConfigFile, options); foreach (var arg in args) { if (arg == null || arg.Length < 1) continue; // If you pass .config.json, we take it. Otherwise, // we consider it the upstream URI if (arg[0] != '@') { if (arg.EndsWith(".config.json")) { _configUri = arg; } else { upstreamUri = arg; } } else if (arg.Equals("@disabled", StringComparison.CurrentCultureIgnoreCase) || arg.Equals("@paused", StringComparison.CurrentCultureIgnoreCase)) { streamingEnabled = false; } else if (arg.Equals("@enabled", StringComparison.CurrentCultureIgnoreCase)) { streamingEnabled = true; } else if (arg.Equals("@generate", StringComparison.CurrentCultureIgnoreCase)) { generateConfigFile = true; } else if (arg.Equals("@logfile", StringComparison.CurrentCultureIgnoreCase)) { useFileLog = true; } else { Console.WriteLine("Warning: Ignoring unrecognized argument '{0}'", arg); } } if (string.IsNullOrWhiteSpace(_configUri)) { // Apply the default URI, and then make sure the log streamer // is disabled until explicitly told otherwise string filePath = GetDefaultFilePath(); if (generateConfigFile || File.Exists(filePath)) { _configUri = "file://" + filePath; } else { _configUri = "http://localhost:" + StarcounterEnvironment.Default.UserHttpPort + DefaultRelativeUri; streamingEnabled = false; } } if (generateConfigFile) { if (!_configUri.Contains("://")) { _configUri = "file://" + _configUri; } if (_configUri.StartsWith("file://")) { var cfg = new Configuration(); cfg.ApplyDefaults(); if (!string.IsNullOrWhiteSpace(upstreamUri)) { cfg.UpstreamUri = LogStreamerConfiguration.CleanUri(upstreamUri); } File.WriteAllText(_configUri.Substring(7), ConfigToJson(cfg.ToConfiguration())); } else { Console.WriteLine("Can't generate config file for URI '{0}'", _configUri); } } _config = LogStreamerConfiguration.Load(_configUri, upstreamUri); Console.WriteLine( "Starting LogStreamer in {0}, OID range {1} - {2}. UpstreamUri: '{3}'.", Db.Environment.DatabaseName, Db.Environment.FirstUserOid, Db.Environment.LastUserOid, _config.UpstreamUri ?? "" ); // Ensure that the FirstUserOid and LastUserOid match what we actually have. if (_config.FirstUserOid != Db.Environment.FirstUserOid) { throw new ArgumentException("FirstUserOid mismatch: config " + _config.FirstUserOid + " != " + Db.Environment.FirstUserOid + " actual"); } if (_config.LastUserOid != Db.Environment.LastUserOid) { throw new ArgumentException("LastUserOid mismatch: config " + _config.LastUserOid + " != " + Db.Environment.LastUserOid + " actual"); } Handle.GET(BaseUri, HandleGETRoot); Handle.GET(BaseUri + "/log", HandleGETLog); Handle.GET(BaseUri + "/config", HandleGETConfig); Handle.GET<string>(BaseUri + "?{?}", HandleGETRootParam); Handle.GET(BaseUri + "/config/upstreamwhitelist", HandleGETUpstreamWhitelist); Handle.GET(BaseUri + "/config/downstreamwhitelist", HandleGETDownstreamWhitelist); string logFilePath = null; if (useFileLog) { logFilePath = Path.Combine(GetConfigDirectory(), "logs", "logstreamer", Db.Environment.DatabaseNameLower + ".logstreamer.log"); (new FileInfo(logFilePath)).Directory.Create(); } _logger = new Logger(logFilePath); Status = "Not connected."; if (!string.IsNullOrWhiteSpace(_config.ListenUri)) { _server = new LogStreamerParent(_logger, _servermanager, _serverCts.Token, _config); } StreamingEnabled = streamingEnabled; }
public void Process() { HandlerOptions ho = new HandlerOptions() { DateFormatString = Options.DateFormatString }; int count = 0; var files = Directory.GetFiles(Source, "*", Options.RecurseSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (var file in files) { count++; string status = String.Empty; string extension = Path.GetExtension(file).ToLower(); if (Options.FileExtensions.Length < 1 || Options.FileExtensions.Contains(extension)) { string value = String.Empty; foreach (var handler in Handlers) { var result = handler.Do(file, ho); if (String.IsNullOrEmpty(result.Value) && !Options.SkipFolder) { value = Path.Combine(value, Options.MissingFolderName); } else if (!String.IsNullOrEmpty(result.Value)) { value = Path.Combine(value, result.Value); } if (result.Exception != null) { status += String.Format("An error occurred retrieving {0} : {1}", handler.Name, result.Exception.Message); } } status += String.Format("Organizing file {0} of {1}.", count, files.Length); try { string destinationDirectory = Path.Combine(Destination, value); if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } string destinationFile = Path.Combine(destinationDirectory, Path.GetFileName(file)); if (!File.Exists(destinationFile) || Options.OverwriteExistingFiles) { if (Options.Copy) { File.Copy(file, destinationFile); } else { File.Move(file, destinationFile); } } } catch (Exception ex) { status += String.Format("An error occurred while trying to sort the file: {0}. {1}", file, ex.Message); } } else { status = String.Format("Skipped file {0}. File is not on the list of selected extensions.", file); } if (OnProgressUpdate != null) { OnProgressUpdate((int)Math.Round((double)(100 * count) / files.Length), status); } } }
public static void Write(this NeutronPlayer owner, NeutronStream.IWriter writer, HandlerOptions handler) { MatchmakingHelper.Internal.Redirect(owner, owner, handler.Protocol, handler.TargetTo, writer.ToArray(), MatchmakingHelper.Internal.GetPlayersByMatchmakingTo(owner, handler.MatchmakingTo)); }
/// <summary> /// Register /// </summary> public static void Register() { HandlerOptions opt = new HandlerOptions() { SkipHandlersPolicy = true, SkipRequestFilters = true }; #region Get MultiHost Depots (todo rename?) Starcounter.Handle.GET("/warehouse/api/multihostdepots/{?}", (string domain, Request request) => { string domainName = HttpUtility.UrlDecode(domain); // check if hostname exist HostService hostService = Db.SQL<HostService>("SELECT o FROM Warehouse.HostService o WHERE o.DomainName=?", domainName).First; if (hostService == null) { return System.Net.HttpStatusCode.NotFound; } string eTag = request.Headers["If-None-Match"]; string depotHostingEtag = string.Format("{0:X8}", hostService.DepotHostingModified.GetHashCode()); if (eTag == depotHostingEtag) { return System.Net.HttpStatusCode.NotModified; } QueryResultRows<DepotHostService> depotHostServices = Db.SQL<DepotHostService>("SELECT o FROM Warehouse.DepotHostService o WHERE o.HostService=?", hostService); Response response = new Response(); DepotHostServices_v1 result = new DepotHostServices_v1(); result.Items.Data = depotHostServices; response.Resource = result; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; response.Headers["ETag"] = depotHostingEtag; return response; }, opt); #endregion #region Get Default Depot Starcounter.Handle.GET("/warehouse/api/depots", (Request request) => { Response response = new Response(); Depots_v1 depots = new Depots_v1(); depots.Depots.Data = Db.SQL<Depot>("SELECT o.Depot FROM Warehouse.DefaultDepot o"); response.Resource = depots; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; }, opt); Starcounter.Handle.GET("/warehouse/api/depots?{?}", (string parameters, Request request) => { // TODO: Handle parameters Response response = new Response(); Depots_v1 depots = new Depots_v1(); depots.Depots.Data = Db.SQL<Depot>("SELECT o.Depot FROM Warehouse.DefaultDepot o"); response.Resource = depots; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; }, opt); #endregion #region Get Depot Starcounter.Handle.GET("/warehouse/api/depots/{?}", (string depotKey, Request request) => { Depot depot = Db.SQL<Depot>("SELECT o FROM Warehouse.Depot o WHERE o.DepotKey=?", depotKey).First; if (depot != null) { string eTag = request.Headers["If-None-Match"]; string depotEtag = string.Format("{0:X8}", depot.Modified.GetHashCode()); if (eTag == depotEtag) { return System.Net.HttpStatusCode.NotModified; } Response response = new Response(); Depot_v1 depotJson = new Depot_v1(); depotJson.Data = depot; response.Resource = depotJson; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; response.Headers["ETag"] = depotEtag; return response; } return (ushort)System.Net.HttpStatusCode.NotFound; }, opt); #endregion #region Get Applications Starcounter.Handle.GET("/warehouse/api/depots/{?}/applications", (string depotKey) => { Depot depot = Db.SQL<Depot>("SELECT o FROM Warehouse.Depot o WHERE o.DepotKey=?", depotKey).First; if (depot != null) { Response response = new Response(); DepotSoftwares_v1 depotItemsJson = new DepotSoftwares_v1(); depotItemsJson.DepotKey = depotKey; var software = Db.SQL<Software>("SELECT o.Software FROM Warehouse.DepotSoftware o WHERE o.Depot=?", depot); depotItemsJson.Softwares.Data = software; response.Resource = depotItemsJson; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; } return (ushort)System.Net.HttpStatusCode.NotFound; }, opt); #endregion #region Get Application Starcounter.Handle.GET("/warehouse/api/depots/{?}/applications/{?}", (string depotKey, string id, Request request) => { Depot depot = Db.SQL<Depot>("SELECT o FROM Warehouse.Depot o WHERE o.DepotKey=?", depotKey).First; if (depot != null) { Software software = depot.FindSoftware(id); if (software != null) { Response response = new Response(); Software_v1 softwareJson = new Software_v1(); softwareJson.Depot = depot; softwareJson.Data = software; if (software is Suite) { softwareJson.SuiteContents.Data = Db.SQL<Software>("SELECT o.Software FROM Warehouse.SuiteSoftware o WHERE o.Suite=?", software); softwareJson.Apps.Data = ((Suite)software).GetContentApps(); // TODO // app.IconUrl is null // Version.url is null } response.Resource = softwareJson; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; } } return (ushort)System.Net.HttpStatusCode.NotFound; }, opt); #endregion #region Get software versions Starcounter.Handle.GET("/warehouse/api/depots/{?}/applications/{?}/versions", (string depotKey, string id, Request request) => { DepotSoftware depotSoftware = Db.SQL<DepotSoftware>("SELECT o FROM Warehouse.DepotSoftware o WHERE o.Depot.DepotKey=? AND o.Software.ID=?", depotKey, id).First; if (depotSoftware != null) { Response response = new Response(); Versions_v1 versionsJson = new Versions_v1(); versionsJson.Depot = depotSoftware.Depot; versionsJson.Versions.Data = depotSoftware.Software.Versions; response.Resource = versionsJson; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; } return (ushort)System.Net.HttpStatusCode.NotFound; }, opt); #endregion #region Get software versions with parameters Starcounter.Handle.GET("/warehouse/api/depots/{?}/applications/{?}/versions?{?}", (string depotKey, string id, string parameters, Request request) => { DepotSoftware depotSoftware = Db.SQL<DepotSoftware>("SELECT o FROM Warehouse.DepotSoftware o WHERE o.Depot.DepotKey=? AND o.Software.ID=?", depotKey, id).First; if (depotSoftware != null) { NameValueCollection collection = System.Web.HttpUtility.ParseQueryString(parameters); string starcounterVersion = collection["starcounterversion"]; bool content; if (!bool.TryParse(collection["content"], out content)) { content = false; } if (starcounterVersion == null && (content == false || depotSoftware.Software is App)) { return Self.GET(string.Format("/warehouse/api/depots/{0}/applications/{1}/versions", depotKey, id)); } Response response = new Response(); Versions_v1 versionsJson = new Versions_v1(); versionsJson.Depot = depotSoftware.Depot; if (depotSoftware.Software is Suite && content) { IList<Version> result = GetAllSuiteContentVersion(depotSoftware.Software as Suite, starcounterVersion); if (result != null) { versionsJson.Versions.Data = result; } } else { foreach (Version version in depotSoftware.Software.Versions) { if (version.IsCompatibleWith(starcounterVersion)) { versionsJson.Versions.Add().Data = version; break; } } } response.Resource = versionsJson; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; } return (ushort)System.Net.HttpStatusCode.NotFound; }, opt); #endregion #region Get version json/binary Starcounter.Handle.GET("/warehouse/api/depots/{?}/applications/{?}/versions/{?}", (string depotKey, string softwareId, string id, Request request) => { Depot depot = Db.SQL<Depot>("SELECT o FROM Warehouse.Depot o WHERE o.DepotKey=?", depotKey).First; if (depot != null) { Software software = depot.FindSoftware(softwareId); if (software != null) { Version version = Db.SQL<Version>("SELECT o FROM Warehouse.Version o WHERE o.Software=? AND o.ID=?", software, id).First; if (version != null) { if (request.Headers["Accept"] == "application/octet-stream") { if (File.Exists(version.BinaryFile)) { string fileName = Path.GetFileName(version.BinaryFile); Response binResponse = new Response() { StatusCode = (ushort)System.Net.HttpStatusCode.OK }; binResponse.StreamedBody = new StreamReader(version.BinaryFile).BaseStream; binResponse.Headers["Content-Disposition"] = "attachment; filename=\"" + fileName + "\""; return binResponse; } return new Response() { StatusCode = (ushort)System.Net.HttpStatusCode.NotFound }; } Response response = new Response(); Version_v1 versionJson = new Version_v1(); versionJson.DepotKey = depotKey; versionJson.Data = version; response.Resource = versionJson; response.StatusCode = (ushort)System.Net.HttpStatusCode.OK; return response; } } } return (ushort)System.Net.HttpStatusCode.NotFound; }, opt); #endregion }
private async Task <string> RunHandlerAsync(HandlerOptions options) { var wrapperProcess = new WrapperProcess(options); long wrapperProcessID = wrapperProcess.ID; string retstr; Log.Information("Running handler[{0}]: \"{1}\"", wrapperProcessID, options.Path); try { wrapperProcess.Start(); await Task.Delay(Const.WrapperInitTimeout); var initResult = await _client.SendMessageAsync(wrapperProcess.Port, true, null, (Headers.Command, HandlerCommands.InitInfo)); string message = await initResult.GetMessageAsync(); if (initResult.IsSuccessStatusCode) { AddWrapper(wrapperProcess); _ = Task.Run(async() => { try { await wrapperProcess.ProcessDeathWaiting; } catch (TaskCanceledException) { return; } RemoveWrapper(wrapperProcess.ID); }); retstr = "Handler[{0}] has started successfully: {1}"; Log.Information(retstr, wrapperProcessID, message); } else { retstr = "Handler[{0}] failed to start: {1}"; Log.Error(retstr, wrapperProcessID, message); } retstr = string.Format(retstr, wrapperProcessID, message); } catch (Exception ex) { if (ex is HttpRequestException) { retstr = "Handler[{0}] is unavailable: {1}"; Log.Error(retstr, wrapperProcessID, ex); } else { retstr = "Exception while trying to run handler[{0}]: {1}"; Log.Error(retstr, wrapperProcessID, ex); } retstr = string.Format(retstr, wrapperProcessID, ex); } return(retstr); }