public MeropsRegistry(AppHost appHost, RpcConfig config) : base(config) { Config = config; _appHost = appHost; _registryClient = new Lazy<IRegistryService>(() => { var address = Config?.Registry?.Address; if (string.IsNullOrWhiteSpace(address)) { LogHelper.Error("Registry Client Config Error: not exist or path is empty"); return null; } var client = _appHost == null ? ClientFactory.GetInstance<IRegistryService>(address) : _appHost.ClientFactory.GetInstance<IRegistryService>(address); return client; }); InitilizeAddresses(); // ReSharper disable once VirtualMemberCallInConstructor StartUpdateRegistry(); }
public void TestFixtureSetUp() { startedAt = Stopwatch.StartNew(); appHost = new AppHost(); appHost.Init(); appHost.Start("http://*:1337/"); }
public MeropsMonitor(AppHost appHost, RpcConfig config) { //var factory = new RpcClientFactory(null, null); _client = appHost.ClientFactory.GetInstance<IMonitorService>(config?.Monitor.Address); // ReSharper disable once UnusedVariable var writeTask = WriteLogsAsync(); }
public JournalServiceTests() { stopWatch = Stopwatch.StartNew(); appHost = new AppHost(); appHost.Init(); appHost.Start("http://*:8888/"); }
public override int Run(string[] remainingArguments) { var packageRepositories = new List<IPackageRepository>(); if (!string.IsNullOrEmpty(Json)) packageRepositories.Add(new JsonFilePackageRepository(Json)); if (!string.IsNullOrEmpty(Xml)) packageRepositories.Add(new XmlFilePackageRepository(Xml)); if (!string.IsNullOrEmpty(StashBaseUri) && !string.IsNullOrEmpty(StashProjectKey)) packageRepositories.Add(new StashPackageRepository(StashBaseUri, StashProjectKey, StashUsername, StashPassword, StashSshInsteadOfHttp)); if (packageRepositories.Count == 0) packageRepositories.Add(new InMemoryPackageRepository()); var listener = string.Format("http://*:{0}/", Port); var appHost = new AppHost(); appHost.Init(); appHost.Container.Register<IPackageRepository>(_ => new AggregatePackageRepository(packageRepositories)); System.Console.WriteLine("Listening on {0}", listener); appHost.Start(listener); Thread.Sleep(Timeout.Infinite); return 0; }
protected void Application_Start(object sender, EventArgs e) { Licensing.RegisterLicenseFromFileIfExists(@"~/appsettings.license.txt".MapHostAbsolutePath()); var appHost = new AppHost(); appHost.Init(); }
public void Init() { var configure = Configure.With() .DefaultBuilder() .DefiningCommandsAs(t => t.Namespace != null && t.Namespace.EndsWith("Commands")) .DefiningEventsAs(t => t.Namespace != null && t.Namespace.EndsWith("Events")) .RunTimeoutManager() .Log4Net() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .RavenPersistence() .Sagas() .RavenSagaPersister() .UnicastBus() .ImpersonateSender(false) .LoadMessageHandlers(); const string listeningOn = "http://*:8888/"; var appHost = new AppHost(); appHost.Init(); appHost.Start(listeningOn); Configure.Instance.Configurer.ConfigureComponent<RavenDocStore>(DependencyLifecycle.SingleInstance); Configure.Instance.Configurer.ConfigureComponent<TimeoutCalculator>(DependencyLifecycle.InstancePerUnitOfWork); Configure.Instance.Configurer.ConfigureComponent<SmsService>(DependencyLifecycle.InstancePerUnitOfWork); Configure.Instance.Configurer.ConfigureComponent<SmsTechWrapper>(DependencyLifecycle.InstancePerUnitOfWork); var bus = configure.CreateBus().Start(); //.Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install()); appHost.Container.Register(bus); appHost.Container.RegisterAutoWiredAs<RavenDocStore, IRavenDocStore>();//.RegisterAs<IRavenDocStore>(new RavenDocStore()); }
public void TestFixtureSetUp() { LogManager.LogFactory = new ConsoleLogFactory(); appHost = new AppHost(); appHost.Init(); appHost.Start("http://*:1337/"); }
public static void Main(string[] args) { Console.WriteLine ("Starting monotest service"); // configure JSON serializer JsConfig.EmitCamelCaseNames = true; var exit = false; var signals = new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }; var host = new AppHost(); host.Init(); host.Start("http://+:8080/"); // wait for termination while (!exit) { var id = UnixSignal.WaitAny(signals); if (id >= 0 && id < signals.Length) { if (signals[id].IsSet) exit = true; } } Console.WriteLine("Terminating monotest service"); }
protected void Application_Start(Object sender, EventArgs e) { // Make package reposiroties. var packageRepositories = new List<IPackageRepository>(); // Get bowerRegistryConfigurationSection var bowerRegistryConfigurationSection = ConfigurationManager.GetSection(BowerRegistryConfigurationSection.SectionName) as BowerRegistryConfigurationSection; if (bowerRegistryConfigurationSection != null) { // Get custom repositories. foreach (var packageRepository in bowerRegistryConfigurationSection.Repositories) { if (packageRepository.GetType() == typeof(InMemory)) packageRepositories.Add(new InMemoryPackageRepository()); if (packageRepository.GetType() == typeof(XmlFile)) packageRepositories.Add(new XmlFilePackageRepository(((XmlFile)packageRepository).FilePath)); if (packageRepository.GetType() == typeof(JsonFile)) packageRepositories.Add(new JsonFilePackageRepository(((JsonFile)packageRepository).FilePath)); if(packageRepository.GetType() == typeof(Stash)) { var stash = packageRepository as Stash; packageRepositories.Add(new StashPackageRepository(stash.BaseUri, stash.ProjectKey, stash.Username, stash.Password, stash.UseSSH)); } } } // Start app. var appHost = new AppHost(); appHost.Init(); appHost.Container.Register<IPackageRepository>(_ => new AggregatePackageRepository(packageRepositories)); }
static void Main (string[] args) { App = new AppHost("http://localhost:1337/") .Start(); NSApplication.Init (); NSApplication.Main (args); }
protected void Application_Start(object sender, EventArgs e) { RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var host = new AppHost(); host.Init(); }
public static void Main() { // Very simple console host var appHost = new AppHost(500); appHost.Init(); appHost.Start("http://*:9000/"); Console.ReadKey(); }
public static void Запустить() { const string listeningOn = "https://*:1337/"; var appHost = new AppHost(); appHost.Init(); appHost.Start(listeningOn); Console.WriteLine("AppHost Created at {0}, listening on {1}", DateTime.Now, listeningOn); }
static void Main(string[] args) { var appHost = new AppHost(); appHost.Init(); appHost.Start("http://localhost:2211/"); Console.Read(); }
static void Main(string[] args) { var listeningOn = args.Length == 0 ? "http://*:8007/" : args[0]; var appHost = new AppHost().Init().Start(listeningOn); Console.WriteLine("AppHost Created at {0}, listening on {1}", DateTime.Now, listeningOn); Console.ReadKey(); }
static void Main(string[] args) { App = new AppHost(); App.Init().Start("http://*:3337/"); NSApplication.Init(); NSApplication.Main(args); }
public void TestFixtureSetUp() { LogManager.LogFactory = new ConsoleLogFactory(); startedAt = Stopwatch.StartNew(); appHost = new AppHost(); appHost.Init(); appHost.Start(ListeningOn); }
public static void Main(string[] args) { var appHost = new AppHost(); appHost.Init(); appHost.Start("http://*****:*****@blub.com" }); }
private static void Main(string[] args) { var appHost = new AppHost(); appHost.Init(); appHost.Start("http://*:1337/"); System.Console.WriteLine("Listening on http://localhost:1337/ ..."); System.Console.ReadLine(); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); }
public void OnTestFixtureSetUp() { LogManager.LogFactory = new ConsoleLogFactory(); appHost = new AppHost { EnableRazor = false }; appHost.Plugins.Add(new MsgPackFormat()); appHost.Init(); appHost.Start(ListeningOn); }
public ServiceAppHost() { InitializeComponent(); XmlConfigurator.Configure(); var coreBuilder = HostConfigurator.GetBuilder(); //HostConfigurator.LoadHostedApps(typeof(IWebService).Assembly, true, coreBuilder); var core = coreBuilder.Build(); _host = new AppHost(core); }
/// <summary> /// Called when the service starts. /// </summary> /// <param name="args"></param> protected override void OnStart(string[] args) { // get the hostname. string hostname = ConfigurationManager.AppSettings["hostname"]; // start the self-hosting. _host = new AppHost(); _host.Init(); _host.Start(hostname); }
public void Run_for_10Mins() { using (var appHost = new AppHost()) { appHost.Init(); appHost.Start("http://localhost:11001/"); Process.Start("http://localhost:11001/"); Thread.Sleep(TimeSpan.FromMinutes(10)); } }
static void Main(string[] args) { Timer timer = new Timer(1000 * 60 * 60 * 5); timer.Elapsed += Timer_Elapsed; timer.Start(); string password = null; if (string.IsNullOrEmpty(Config.MergedConfig.CrmPassword)) { Console.Write($"Password for {Config.MergedConfig.CrmUser}: "); password = GetPasswordFromConsole(); Console.Clear(); } LoginHelper.Init(Config.MergedConfig.CrmKey ?? SecureRandomString.Generate(50)); CrmConnectionManager.Init(Config.MergedConfig.CrmUser, password ?? Config.MergedConfig.CrmPassword, "https://"+ Config.MergedConfig.CrmOrg +".crm.dynamics.com/XRMServices/2011/Organization.svc"); var listeningOn = Config.MergedConfig.Listen; var appHost = new AppHost(); appHost.Init(); appHost.GlobalRequestFilters.Add((req, res, obj) => { if (req.Dto is AuthenticatedRequestBase) { var request = (AuthenticatedRequestBase) req.Dto; if (string.IsNullOrEmpty(request.AuthenticationToken) && !string.IsNullOrEmpty(req.GetHeader("X-AUTH-TOKEN"))) request.AuthenticationToken = req.GetHeader("X-AUTH-TOKEN"); if (String.IsNullOrEmpty(request.AuthenticationToken)) throw new ApplicationException("No Auth Token"); var authInfo = LoginHelper.Instance.ParseToken(request.AuthenticationToken); if (authInfo == null) throw new ApplicationException("No Valid Auth Token"); } if (req.Dto is MattermostRequestBase) { var request = (MattermostRequestBase) req.Dto; if (String.IsNullOrEmpty(request.token)) throw new ApplicationException("No Token"); foreach (var token in Config.MergedConfig.WebhookTokens) { if (request.token.Equals(token)) return; } throw new ApplicationException("Not a valid token"); } }); appHost.Start(listeningOn); Console.WriteLine("AppHost Created at {0}, listening on {1}", DateTime.Now, listeningOn); Console.ReadKey(); }
static void Main() { Cef.Initialize(new CefSettings()); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppHost = new AppHost(); AppHost.Init().Start("http://*:1337/"); "ServiceStack SelfHost listening at {0} ".Fmt(HostUrl).Print(); Form = new FormMain(); Application.Run(Form); }
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs) { Loaded -= OnLoaded; AppHost appHost = new AppHost(); appHost.Init(); //EndpointHost.AppHost.Register(new InMemoryProjectModelRepo()); var projectModelRepo = EndpointHost.AppHost.TryResolve<IProjectModelRepository>(); var projectModel = projectModelRepo.GetProject(478, 174); var projectDto = ProjectModelConverters.FromModelToDto(projectModel); var projectVm = ProjectMVVMConverters.FromModelToViewModel(projectDto); ProjectView.DataContext = projectVm; }
//Run it! static void Main(string[] args) { var listeningOn = args.Length == 0 ? "http://*:1337/" : args[0]; var appHost = new AppHost(); appHost.Init(); // currently the following line will throw a HttpListnerException with "Access is denied" message // to avoid this, run VisualStudio as administrator appHost.Start(listeningOn); Console.WriteLine("AppHost Created at {0}, listening on {1}", DateTime.Now, listeningOn); while (true) { Console.ReadKey(); //appHost.SayHello("Bhavesh"); } }
static void Main(string[] args) { var appHost = new AppHost(); appHost.Init(); appHost.Start(ListeningOn); Console.WriteLine("Started listening on: " + ListeningOn); Console.WriteLine("AppHost Created at {0}, listening on {1}", DateTime.Now, ListeningOn); Console.WriteLine("ReadKey()"); Console.ReadKey(); }
/// <summary> /// /// </summary> /// <param name="host"></param> /// <param name="config"></param> public RpcServiceFactory(AppHost host, RpcConfig config) { _appHost = host; _config = config; Services = new ReadOnlyListWraper<RpcService>(_services); if (config?.Service?.Mapper != null) { var factory = ReflectHelper.CreateInstanceByIdentifier<IServiceMapperFactory>(config.Service.Mapper.Type); _serviceMapper = factory.CreateServiceMapper(this, config); } else { _serviceMapper = new DefaultServiceMapper(this, config); } }
public void SendLog() { SysUtils.SendMail(GKData.APP_MAIL, "GEDKeeper: feedback", "This automatic notification of error.", AppHost.GetLogFilename()); }
private static string GetIpcPath() { string strPath = AppHost.GetAppDataPathStatic(); return(strPath); }
public IRegistry CreateRegistry(AppHost appHost, RpcConfig config) { return(new MeropsRegistry(appHost, config)); }
//After configure called public static void AfterInit() { if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) { config.IgnoreFormatsInMetadata.Add("xml"); } if ((Feature.Json & config.EnableFeatures) != Feature.Json) { config.IgnoreFormatsInMetadata.Add("json"); } if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) { config.IgnoreFormatsInMetadata.Add("jsv"); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { config.IgnoreFormatsInMetadata.Add("csv"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { config.IgnoreFormatsInMetadata.Add("html"); } if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) { config.IgnoreFormatsInMetadata.Add("soap11"); } if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) { config.IgnoreFormatsInMetadata.Add("soap12"); } } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { Plugins.RemoveAll(x => x is HtmlFormat); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { Plugins.RemoveAll(x => x is CsvFormat); } if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) { Plugins.RemoveAll(x => x is MarkdownFormat); } if ((Feature.Razor & config.EnableFeatures) != Feature.Razor) { Plugins.RemoveAll(x => x is IRazorPlugin); //external } if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) { Plugins.RemoveAll(x => x is IProtoBufPlugin); //external } var specifiedContentType = config.DefaultContentType; //Before plugins loaded AppHost.LoadPlugin(Plugins.ToArray()); pluginsLoaded = true; AfterPluginsLoaded(specifiedContentType); }
public static string BrowseWebRootPath([NotNull] string webSiteRoot, [NotNull] string siteName) { Assert.ArgumentNotNull(webSiteRoot, nameof(webSiteRoot)); Assert.ArgumentNotNull(siteName, nameof(siteName)); var selectedPath = webSiteRoot; if (string.IsNullOrEmpty(selectedPath)) { selectedPath = AppHost.Settings.Get("Web Site Location", "Last Selected Path", string.Empty) as string ?? string.Empty; } var retry = true; while (retry) { DialogResult dialogResult; using (var d = new FolderBrowserDialog { ShowNewFolderButton = false, SelectedPath = selectedPath }) { if (!string.IsNullOrEmpty(siteName)) { d.Description = string.Format(Resources.SiteHelper_BrowseWebRootPath_Select_the_root_of_the_web_site___0___, siteName); } else { d.Description = Resources.SiteEditor_Browse_Select_the_root_of_the_web_site_; } dialogResult = d.ShowDialog(); selectedPath = d.SelectedPath; } if (dialogResult != DialogResult.OK) { return(null); } if (IsValidWebRootPath(selectedPath)) { break; } switch (AppHost.MessageBox(Resources.SiteHelper_BrowseWebRootPath_, Resources.Information, MessageBoxButton.YesNoCancel, MessageBoxImage.Question)) { case MessageBoxResult.Yes: retry = false; break; case MessageBoxResult.No: // retry = true; break; default: return(null); } } if (string.IsNullOrEmpty(selectedPath)) { return(null); } AppHost.Settings.Set("Web Site Location", "Last Selected Path", selectedPath); return(selectedPath); }
public void Run() { var token = CancellationTokenSource.Token; AppHost.RunAsync(token); }
//After configure called public static void AfterInit() { StartedAt = DateTime.Now; if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) { config.IgnoreFormatsInMetadata.Add("xml"); } if ((Feature.Json & config.EnableFeatures) != Feature.Json) { config.IgnoreFormatsInMetadata.Add("json"); } if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) { config.IgnoreFormatsInMetadata.Add("jsv"); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { config.IgnoreFormatsInMetadata.Add("csv"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { config.IgnoreFormatsInMetadata.Add("html"); } if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) { config.IgnoreFormatsInMetadata.Add("soap11"); } if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) { config.IgnoreFormatsInMetadata.Add("soap12"); } } if ((Feature.Html & config.EnableFeatures) != Feature.Html) { Plugins.RemoveAll(x => x is HtmlFormat); } if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) { Plugins.RemoveAll(x => x is CsvFormat); } if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) { Plugins.RemoveAll(x => x is MarkdownFormat); } if ((Feature.Razor & config.EnableFeatures) != Feature.Razor) { Plugins.RemoveAll(x => x is IRazorPlugin); //external } if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) { Plugins.RemoveAll(x => x is IProtoBufPlugin); //external } if (ExceptionHandler == null) { ExceptionHandler = (httpReq, httpRes, operationName, ex) => { var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message); var statusCode = ex.ToStatusCode(); //httpRes.WriteToResponse always calls .Close in it's finally statement so //if there is a problem writing to response, by now it will be closed if (!httpRes.IsClosed) { httpRes.WriteErrorToResponse(httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode); } }; } var specifiedContentType = config.DefaultContentType; //Before plugins loaded ConfigurePlugins(); AppHost.LoadPlugin(Plugins.ToArray()); pluginsLoaded = true; AfterPluginsLoaded(specifiedContentType); var registeredCacheClient = AppHost.TryResolve <ICacheClient>(); using (registeredCacheClient) { if (registeredCacheClient == null) { Container.Register <ICacheClient>(new MemoryCacheClient()); } } ReadyAt = DateTime.Now; }
public override bool Handle() { AppHost.MessageBox(Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(true); }
protected override void RenderPackages() { PluginsListBox.Clear(); PluginsListBox.SupportPrereleases = true; PluginsListBox.Loading.ShowLoading(PluginsListBox.PackageListPane); AppHost.DoEvents(); var plugins = new List <BasePluginDescriptor>(); IPackageRepository repository; try { repository = PackageRepositoryFactory.Default.CreateRepository(Url); } catch (Exception ex) { AppHost.Output.LogException(ex); AppHost.MessageBox(string.Format("The URL of the repository \"{0}\" is invalid:\n\n{1}\n\n{2}", FeedName, Url, ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } var packages = new List <IPackage>(); try { var query = repository.Search(PluginsListBox.Search.Text, PluginsListBox.IncludePrereleases); query = query.OrderByDescending(p => p.DownloadCount).ThenBy(p => p.Title).Skip(PageIndex * 10); packages = query.ToList().GroupBy(p => p.Id).Select(y => y.OrderByDescending(p => p.Version).First()).ToList(); } catch (WebException ex) { AppHost.MessageBox("Failed to communicated with the server: " + Url + "\n\nThe server responded with: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (UriFormatException) { AppHost.MessageBox("The URL is invalid: " + Url, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } var listBoxItems = new List <PluginsListBoxItem>(); var count = 0; foreach (var package in packages) { var plugin = new PackagePluginDescriptor(repository, package); plugins.Add(plugin); count++; if (count == 10) { break; } var isInstalled = InstalledPlugins.OfType <PackagePluginDescriptor>().Any(p => p.Package.Id == package.Id && p.Package.Version == package.Version); listBoxItems.Add(new PluginsListBoxItem(this, plugin, true, false, false, isInstalled)); } var total = PageIndex * 10 + packages.Count; var currentPage = PageIndex; var firstPage = currentPage - 2; if (firstPage < 0) { firstPage = 0; } var lastPage = total % 10 == 0 ? total / 10 - 1 : total / 10; if (lastPage > firstPage + 4) { lastPage = firstPage + 4; } PluginsListBox.RenderPlugins(listBoxItems); PluginsListBox.RenderPager(currentPage, firstPage, lastPage); }
public override void Modify(object sender, ModifyEventArgs eArgs) { var iRec = fDataOwner as GDMIndividualRecord; if (fBaseWin == null || fSheetList == null || iRec == null) { return; } GDMUserReference userRef = eArgs.ItemData as GDMUserReference; bool result = false; switch (eArgs.Action) { case RecordAction.raAdd: case RecordAction.raEdit: using (var dlg = AppHost.ResolveDialog <IUserRefEditDlg>(fBaseWin)) { bool exists = (userRef != null); if (!exists) { userRef = new GDMUserReference(); } dlg.UserRef = userRef; result = AppHost.Instance.ShowModalX(dlg, false); if (!exists) { if (result) { result = fUndoman.DoOrdinaryOperation(OperationType.otIndividualURefAdd, iRec, userRef); } else { userRef.Dispose(); } } } break; case RecordAction.raDelete: { string confirmation = !string.IsNullOrEmpty(userRef.StringValue) ? userRef.StringValue : userRef.ReferenceType; confirmation = string.Format( LangMan.LS(LSID.LSID_RemoveUserRefQuery), confirmation); if (AppHost.StdDialogs.ShowQuestionYN(confirmation)) { result = fUndoman.DoOrdinaryOperation(OperationType.otIndividualURefRemove, iRec, userRef); fBaseWin.Context.Modified = true; } break; } } if (result) { fBaseWin.Context.Modified = true; eArgs.IsChanged = true; } }
public MvcHtmlString GetAbsoluteUrl(string virtualPath) { return(MvcHtmlString.Create(AppHost.ResolveAbsoluteUrl(virtualPath, Request))); }
public AppServiceRunner(AppHost appHost, ActionContext actionContext) : base(appHost, actionContext) { }
public void Test() { if (!CheckHostName()) { return; } if (!CheckUserName()) { return; } if (!IsValidWebRootPath()) { return; } Connection connection; if (UseWindowsAuthentication.IsChecked == true) { connection = new Connection { UserName = CurrentUserName, UseWindowsAuth = true }; } else { connection = new Connection { UserName = UserName.Text, Password = Password.Password }; } connection.HostName = (Server.Text ?? string.Empty).Trim(); connection.DataServiceName = SiteEditor.DataDriver.SelectedValue as string ?? string.Empty; var site = new Site(connection); SiteEditor.TestButton.IsEnabled = false; SiteEditor.OkButton.IsEnabled = false; SiteEditor.CancelButton.IsEnabled = false; AppHost.DoEvents(); try { try { if (site.DataService.TestConnection(string.Empty)) { AppHost.MessageBox(Rocks.Resources.ProjectSettingsDialog_TestClick_Yes__it_works_, Rocks.Resources.Test_Connection, MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { AppHost.MessageBox(Rocks.Resources.SiteEditor_TestClick_OK__it_does_not_work_ + @"\n\n" + ex.Message, Rocks.Resources.Test_Connection, MessageBoxButton.OK, MessageBoxImage.Information); } } finally { SiteEditor.TestButton.IsEnabled = true; SiteEditor.OkButton.IsEnabled = true; SiteEditor.CancelButton.IsEnabled = true; } }
void Start() { // search for textures var texturepath = String.Concat(Environment.CurrentDirectory, @"\webroot\textures"); var info = new DirectoryInfo(texturepath); var fileInfo = info.GetFiles(); var availableTextures = new String[fileInfo.Length]; foreach (FileInfo file in fileInfo) { Debug.Log(file.Name); } // write config file string path = String.Concat(Environment.CurrentDirectory, @"\webroot\js\server-config.js"); TextWriter configFile = new StreamWriter(path); configFile.WriteLine("function ServerConfig(){"); configFile.WriteLine(String.Concat(@"this.ip = """, Network.player.ipAddress, @""";")); configFile.WriteLine(String.Concat(@"this.screenWidth = ", Screen.width, @";")); configFile.WriteLine(String.Concat(@"this.screenHeight = ", Screen.height, @";")); // write texture array configFile.WriteLine("this.textures = ["); for (var i = 0; i < fileInfo.Length; i++) { if (i == fileInfo.Length - 1) { configFile.WriteLine(String.Concat(@"""", fileInfo[i].Name, @"""")); } else { configFile.WriteLine(String.Concat(@"""", fileInfo[i].Name, @""",")); } } configFile.WriteLine("]"); configFile.WriteLine("}"); configFile.Close(); try { // create and start the host appHost = new AppHost(); appHost.Config.WebHostPhysicalPath = Path.Combine(Directory.GetCurrentDirectory(), webrootPath); appHost.Init(); appHost.Start(host); Debug.Log("Server listening at http://" + Network.player.ipAddress + "/home"); Cache = appHost.GetCacheClient(); } catch (Exception exeption) { Debug.Log(exeption); Cache = new MemoryCacheClient(); } var instance = FindObjectOfType(typeof(Exec)) as Exec; if (instance == null) { instance = gameObject.AddComponent <Exec>(); } wsServer = new WebSocketServer(1081) { OnDisconnect = context => { print("DISCONNECT"); }, // Called when the server connects OnConnected = context => { var response = (object)null; isConnected = true; GameObject cached = default(GameObject); shouldHideIP = true; OnGUI(); if (!OnlineUsers.ContainsKey(context.ClientAddress.ToString())) { OnlineUsers[context.ClientAddress.ToString()] = context; } // Called when the server disconnects context.SetOnDisconnect((e) => { UserContext ctx = null; OnlineUsers.TryRemove(e.ClientAddress.ToString(), out ctx); if (ctx != null) { Exec.OnMain(() => Debug.Log("User: "******" has disconnected")); } }); // Called when new data is received over the socket context.SetOnReceive((e) => { try { var jsonObject = JSON.Parse(e.DataFrame.ToString()); var eventIdentifier = jsonObject["event_identifier"].Value; var uuid = jsonObject["uuid"].Value; switch (eventIdentifier) { case "create_rect": Exec.OnMain(() => { GameObject rect = GameObject.CreatePrimitive(PrimitiveType.Quad); rect.name = uuid; rect.transform.position = new Vector3(0, 0, zIndexCounter); zIndexCounter--; //set shaders and custom behaviours rect.renderer.material.shader = Shader.Find("Custom/transform"); moveRect moveBehaviour = rect.AddComponent("moveRect") as moveRect; projectionMatrix matrix = rect.AddComponent("projectionMatrix") as projectionMatrix; vertexPositions vertexPositioning = rect.AddComponent <vertexPositions> () as vertexPositions; //set intitial position vertexPositioning.moveVertices(jsonObject["positions"]); //set the texture of the new rect var initTextureURL = jsonObject["texture"]["url"].Value; WWW initialtexture = new WWW(initTextureURL); while (!initialtexture.isDone) { var dumm = "blöd"; } Texture texture = initialtexture.texture; rect.renderer.material.mainTexture = texture; Debug.Log("Received create_rect command, new rect with uuid: " + uuid); }); break; case "delete_rect": Exec.OnMain(() => { GameObject rect = GameObject.Find(uuid); Destroy(rect); Debug.Log("Received delete_rect command for rect with uuid: " + uuid); }); break; case "move_rect": Exec.OnMain(() => { GameObject rect = GameObject.Find(uuid); var moveBehaviour = rect.GetComponent <vertexPositions>(); moveBehaviour.moveVertices(jsonObject["positions"]); Debug.Log("Received move_rect command"); }); break; case "move_vertice": // The index of the vertice that should be moved. var verticeIndex = 0; Vector2 verticeDelta; switch (jsonObject["vertice"].Value) { case ("top_left"): break; case ("top_right"): verticeIndex = 1; break; case ("bottom_right"): verticeIndex = 2; break; case ("bottom_left"): verticeIndex = 3; break; } var delta = jsonObject["vertice"]; verticeDelta.x = delta["x"].AsFloat; verticeDelta.y = delta["y"].AsFloat; Exec.OnMain(() => { GameObject rect = GameObject.FindWithTag(uuid); Debug.Log("Received move_vertice command for the vertice: " + jsonObject["vertice"].Value + " and delta: " + verticeDelta); }); break; case "change_texture": var textureURL = jsonObject["texture"]["url"].Value; Exec.OnMain(() => { WWW webTexture = new WWW(textureURL); //yield return webTexture; while (!webTexture.isDone) { var dumm = "blöd"; } Texture newTexture = webTexture.texture; GameObject rect = GameObject.Find(uuid); rect.renderer.material.mainTexture = newTexture; Debug.Log("Received change_texture command"); }); break; default: break; } var v = e.DataFrame.ToString().FromJson <Do>(); var ou = new { rcvd = e, t = DateTime.Now }; foreach (var userContext in OnlineUsers) { if (userContext.Key != context.ClientAddress.ToString()) { userContext.Value.Send(v.ToJson()); } } } catch (Exception exeption) { Exec.OnMain(() => Debug.Log(exeption)); } }); } }; // Starting the server wsServer.Start(); // suppossed to register the log callback... Application.RegisterLogCallback((log, stack, type) => { foreach (var userContext in OnlineUsers) { userContext.Value.Send(new { log, stack, type }.ToJson()); } }); }
public void ShowLog() { GKUtils.LoadExtFile(AppHost.GetLogFilename()); }
/// <summary> /// Add or update new user group. /// </summary> public GXUserGroupUpdateResponse Put(GXUserGroupUpdateRequest request) { IAuthSession s = this.GetSession(false); //Normal user can't change user group name or add new one. if (!GuruxAMI.Server.GXBasicAuthProvider.CanUserEdit(s)) { throw new ArgumentException("Access denied."); } long adderId = Convert.ToInt64(s.Id); List <GXEventsItem> events = new List <GXEventsItem>(); lock (Db) { using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted)) { bool superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s); //Add new user groups foreach (GXAmiUserGroup it in request.UserGroups) { if (string.IsNullOrEmpty(it.Name)) { throw new ArgumentException("Invalid name."); } //If new user group. if (it.Id == 0) { it.Added = DateTime.Now.ToUniversalTime(); Db.Insert(it); #if !SS4 it.Id = Db.GetLastInsertId(); #else it.Id = Db.LastInsertId(); #endif //Add adder to user group if adder is not super admin. if (!superAdmin) { GXAmiUserGroupUser g = new GXAmiUserGroupUser(); g.UserID = Convert.ToInt64(s.Id); g.UserGroupID = it.Id; g.Added = DateTime.Now.ToUniversalTime(); Db.Insert(g); } events.Add(new GXEventsItem(ActionTargets.UserGroup, Actions.Add, it)); } else //Update user group. { if (!superAdmin) { //User can't update user data if he do not have access to the user group. long[] groups1 = GXUserGroupService.GetUserGroups(Db, adderId); long[] groups2 = GXUserGroupService.GetUserGroups(Db, it.Id); bool found = false; foreach (long it1 in groups1) { foreach (long it2 in groups2) { if (it1 == it2) { found = true; break; } } if (found) { break; } } if (!found) { throw new ArgumentException("Access denied."); } } //Get Added time. #if !SS4 GXAmiUserGroup orig = Db.GetById <GXAmiUserGroup>(it.Id); #else GXAmiUserGroup orig = Db.SingleById <GXAmiUserGroup>(it.Id); #endif it.Added = orig.Added.ToUniversalTime(); Db.Update(it); events.Add(new GXEventsItem(ActionTargets.UserGroup, Actions.Edit, it)); } } trans.Commit(); } } AppHost host = this.ResolveService <AppHost>(); host.SetEvents(Db, this.Request, adderId, events); return(new GXUserGroupUpdateResponse(request.UserGroups)); }
public Index_NewSession() { appHost = AppHost.Simulate(AspMvcBasementHelloWorld.C_StringConstants.C_ApplicationName); //If you MVC project is not in the root of your solution directory then include the path //e.g. AppHost.Simulate("Website\MyMvcApplication") }
public GXRemoveUserFromUserGroupResponse Post(GXRemoveUserFromUserGroupRequest request) { IAuthSession s = this.GetSession(false); //Normal user can't change user group name or add new one. if (!GuruxAMI.Server.GXBasicAuthProvider.CanUserEdit(s)) { throw new ArgumentException("Access denied."); } long adderId = Convert.ToInt64(s.Id); List <GXEventsItem> events = new List <GXEventsItem>(); lock (Db) { using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted)) { bool superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s); foreach (long user in request.Users) { foreach (long group in request.Groups) { if (!superAdmin) { //User can't update user data if he do not have access to the user group. long[] groups1 = GXUserGroupService.GetUserGroups(Db, adderId); long[] groups2 = GXUserGroupService.GetUserGroups(Db, group); bool found = false; foreach (long it1 in groups1) { foreach (long it2 in groups2) { if (it1 == it2) { found = true; break; } } if (found) { break; } } if (!found) { throw new ArgumentException("Access denied."); } } string query = "SELECT * FROM " + GuruxAMI.Server.AppHost.GetTableName <GXAmiUserGroupUser>(Db); query += string.Format("WHERE UserID = {0} AND UserGroupID = {1}", user, group); List <GXAmiUserGroupUser> items = Db.Select <GXAmiUserGroupUser>(query); foreach (GXAmiUserGroupUser it in items) { Db.DeleteById <GXAmiUserGroupUser>(it.Id); events.Add(new GXEventsItem(ActionTargets.UserGroup, Actions.Edit, group)); } } } trans.Commit(); } } AppHost host = this.ResolveService <AppHost>(); host.SetEvents(Db, this.Request, adderId, events); return(new GXRemoveUserFromUserGroupResponse()); }
public static IServiceRunner <TRequest> CreateServiceRunner <TRequest>(ActionContext actionContext) { return(AppHost != null ? AppHost.CreateServiceRunner <TRequest>(actionContext) : new ServiceRunner <TRequest>(null, actionContext)); }
/// <summary> /// Applies the response filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyResponseFilters(IHttpRequest httpReq, IHttpResponse httpRes, object response) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Response Filters")) { var responseDto = response.ToResponseDto(); var attributes = responseDto != null ? FilterAttributeCache.GetResponseFilterAttributes(responseDto.GetType()) : null; //Exec all ResponseFilter attributes with Priority < 0 var i = 0; if (attributes != null) { for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests { AppHost.Release(attribute); } if (httpRes.IsClosed) { return(httpRes.IsClosed); } } } //Exec global filters foreach (var responseFilter in ResponseFilters) { responseFilter(httpReq, httpRes, response); if (httpRes.IsClosed) { return(httpRes.IsClosed); } } //Exec remaining RequestFilter attributes with Priority >= 0 if (attributes != null) { for (; i < attributes.Length; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests { AppHost.Release(attribute); } if (httpRes.IsClosed) { return(httpRes.IsClosed); } } } return(httpRes.IsClosed); } }
public void Setup() { AppHost.InitInstance <WFAppHost>(); }
public void TestFixtureSetUp() { //If you MVC project is not in the root of your solution directory then include the path //e.g. AppHost.Simulate("Website\MyMvcApplication") appHost = AppHost.Simulate("MyMvcApplication"); }
protected override void OnStart(AppHost host) { _host = host; base.OnStart(host); _vgDocHost = new VgVisualDocHost(); _vgDocHost.SetImgRequestDelgate(ImgBinderLoadImg); _vgDocHost.SetInvalidateDelegate(vgElem => { //TODO }); // { _backBoard = new BackDrawBoardUI(800, 600); _backBoard.SetLocation(0, 0); _backBoard.BackColor = PixelFarm.Drawing.Color.White; host.AddChild(_backBoard); } { _lstbox_svgFiles = new ListBox(200, 400); _lstbox_svgFiles.SetLocation(500, 20); host.AddChild(_lstbox_svgFiles); // _lstbox_svgFiles.ListItemMouseEvent += (s, e) => { if (_lstbox_svgFiles.SelectedIndex > -1) { if (_lstbox_svgFiles.GetItem(_lstbox_svgFiles.SelectedIndex).Tag is string filename) { ParseAndRenderSvgFile(filename); } } }; //foreach (string file in System.IO.Directory.GetFiles("../Test8_HtmlRenderer.Demo/Samples/Svg/others", "*.svg")) //{ // ListItem listItem = new ListItem(200, 20); // listItem.Text = System.IO.Path.GetFileName(file); // listItem.Tag = file; // _lstvw_svgFiles.AddItem(listItem); //} //foreach (string file in System.IO.Directory.GetFiles("../Test8_HtmlRenderer.Demo/Samples/Svg/freepik", "*.svg")) //{ // ListItem listItem = new ListItem(200, 20); // listItem.Text = System.IO.Path.GetFileName(file); // listItem.Tag = file; // _lstvw_svgFiles.AddItem(listItem); //} //foreach (string file in System.IO.Directory.GetFiles("../../../HtmlRenderer.SomeTestResources/Svg/twemoji", "*.svg")) //{ // ListItem listItem = new ListItem(200, 20); // listItem.Text = System.IO.Path.GetFileName(file); // listItem.Tag = file; // _lstvw_svgFiles.AddItem(listItem); //} //string[] allFiles = System.IO.Directory.GetFiles("../../../HtmlRenderer.SomeTestResources/Svg/noto_emoji", "*.svg"); string rootSampleFolder = "..\\Test8_HtmlRenderer.Demo\\Samples\\Svg\\others"; string[] allFiles = System.IO.Directory.GetFiles(rootSampleFolder, "*.svg"); int i = 0; int lim = Math.Min(allFiles.Length, 150); for (; i < lim; ++i) { string file = allFiles[i]; ListItem listItem = new ListItem(200, 20); listItem.Text = System.IO.Path.GetFileName(file); listItem.Tag = file; _lstbox_svgFiles.AddItem(listItem); } } }
/// <summary> /// Add users to user groups. /// </summary> /// <param name="request"></param> /// <returns></returns> public GXAddUserToUserGroupResponse Post(GXAddUserToUserGroupRequest request) { IAuthSession s = this.GetSession(false); //Normal user can't change user group name or add new one. if (!GuruxAMI.Server.GXBasicAuthProvider.CanUserEdit(s)) { throw new ArgumentException("Access denied."); } long adderId = Convert.ToInt64(s.Id); List <GXEventsItem> events = new List <GXEventsItem>(); lock (Db) { using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted)) { bool superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s); foreach (long user in request.Users) { foreach (long group in request.Groups) { if (!superAdmin) { //User can't update user data if he do not have access to the user group. long[] groups1 = GXUserGroupService.GetUserGroups(Db, adderId); long[] groups2 = GXUserGroupService.GetUserGroups(Db, group); bool found = false; foreach (long it1 in groups1) { foreach (long it2 in groups2) { if (it1 == it2) { found = true; break; } } if (found) { break; } } if (!found) { throw new ArgumentException("Access denied."); } } GXAmiUserGroupUser it = new GXAmiUserGroupUser(); it.UserGroupID = group; it.UserID = user; it.Added = DateTime.Now.ToUniversalTime(); Db.Insert(it); events.Add(new GXEventsItem(ActionTargets.UserGroup, Actions.Edit, it)); } } trans.Commit(); } } AppHost host = this.ResolveService <AppHost>(); host.SetEvents(Db, this.Request, adderId, events); return(new GXAddUserToUserGroupResponse()); }
public IEnumerable <TemplateModel> Get() { return(AppHost.GetTemplates()); }
public override void Modify(object sender, ModifyEventArgs eArgs) { var iRec = fDataOwner as GDMIndividualRecord; if (fBaseWin == null || fSheetList == null || iRec == null) { return; } GDMPersonalName persName = eArgs.ItemData as GDMPersonalName; bool result = false; switch (eArgs.Action) { case RecordAction.raAdd: case RecordAction.raEdit: using (var dlg = AppHost.ResolveDialog <IPersonalNameEditDlg>(fBaseWin)) { bool exists = (persName != null); if (!exists) { persName = new GDMPersonalName(); } dlg.Individual = iRec; dlg.PersonalName = persName; result = AppHost.Instance.ShowModalX(dlg, false); if (!exists) { if (result) { result = fUndoman.DoOrdinaryOperation(OperationType.otIndividualNameAdd, iRec, persName); } else { persName.Dispose(); } } } break; case RecordAction.raDelete: if (iRec.PersonalNames.Count > 1) { result = (AppHost.StdDialogs.ShowQuestionYN(LangMan.LS(LSID.LSID_RemoveNameQuery))); if (result) { result = fUndoman.DoOrdinaryOperation(OperationType.otIndividualNameRemove, iRec, persName); } } else { AppHost.StdDialogs.ShowError(LangMan.LS(LSID.LSID_RemoveNameFailed)); } break; case RecordAction.raMoveUp: case RecordAction.raMoveDown: int idx = iRec.PersonalNames.IndexOf(persName); switch (eArgs.Action) { case RecordAction.raMoveUp: iRec.PersonalNames.Exchange(idx - 1, idx); break; case RecordAction.raMoveDown: iRec.PersonalNames.Exchange(idx, idx + 1); break; } result = true; break; } if (result) { fBaseWin.Context.Modified = true; eArgs.IsChanged = true; } }
private void InitializeDataService() { if (Connection.AutomaticallyUpdate && !string.IsNullOrEmpty(Connection.WebRootPath)) { UpdateServerComponentsManager.AutomaticUpdate(Connection.WebRootPath); } dataService = CreateDataService(); var busy = true; var aspxAuthCookieBehavior = new AspxAuthCookieBehavior(GetHostName()); dataService.Endpoint.Behaviors.Add(aspxAuthCookieBehavior); AppHost.Statusbar.SetText(string.Format(Resources.LoginWindow_ControlLoaded_Connecting_to___0______, Connection.HostName)); EventHandler <LoginCompletedEventArgs> completed = delegate(object sender, LoginCompletedEventArgs e) { if (e.Error != null) { if (DisableLoginErrorMessage) { busy = false; dataService = null; return; } Dispatcher.CurrentDispatcher.Invoke(new Action(delegate { var endPoint = dataService != null ? dataService.Endpoint : null; var pipeline = TroubleshooterPipeline.Run().WithParameters(this, true, e.Error, endPoint); if (pipeline.Retry) { if (dataService == null) { dataService = CreateDataService(); } dataService.LoginAsync(GetCredentials()); return; } dataService = null; busy = false; })); return; } if (e.Result == @"Invalid user or password.") { Dispatcher.CurrentDispatcher.Invoke(new Action(ShowInvalidUserNameOrPassword)); dataService = null; busy = false; return; } WebServiceVersion = @"0.0.0.0"; SitecoreVersionString = string.Empty; SitecoreVersion = RuntimeVersion.Empty; var root = e.Result.ToXElement(); if (root != null) { LoggedInPipeline.Run().WithParameters(this, root); } busy = false; }; AppHost.DoEvents(); if (dataService != null) { dataService.LoginCompleted += completed; var dispatcherOperation = Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => dataService.LoginAsync(GetCredentials()))); if (!AppHost.DoEvents(ref busy)) { dispatcherOperation.Abort(); ServiceEndpoint endPoint = null; if (dataService != null) { endPoint = dataService.Endpoint; } var pipeline = TroubleshooterPipeline.Run().WithParameters(this, true, new TimeoutException("The operation timed out after 2 minutes."), endPoint); if (pipeline.Retry && dataService != null) { dataService.LoginAsync(GetCredentials()); return; } dataService = null; } } if (dataService != null) { dataService.LoginCompleted -= completed; } if (dataService != null && dataService.InnerChannel.State == CommunicationState.Opened) { Status = DataServiceStatus.Connected; } else { Status = DataServiceStatus.Failed; } }
private void ShowInvalidUserNameOrPassword() { AppHost.MessageBox(Resources.LoginWindow_ShowInvalidUserNameOrPassword_Invalid_user_name_or_password_, Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error); }
protected void Application_Start(object sender, EventArgs e) { var appHost = new AppHost(); appHost.Init(); }
public override void Modify(object sender, ModifyEventArgs eArgs) { var iRec = fDataOwner as GDMIndividualRecord; if (fBaseWin == null || fSheetList == null || iRec == null) { return; } GDMChildToFamilyLink cfLink = eArgs.ItemData as GDMChildToFamilyLink; bool result = false; switch (eArgs.Action) { case RecordAction.raAdd: GDMFamilyRecord family = fBaseWin.Context.SelectFamily(iRec); if (family != null && family.IndexOfChild(iRec) < 0) { result = fUndoman.DoOrdinaryOperation(OperationType.otIndividualParentsAttach, iRec, family); } break; case RecordAction.raEdit: if (cfLink != null) { using (var dlg = AppHost.ResolveDialog <IParentsEditDlg>(fBaseWin)) { dlg.Person = iRec; dlg.Link = cfLink; result = AppHost.Instance.ShowModalX(dlg, false); } } break; case RecordAction.raDelete: if (AppHost.StdDialogs.ShowQuestionYN(LangMan.LS(LSID.LSID_DetachParentsQuery))) { var famRec = fBaseContext.Tree.GetPtrValue(cfLink); result = fUndoman.DoOrdinaryOperation(OperationType.otIndividualParentsDetach, iRec, famRec); } break; case RecordAction.raMoveUp: case RecordAction.raMoveDown: int idx = iRec.ChildToFamilyLinks.IndexOf(cfLink); switch (eArgs.Action) { case RecordAction.raMoveUp: iRec.ChildToFamilyLinks.Exchange(idx - 1, idx); break; case RecordAction.raMoveDown: iRec.ChildToFamilyLinks.Exchange(idx, idx + 1); break; } result = true; break; } if (result) { fBaseWin.Context.Modified = true; eArgs.IsChanged = true; } }