public void Activate() { // Set operating mode to active _setupManager = new SetupManager(_dataManager); _setupManager.OperatingMode = SetupManager.OperatingModeTypes.ACTIVE; //Console.WriteLine("Operating Mode: Active"); }
public void Close() { // Close the connection _setupManager = null; _readerManager = null; _infoManager = null; _dataManager.Close(); //Console.WriteLine("Connection Closed"); }
public void CreateFromAction_ExpressionHelperReturnsNullMethod_ThrowsException() { Expression<Action> expression = ReflectionUtility.GetExpression(() => Console.WriteLine()); _expressionHelperMock .Setup(helper => helper.GetMethod(expression)) .Returns(default(MethodCallInfo)); var subject = new SetupManager(_expressionHelperMock.Object); var exception = Assert.Throws<ArgumentException>(() => subject.Create(expression)); Assert.AreEqual("expression", exception.ParamName); }
public void When_AddGamifyConfiguratorToSetupManager_Then_Success() { var gamifyConfigurator = new GamifyConfigurator<TestMoveObject, TestResponseObject>(this.gameDefinition); var setupManager = new SetupManager(); setupManager.AddConfigurator(gamifyConfigurator); var plugin = setupManager.GetPlugin() as IPluginSetup; Assert.IsNotNull(plugin); Assert.AreEqual(5, plugin.Components.Count()); }
public void CreateFromAction_AddsToCollection() { var methodCallInfo = TestDataFactory.CreateMethodCallInfo(() => Console.WriteLine()); Expression<Action> expression = ReflectionUtility.GetExpression(() => Console.WriteLine()); _expressionHelperMock .Setup(helper => helper.GetMethod(expression)) .Returns(methodCallInfo); var subject = new SetupManager(_expressionHelperMock.Object); ISetup setup = subject.Create(expression); Assert.IsTrue(subject.Cast<ISetup>().SequenceEqual(new[] { setup })); }
void Awake () { localShowCase.gameObject.SetActive(false); fileTranser.gameObject.SetActive(false); navigation.gameObject.SetActive(false); loading.SetActive(false); customize.gameObject.SetActive(false); _setupManager = new SetupManager(); localShowCase.GetComponent<LocalCaseView>().SetSetupManager(_setupManager); navigation.GetComponent<NavigationView>().SetSetupManager(_setupManager); customize.GetComponent<CustomizeView>().SetSetupManager(_setupManager); rotation.GetComponent<RotationView>().SetSetupManager(_setupManager); calibration.gameObject.SetActive(false); rotation.gameObject.SetActive(false); }
public ActionResult EmployeeForm() { Employee emp = new Employee(); try { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { SetupManager.Provision(clientContext); var web = clientContext.Web; List desgList = web.Lists.GetByTitle("EmpDesignation"); ListItemCollection desgItems = desgList.GetItems(CamlQuery.CreateAllItemsQuery()); List countryList = web.Lists.GetByTitle("EmpCountry"); ListItemCollection countryItems = countryList.GetItems(CamlQuery.CreateAllItemsQuery()); string itemID = Request.QueryString["itemId"]; ListItem emplistItem = null; if (itemID != null) { List lstEmployee = web.Lists.GetByTitle("Employees"); emplistItem = lstEmployee.GetItemById(itemID); clientContext.Load(emplistItem); emp.Id = itemID; } clientContext.Load(desgItems); clientContext.Load(countryItems); clientContext.ExecuteQuery(); List <SelectListItem> empDesgList = new List <SelectListItem>(); foreach (var item in desgItems) { empDesgList.Add(new SelectListItem { Text = item["Title"].ToString() }); } emp.Designations = new SelectList(empDesgList, "Text", "Text"); List <SelectListItem> cList = new List <SelectListItem>(); foreach (var item in countryItems) { cList.Add(new SelectListItem { Text = item["Title"].ToString(), Value = item["ID"].ToString() }); } emp.Countries = new SelectList(cList, "Value", "Text"); string empDesignation = string.Empty; int stateID = 0; int countryId = 0; if (emplistItem != null) { emp.EmpNumber = ConvertObjectToString(emplistItem["EmpNumber"]); emp.Name = ConvertObjectToString(emplistItem["Title"]); emp.UserID = ConvertObjectToString(emplistItem["UserID"]); emp.EmpManager = ConvertObjectToString(emplistItem["EmpManager"]); emp.Designation = ConvertObjectToString(emplistItem["Designation"]); string cityVal = ConvertObjectToString(emplistItem["Location"]); ViewBag.JsCity = ""; ViewBag.JsStateID = ""; if (cityVal != "") { ViewBag.JsCity = cityVal; List lstCity = web.Lists.GetByTitle("EmpCity"); CamlQuery query = new CamlQuery(); query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", cityVal); ListItemCollection cityItems = lstCity.GetItems(query); clientContext.Load(cityItems); clientContext.ExecuteQuery(); if (cityItems.Count > 0) { stateID = (cityItems[0]["State"] as FieldLookupValue).LookupId; } ViewBag.JsStateID = stateID; List lstSate = web.Lists.GetByTitle("EmpState"); query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>{0}</Value></Eq></Where></Query></View>", stateID); ListItemCollection stateItems = lstSate.GetItems(query); clientContext.Load(stateItems); clientContext.ExecuteQuery(); if (stateItems.Count > 0) { countryId = (stateItems[0]["Country"] as FieldLookupValue).LookupId; } emp.CountryID = countryId.ToString(); } string skillsData = ConvertObjectToString(emplistItem["Skills"]); string[] skills = skillsData.Split(';'); List <Skill> lsSkills = new List <Skill>(); foreach (string skillData in skills) { if (skillData != "") { string[] skill = skillData.Split(','); lsSkills.Add(new Skill { Technology = skill[0], Experience = skill[1] }); } } emp.Skills = lsSkills; emp.SkillsCount = lsSkills.Count; string attachementID = ConvertObjectToString(emplistItem["AttachmentID"]); if (attachementID != "") { List lstAttachments = web.Lists.GetByTitle("EmpAttachments"); CamlQuery queryAttachments = new CamlQuery(); queryAttachments.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='AttachmentID' /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", attachementID); ListItemCollection attachmentItems = lstAttachments.GetItems(queryAttachments); clientContext.Load(attachmentItems); clientContext.ExecuteQuery(); List <EmpAttachment> lsAttachments = new List <EmpAttachment>(); if (attachmentItems.Count > 0) { foreach (ListItem item in attachmentItems) { lsAttachments.Add(new EmpAttachment { FileName = item["Title"].ToString(), FileUrl = Request.QueryString["SPHostUrl"] + "/Lists/EmpAttachments/" + item["FileLeafRef"].ToString(), FileRelativeUrl = item["FileRef"].ToString() }); } } emp.AttachmentID = attachementID; emp.Attachments = lsAttachments; emp.AttachmentsCount = lsAttachments.Count; } else { emp.AttachmentID = Guid.NewGuid().ToString(); } emp.ActionName = "UpdateEmployeeToSPList"; emp.SubmitButtonName = "Update Employee"; } else { PeopleManager peopleManager = new PeopleManager(clientContext); PersonProperties personProperties = peopleManager.GetMyProperties(); clientContext.Load(personProperties, p => p.AccountName); clientContext.ExecuteQuery(); if (personProperties != null && personProperties.AccountName != null) { emp.UserID = personProperties.AccountName; } List <Skill> lsSkills = new List <Skill>(); lsSkills.Add(new Skill { Technology = "", Experience = "" }); emp.Skills = lsSkills; emp.SkillsCount = lsSkills.Count; emp.AttachmentID = Guid.NewGuid().ToString(); emp.isFileUploaded = false; emp.ActionName = "AddEmployeeToSPList"; emp.SubmitButtonName = "Add Employee"; } LoadUserSiteGroups(ref emp, clientContext); } // if (clientContext != null) } // using (var clientContext ViewBag.SPURL = Request.QueryString["SPHostUrl"]; } catch (Exception ex) { ViewBag.Error = ex.Message + "\n" + ex.StackTrace; } return(View(emp)); }
public static void GenerateAvatar(int userID, string stringInDatabase) { string extension = Path.GetExtension(stringInDatabase); string fileName = SetupManager.GetAvatarFilename(userID, stringInDatabase);// userID + extension; string srcPath = SetupManager.GetSrcAvatarPath(userID, stringInDatabase); string tempFileName = fileName.Replace("\\", "/").Replace(userID + "/", ""); string bigAvatarPath = IOUtil.JoinPath(bigAvatarOutputPath, tempFileName); string smallAvatarPath = IOUtil.JoinPath(smallAvatarOutputPath, tempFileName); string normalAvatarPath = IOUtil.JoinPath(normalAvatarOutputPath, tempFileName); string bigDir = bigAvatarPath.Replace("/", "\\"); bigDir = bigDir.Substring(0, bigDir.LastIndexOf("\\")); string smallDir = smallAvatarPath.Replace("/", "\\"); smallDir = smallDir.Substring(0, smallDir.LastIndexOf("\\")); string normalDir = normalAvatarPath.Replace("/", "\\"); normalDir = normalDir.Substring(0, normalDir.LastIndexOf("\\")); if (Directory.Exists(bigDir) == false) { Directory.CreateDirectory(bigDir); } if (Directory.Exists(smallDir) == false) { Directory.CreateDirectory(smallDir); } if (Directory.Exists(normalDir) == false) { Directory.CreateDirectory(normalDir); } if (string.Compare(".gif", extension, true) == 0) { GifDecoder gifDecoder = new GifDecoder(); if (gifDecoder.Read(srcPath) == GifDecoder.STATUS_OK) { GenerateThumbGif(gifDecoder, smallAvatarPath, smallAvatarSize); GenerateThumbGif(gifDecoder, normalAvatarPath, normalAvatarSize); GenerateThumbGif(gifDecoder, bigAvatarPath, bigAvatarSize); } else { using (Image image = Image.FromFile(srcPath)) { GenerateThumb(image, smallAvatarPath, smallAvatarSize); GenerateThumb(image, normalAvatarPath, normalAvatarSize); GenerateThumb(image, bigAvatarPath, bigAvatarSize); } } } else { using (Image image = Image.FromFile(srcPath)) { GenerateThumb(image, smallAvatarPath, smallAvatarSize); GenerateThumb(image, normalAvatarPath, normalAvatarSize); GenerateThumb(image, bigAvatarPath, bigAvatarSize); } } }
// Update is called once per frame private void Start() { audio = gameObject.GetComponent <AudioSource>(); setupMan = GameObject.FindGameObjectWithTag("Manager").GetComponent <SetupManager>(); audio.enabled = false; }
public ActionResult Websites(Uri url, string username, string password) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("url={0}", url)); try { var serviceUri = GetOrganizationServiceUrl(url); var authenticationType = GetAuthenticationType(serviceUri); var connection = GetConnection(serviceUri, authenticationType, username, password); using (var service = new OrganizationService(connection)) { var query = new QueryExpression("adx_website") { ColumnSet = new ColumnSet("adx_name") }; query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); query.Criteria.AddCondition("adx_parentwebsiteid", ConditionOperator.Null); var linkEntity = new LinkEntity("adx_website", "adx_websitebinding", "adx_websiteid", "adx_websiteid", JoinOperator.LeftOuter); linkEntity.Columns.AddColumn("adx_websitebindingid"); linkEntity.EntityAlias = "binding"; linkEntity.LinkCriteria.AddCondition("statecode", ConditionOperator.Equal, 0); linkEntity.LinkCriteria.AddCondition("adx_sitename", ConditionOperator.Equal, SetupManager.GetSiteName()); var filter = linkEntity.LinkCriteria.AddFilter(LogicalOperator.Or); var path = HostingEnvironment.ApplicationVirtualPath ?? "/"; if (!path.StartsWith("/")) { path = "/" + path; } filter.AddCondition("adx_virtualpath", ConditionOperator.Equal, path); filter.AddCondition("adx_virtualpath", ConditionOperator.Equal, path.Substring(1)); if (path.Substring(1) == string.Empty) { filter.AddCondition("adx_virtualpath", ConditionOperator.Null); } query.LinkEntities.Add(linkEntity); var entities = service.RetrieveMultiple(query).Entities; var websites = entities .Select(w => new { Name = w.GetAttributeValue <string>("adx_name"), Id = w.GetAttributeValue <Guid>("adx_websiteid"), Binding = w.GetAttributeValue <AliasedValue>("binding.adx_websitebindingid") != null }) .OrderBy(w => w.Name) .ToList(); if (!websites.Any()) { throw new ModelErrorException("Website", ResourceManager.GetString("No_Active_Website_Found_Exception"), null); } return(Json(websites)); } } catch (ModelErrorException mee) { return(ToJsonModelError(mee.Key, mee)); } catch (Exception e) { return(ToJsonModelError("Website", e)); } }
private static string GetWebsiteName() { return(SetupManager.GetWebsiteName()); }
private void Awake() { Instance = this; } void Start() { SturfeeEventManager.Instance.OnSessionReady += OnSessionReady; SturfeeEventManager.Instance.OnLocalizationSuccessful += OnLocalizationSuccessful;
public void StartWork(VisaDataSet.ClientDataRow clientDataRow) { _logger.Trace( $"Start _crawlerWorker_DoWork. State = {_progressState}"); if (clientDataRow != null) { CurrentClientDataRow = clientDataRow; } if (_crawlerRegistry != null) { _crawlerRegistry.Canceled = Canceled; } var bBreak = false; //_crawlerWorker_CheckSiteAvailability(); do { CrawlerRefreshEngine(); if (_crawlerRegistry == null) { throw new NotImplementedException(); //This error instead of NullPointerException, //because if _crawlerRegistry is null here we something code in wrong way } if (_crawlerRegistry.Canceled) { _logger.Warn( $" _crawlerRegistry.Canceled _state={_progressState}"); bBreak = true; SetDefaultState(); CloseBrowsers(false); _crawlerRegistry.Canceled = false; _crawlerRegistry.Error = false; } else if (_crawlerRegistry.Error) // if Error { _logger.Warn( $"return _crawlerWorker_DoWork. State = {_progressState}." + $" OutData = {_crawlerRegistry.OutData}. _crawlerRegistry.Error = true "); SetDefaultState(); bBreak = true; SystemSounds.Beep.Play(); ShowAlert(_crawlerRegistry.OutData.IsNotBlank() ? _crawlerRegistry.OutData : ResManager.GetString(ResKeys.ServerError), true); CloseBrowsers(false); _crawlerRegistry.OutData = string.Empty; _crawlerRegistry.Error = false; } else { // ReSharper disable once SwitchStatementMissingSomeCases switch (_progressState) { case ProgressState.Start: XtraMessageBox.Show( ResManager.GetString( ResKeys.Complete_Registration), ResManager.GetString(ResKeys.SearchResult), MessageBoxButtons.OK, MessageBoxIcon.Information); bBreak = true; SetDefaultState(); break; case ProgressState.SelectVisaType: case ProgressState.ShowMessage: #if (!GoWithoutDates) case ProgressState.GetFirstDate: #endif case ProgressState.SubmitDate: case ProgressState.SubmitClientData: string sss = ""; if (SetupManager.GetOptions().RuCaptchaKey.IsNotBlank()) { sss = _crawlerRegistry.SendRecaptchav2Request( "6Lc7lBATAAAAAG-R0DVv6sR4BJPtVLMFJf7YusKQ"); } if (sss.StartsWith("OK")) { ShowAlert( $"OK response: \r\n{sss.Substring(3)}", true); } else { // captcha is not resolved, maby rucaptcha key is not entered in setupSettings SystemSounds.Beep.Play(); ShowAlert( ResManager.GetString(ResKeys.FillCaptchaAndPress), false); if (sss != "") { ShowAlert( $"Error in response: \r\n{sss}", true); } bBreak = true; } break; #if (GoWithoutDates) case ProgressState.GetFirstDate: ShowAlert( ResManager.GetString(ResKeys.Fill_Calendar_And_Captcha), false); bBreak = true; break; #else case ProgressState.SelectRegistrationTime: SystemSounds.Beep.Play(); ShowAlert(_crawlerRegistry.OutData, true); ShowAlert( ResManager.GetString(ResKeys.FillCaptchaAndPress), false); bBreak = true; break; #endif case ProgressState.BreakState: SetDefaultState(); bBreak = true; break; } } } while (!bBreak); _logger.Trace( $"End _crawlerWorker_DoWork. State = {_progressState}." + $" _crawlerRegistry.Error = {_crawlerRegistry?.Error}"); }
public void CreateFromFunc_AddsToCollection() { var methodCallInfo = TestDataFactory.CreateMethodCallInfo(() => Console.ReadLine()); var expression = ReflectionUtility.GetExpression(() => Console.ReadLine()); _expressionHelperMock .Setup(helper => helper.GetMethod(expression)) .Returns(methodCallInfo); var subject = new SetupManager(_expressionHelperMock.Object); var setup = subject.Create(expression) as IInternalSetup; Assert.IsTrue(subject.SequenceEqual(new[] { setup })); }
public void CreateFromProperty_ReturnsSetupFromExpressionHelper() { // Doesn't really matter what method call we create here, it's only // used for comparison. var methodCallInfo = TestDataFactory.CreateMethodCallInfo(() => Console.WriteLine()); var expression = ReflectionUtility.GetExpression(() => DateTime.Now); _expressionHelperMock .Setup(helper => helper.GetPropertyGetCall(expression)) .Returns(methodCallInfo); var subject = new SetupManager(_expressionHelperMock.Object); var result = subject.Create(expression) as IInternalSetup; Assert.AreSame(result.MethodCall, methodCallInfo); }
public SetupService() { _setupManager = new SetupManager(); }
void Start() { setup = this; Setup(); }
public void SetSetupManager(SetupManager mg) { _setManager = mg; }
public SetupController(DatabaseManager database, Settings settings, IStringLocalizer <SetupController> localizer) : base(database, settings) { _setupManager = new SetupManager(Database); _localizer = localizer; }
/// <summary> /// Initializes a new instance of the <see cref="FluentCircularApi{TTargetObject}"/> class. /// </summary> /// <param name="callback"> /// The callback. /// </param> /// <param name="setupManager"> /// The object filler setup manager. /// </param> internal FluentCircularApi(FluentFillerApi <TTargetObject> callback, SetupManager setupManager) { this.callback = callback; this.setupManager = setupManager; }
/// <summary> /// Start the ASP listener, and Connects to the stats database /// </summary> public static void Start() { // Can't start if we are already running! if (IsRunning) { return; } // === Try to connect to the database using (StatsDatabase Database = new StatsDatabase()) { if (!Database.TablesExist) { string message = "In order to use the Private Stats feature of this program, we need to setup a database. " + "You may choose to do this later by clicking \"Cancel\". Would you like to setup the database now?"; DialogResult R = MessageBox.Show(message, "Stats Database Setup", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (R == DialogResult.Yes) { SetupManager.ShowDatabaseSetupForm(DatabaseMode.Stats, MainForm.Instance); } // Call the stopped event to Re-enable the main form's buttons Stopped(null, EventArgs.Empty); return; } // Initialize the stats manager StatsManager.Load(Database); // Drop the SQLite ip2nation country tables (old table versions) if (Database.DatabaseEngine == DatabaseEngine.Sqlite) { string query = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='ip2nation'"; if (Database.ExecuteScalar <bool>(query)) // 0 count converts to false { Database.Execute("DROP TABLE IF EXISTS 'ip2nation';"); Database.Execute("DROP TABLE IF EXISTS 'ip2nationcountries';"); Database.Execute("VACUUM;"); } } } // === Compile our templates string path = Path.Combine(Program.RootPath, "Web", "Bf2Stats", "Views"); foreach (string file in Directory.EnumerateFiles(path, "*.cshtml")) { // If this template file is loaded already, then skip string fileName = Path.GetFileName(file); if (Engine.Razor.IsTemplateCached(fileName, ModelType)) { continue; } // Open the file, and compile it try { using (FileStream stream = File.OpenRead(file)) using (StreamReader reader = new StreamReader(stream)) Engine.Razor.Compile(reader.ReadToEnd(), fileName, ModelType); } catch (TemplateCompilationException e) { // Show the Exception form so the user can view DialogResult Res = ExceptionForm.ShowTemplateError(e, file); // If the user clicked "Quit", we stop if (Res == DialogResult.Abort) { return; } } } // === Load XML stats and awards files Bf2StatsData.Load(); BackendAwardData.BuildAwardData(); // Start the Listener and accept new connections try { Listener.Start(); Listener.BeginGetContext(HandleRequest, Listener); } catch (ObjectDisposedException) { // If we are disposed (happens when port 80 was in use already before, and we tried to start) // Then we need to start over with a new Listener CreateHttpListener(); Listener.Start(); Listener.BeginGetContext(HandleRequest, Listener); } // Fire Startup Event Started(null, EventArgs.Empty); }
public void GetSetupsForMethod_ReturnsOnlyMatchingSetups() { var methodCallInfo = TestDataFactory.CreateMethodCallInfo(() => Console.WriteLine()); Expression<Action> expression = ReflectionUtility.GetExpression(() => Console.WriteLine()); _expressionHelperMock .Setup(helper => helper.GetMethod(expression)) .Returns(methodCallInfo); var subject = new SetupManager(_expressionHelperMock.Object); subject.Create(expression); var result1 = subject.GetSetupsForMethod(ReflectionUtility.GetMethod(() => Console.WriteLine())); var result2 = subject.GetSetupsForMethod(ReflectionUtility.GetMethod(() => Console.ReadLine())); Assert.AreEqual(1, result1.Count); Assert.AreEqual(0, result2.Count); }
/// <summary> /// Starts the Login Server listeners, and begins accepting new connections /// </summary> public static void Start() { // Make sure we arent already running! if (bIsRunning) { return; } // Start the DB Connection using (GamespyDatabase Database = new GamespyDatabase()) { // First, make sure our account table exists if (!Database.TablesExist) { string message = "In order to use the Gamespy Emulation feature of this program, we need to setup a database. " + "You may choose to do this later by clicking \"Cancel\". Would you like to setup the database now?"; DialogResult R = MessageBox.Show(message, "Gamespy Database Setup", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (R == DialogResult.Yes) { SetupManager.ShowDatabaseSetupForm(DatabaseMode.Gamespy, MainForm.Instance); } // Call the stoOnShutdown event to Re-enable the main forms buttons Stopped(); return; } else if (Database.NeedsUpdated) { // We cannot run an outdated database DialogResult R = MessageBox.Show( String.Format( "The Gamespy database tables needs to be updated to version {0} before using this feature. Would you like to do this now?", GamespyDatabase.LatestVersion ) + Environment.NewLine.Repeat(1) + "NOTE: You should backup your gamespy account table if you are unsure as this update cannot be undone!", "Gamespy Database Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); // If the user doesnt migrate the database tables, quit if (R != DialogResult.Yes) { // Call the stoOnShutdown event to Re-enable the main forms buttons Stopped(); return; } // Do table migrations Database.MigrateTables(); } } // Bind gpcm server on port 29900 int port = 29900; // Setup the DebugLog DebugLog.LoggingEnabled = Program.Config.GamespyServerDebug; if (Program.Config.GamespyServerDebug) { DebugLog.ClearLog(); } try { // Begin logging DebugLog.Write("=== Gamespy Emulator Initializing ==="); DebugLog.Write("Starting Client Manager"); // Start the client manager ClientManager = new GpcmServer(); // Begin logging DebugLog.Write("Bound to TCP port: " + port); DebugLog.Write("Starting Account Service Provider"); // Start search provider server port++; SearchProvider = new GpspServer(); // Begin logging DebugLog.Write("Bound to TCP port: " + port); DebugLog.Write("Starting Master Server"); // Start then Master Server MasterServer = new MasterServer(ref port, DebugLog); // Start CDKey Server port = 29910; DebugLog.Write("Starting Cdkey Server"); CDKeyServer = new CDKeyServer(DebugLog); // Begin logging DebugLog.Write("=== Gamespy Emulator Initialized ==="); } catch (Exception E) { Notify.Show( "Failed to Start Gamespy Servers!", "Error binding to port " + port + ": " + Environment.NewLine + E.Message, AlertType.Warning ); // Append log if (DebugLog != null) { DebugLog.Write("=== Failed to Start Emulator Servers! ==="); DebugLog.Write("Error binding to port " + port + ": " + E.Message); } // Shutdown all started servers if (ClientManager != null && ClientManager.IsListening) { ClientManager.Shutdown(); } if (SearchProvider != null && SearchProvider.IsListening) { SearchProvider.Shutdown(); } if (MasterServer != null && MasterServer.IsRunning) { MasterServer.Shutdown(); } // Cdkey server must have throwm the exception at this point, since it starts last // Throw excpetion to parent throw; } // Let the client know we are ready for connections bIsRunning = true; Started(); }
private void step3_Next_Click(object sender, EventArgs e) { webSite.Focus(); step3_Next.Enabled = false; step3_Prev.Enabled = false; step4_Next.Enabled = true; step4_Prev.Enabled = true; Settings setting = Settings.Current; #if SQLSERVER setting.IServerAddress = address.Text.Trim(); setting.IDatabase = dbName.Text.Trim(' ', '[', ']'); setting.IsIWindows = false; if (!setting.IsIWindows) { setting.IUserID = userName.Text.Trim(); setting.IPassword = dbPwd.Text.Trim(); } string result = ConnectionTester.Check(); if (string.IsNullOrEmpty(result)) { settings = SetupManager.GetSettings(); result = ConnectionTester.GetUpgradeOption(); if (result.StartsWith("~"))//修改安装 { changeInstall.Text = result.Substring(1); changeInstall.Enabled = true; changeInstall.Checked = true; webSite.Text = settings.SiteName; webSite.Enabled = false; webUrl.Text = settings.SiteUrl; webUrl.Enabled = false; bbsName.Text = settings.BBSName; bbsName.Enabled = false; //bbsUrl.Text = settings.BBSUrl; //bbsUrl.Enabled = false; adminName.Text = settings.AdminName; adminName.Enabled = false; label23.Visible = false; adminPwd.Visible = false; //adminNickName.Text = settings.AdminNickName; //adminNickName.Enabled = false; } else { adminName.Text = "admin"; adminNickName.Text = "admin"; //ip或主机头..虚拟目录名称?多级虚拟目录.. string port = SiteInfo.Current.Port == "80" ? "" : ":" + SiteInfo.Current.Port; string ip = SiteInfo.Current.IP == "" ? "localhost" : SiteInfo.Current.IP; string host = SiteInfo.Current.Host == "" ? ip + port : SiteInfo.Current.Host + port; webUrl.Text = string.Format("http://{0}", host); //bbsUrl.Text = string.Format("http://{0}/{1}", host, SiteInfo.Current.VirtualName); // changeInstall.Text = result; changeInstall.Enabled = false; newInstall.Checked = true; } this.tabControl1.SelectedIndex = 3; } else { step3_Next.Enabled = true; step3_Prev.Enabled = true; MessageBox.Show("连接数据库失败", "安装向导", MessageBoxButtons.OK, MessageBoxIcon.Warning); } #endif #if SQLITE setting.BbsMaxFilePath = bbsMaxFilePath.Text; setting.IdMaxFilePath = idMaxFilePath.Text; adminName.Text = "admin"; adminNickName.Text = "admin"; //ip或主机头..虚拟目录名称?多级虚拟目录.. string port = SiteInfo.Current.Port == "80" ? "" : ":" + SiteInfo.Current.Port; string ip = SiteInfo.Current.IP == "" ? "localhost" : SiteInfo.Current.IP; string host = SiteInfo.Current.Host == "" ? ip + port : SiteInfo.Current.Host + port; webUrl.Text = string.Format("http://{0}", host); bbsUrl.Text = string.Format("http://{0}/{1}", host, SiteInfo.Current.VirtualName); Regex reg = new Regex(@"\\.*?", RegexOptions.IgnoreCase);// /d/bbsmax/bbsmax.config string[] array = null; if (reg.IsMatch(bbsMaxFilePath.Text)) { array = reg.Split(bbsMaxFilePath.Text); } setting.BbsMaxDatabase = array[array.Length - 1]; if (reg.IsMatch(idMaxFilePath.Text)) { array = reg.Split(idMaxFilePath.Text); } setting.IdMaxDatabase = array[array.Length - 1]; string result = string.Empty; if (ConnectionTester.IsSqlLiteMaxExists())//该数据库是否存在 { settings = SetupManager.GetSettings(); result = ConnectionTester.GetUpgradeOption(); if (result.StartsWith("~")) { changeInstall.Text = result.Substring(1); changeInstall.Enabled = true; changeInstall.Checked = true; webSite.Text = settings.SiteName; webSite.Enabled = false; webUrl.Text = settings.SiteUrl; webUrl.Enabled = false; bbsName.Text = settings.BBSName; bbsName.Enabled = false; bbsUrl.Text = settings.BBSUrl; bbsUrl.Enabled = false; adminName.Text = settings.AdminName; adminName.Enabled = false; label23.Visible = false; adminPwd.Visible = false; adminNickName.Text = settings.AdminNickName; adminNickName.Enabled = false; } else { changeInstall.Text = result; changeInstall.Enabled = false; newInstall.Checked = true; } this.tabControl1.SelectedIndex = 3; } else { changeInstall.Enabled = false; newInstall.Checked = true; this.tabControl1.SelectedIndex = 3; } #endif }
private void CrawlerRefreshEngine() { _logger.Trace( $"Start CrawlerRefreshEngine _state = {_progressState}"); var counter = 0; do { if (_crawlerRegistry != null && _crawlerRegistry.Error) { if (_crawlerRegistry.IsServerDown) { _logger.Warn($"Reload page. _state = {_progressState}"); ShowAlert( ResManager.GetString(ResKeys.WebPage_WillBeReloaded), true); _crawlerRegistry.ReloadPage(); } } if (_crawlerRegistry != null) { _crawlerRegistry.Error = false; } CrawlerWorkSecondPart(); if (_crawlerRegistry == null) { throw new NotImplementedException("CrawlerRefreshEngine => _crawlerRegistry == null"); } if (_crawlerRegistry.Canceled || !_crawlerRegistry.Error) { continue; } _logger.Warn( $"!_crawlerRegistry.Canceled && _crawlerRegistry.Error. _state = {_progressState}." + $" counter = {counter} _crawlerRegistry.ValidationError = {_crawlerRegistry.ValidationError}"); // ReSharper disable once SwitchStatementMissingSomeCases switch (_progressState) { case ProgressState.CheckDate: break; case ProgressState.BackToCityAndReason: _progressState = ProgressState.BackToCityAndReason; //todo need check no _progressState changes break; default: _progressState--; break; } counter++; if (!_crawlerRegistry.ValidationError) { continue; } //we should show that error and finish the process of registration counter = RefreshCount; _progressState = ProgressState.BreakState; _crawlerRegistry.ValidationError = false; } while (counter < RefreshCount && _crawlerRegistry.Error && SetupManager.GetOptions() .RepeatIfCrash); _logger.Trace($"End CrawlerRefreshEngine. _state={_progressState}"); }
void Start() { //setupManager = GameObject.FindGameObjectWithTag(_Tags.lobbyManager).GetComponent<SetupManager>(); setupManager = null; }
public async Task CanGetLetsEncryptCertificateAndRenewIt() { var settingPath = Path.Combine(NewDataPath(forceCreateDir: true), "settings.json"); var defaultSettingsPath = new PathSetting("settings.default.json").FullPath; File.Copy(defaultSettingsPath, settingPath, true); UseNewLocalServer(customConfigPath: settingPath); // Use this when testing against pebble //var acmeStaging = "https://localhost:14000/"; var acmeStaging = "https://acme-staging-v02.api.letsencrypt.org/"; Server.Configuration.Core.AcmeUrl = acmeStaging; Server.ServerStore.Configuration.Core.SetupMode = SetupMode.Initial; var domain = "RavenClusterTest" + Environment.MachineName.Replace("-", ""); string email; string rootDomain; Server.ServerStore.EnsureNotPassive(); var license = Server.ServerStore.LoadLicense(); using (var store = GetDocumentStore()) using (var commands = store.Commands()) using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var command = new ClaimDomainCommand(store.Conventions, context, new ClaimDomainInfo { Domain = domain, License = license }); await commands.RequestExecutor.ExecuteAsync(command, commands.Context); Assert.True(command.Result.RootDomains.Length > 0); rootDomain = command.Result.RootDomains[0]; email = command.Result.Email; } var tcpListener = new TcpListener(IPAddress.Loopback, 0); tcpListener.Start(); var port = ((IPEndPoint)tcpListener.LocalEndpoint).Port; tcpListener.Stop(); var setupInfo = new SetupInfo { Domain = domain, RootDomain = rootDomain, ModifyLocalServer = false, // N/A here RegisterClientCert = false, // N/A here Password = null, Certificate = null, LocalNodeTag = "A", License = license, Email = email, NodeSetupInfos = new Dictionary <string, SetupInfo.NodeInfo>() { ["A"] = new SetupInfo.NodeInfo { Port = port, Addresses = new List <string> { "127.0.0.1" } } } }; X509Certificate2 serverCert; byte[] serverCertBytes; string firstServerCertThumbprint; BlittableJsonReaderObject settingsJsonObject; using (var store = GetDocumentStore()) using (var commands = store.Commands()) using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var command = new SetupLetsEncryptCommand(store.Conventions, context, setupInfo); await commands.RequestExecutor.ExecuteAsync(command, commands.Context); Assert.True(command.Result.Length > 0); var zipBytes = command.Result; try { settingsJsonObject = SetupManager.ExtractCertificatesAndSettingsJsonFromZip(zipBytes, "A", context, out serverCertBytes, out serverCert, out _, out _, out _, out _); firstServerCertThumbprint = serverCert.Thumbprint; } catch (Exception e) { throw new InvalidOperationException("Unable to extract setup information from the zip file.", e); } // Finished the setup wizard, need to restart the server. // Since cannot restart we'll create a new server loaded with the new certificate and settings and use the server cert to connect to it settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Security.CertificatePassword), out string certPassword); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Security.CertificateLetsEncryptEmail), out string letsEncryptEmail); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.PublicServerUrl), out string publicServerUrl); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.ServerUrls), out string serverUrl); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.SetupMode), out SetupMode setupMode); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.ExternalIp), out string externalIp); var tempFileName = Path.GetTempFileName(); File.WriteAllBytes(tempFileName, serverCertBytes); IDictionary <string, string> customSettings = new ConcurrentDictionary <string, string> { [RavenConfiguration.GetKey(x => x.Security.CertificatePath)] = tempFileName, [RavenConfiguration.GetKey(x => x.Security.CertificateLetsEncryptEmail)] = letsEncryptEmail, [RavenConfiguration.GetKey(x => x.Security.CertificatePassword)] = certPassword, [RavenConfiguration.GetKey(x => x.Core.PublicServerUrl)] = publicServerUrl, [RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = serverUrl, [RavenConfiguration.GetKey(x => x.Core.SetupMode)] = setupMode.ToString(), [RavenConfiguration.GetKey(x => x.Core.ExternalIp)] = externalIp, [RavenConfiguration.GetKey(x => x.Core.AcmeUrl)] = acmeStaging }; Server.Dispose(); DoNotReuseServer(customSettings); } UseNewLocalServer(); // Note: because we use a staging lets encrypt cert, the chain is not trusted. // It only works because in the TestBase ctor we do: // RequestExecutor.ServerCertificateCustomValidationCallback += (msg, cert, chain, errors) => true; using (var store = GetDocumentStore(new Options { AdminCertificate = serverCert, ClientCertificate = serverCert })) using (var commands = store.Commands()) using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { Server.ServerStore.EnsureNotPassive(); Assert.Equal(firstServerCertThumbprint, Server.Certificate.Certificate.Thumbprint); Server.Time.UtcDateTime = () => DateTime.UtcNow.AddDays(80); var mre = new ManualResetEventSlim(); Server.ServerCertificateChanged += (sender, args) => mre.Set(); var command = new ForceRenewCertCommand(store.Conventions, context); await commands.RequestExecutor.ExecuteAsync(command, commands.Context); Assert.True(command.Result.Success, "ForceRenewCertCommand returned false"); var result = mre.Wait(Debugger.IsAttached ? TimeSpan.FromMinutes(10) : TimeSpan.FromMinutes(2)); if (result == false && Server.RefreshTask.IsCompleted) { if (Server.RefreshTask.IsFaulted || Server.RefreshTask.IsCanceled) { Assert.True(result, $"Refresh task failed to complete successfully. Exception: {Server.RefreshTask.Exception}"); } Assert.True(result, "Refresh task completed successfully, waited too long for the cluster cert to be replaced"); } Assert.True(result, "Refresh task didn't complete. Waited too long for the cluster cert to be replaced"); Assert.NotEqual(firstServerCertThumbprint, Server.Certificate.Certificate.Thumbprint); } }
public void StartWork(VisaDataSet.ClientDataRow clientDataRow) { _logger.Trace( $"Start _crawlerWorker_DoWork. State = {_progressState}"); if (clientDataRow != null) { CurrentClientDataRow = clientDataRow; } if (_crawlerRegistry != null) { _crawlerRegistry.Canceled = Canceled; } var bBreak = false; //_crawlerWorker_CheckSiteAvailability(); do { CrawlerRefreshEngine(); if (_crawlerRegistry == null) { throw new NotImplementedException(); //This error instead of NullPointerException, //because if _crawlerRegistry is null here we something code in wrong way } if (_crawlerRegistry.Canceled) { _logger.Warn( $" _crawlerRegistry.Canceled _state={_progressState}"); bBreak = true; SetDefaultState(); CloseBrowsers(false); _crawlerRegistry.Canceled = false; _crawlerRegistry.Error = false; } else if (_crawlerRegistry.Error) // if Error { _logger.Warn( $"return _crawlerWorker_DoWork. State = {_progressState}." + $" OutData = {_crawlerRegistry.OutData}. _crawlerRegistry.Error = true "); SetDefaultState(); bBreak = true; SystemSounds.Beep.Play(); ShowAlert(_crawlerRegistry.OutData.IsNotBlank() ? _crawlerRegistry.OutData : ResManager.GetString(ResKeys.ServerError), true); CloseBrowsers(false); _crawlerRegistry.OutData = string.Empty; _crawlerRegistry.Error = false; } else { // ReSharper disable once SwitchStatementMissingSomeCases switch (_progressState) { case ProgressState.Start: XtraMessageBox.Show( ResManager.GetString( ResKeys.Complete_Registration), ResManager.GetString(ResKeys.SearchResult), MessageBoxButtons.OK, MessageBoxIcon.Information); bBreak = true; SetDefaultState(); break; case ProgressState.ShowMessage: #if (!GoWithoutDates) case ProgressState.GetFirstDate: case ProgressState.SelectRegistrationTime: #endif var ruCaptchaKey = SetupManager.GetOptions().RuCaptchaKey; if (ruCaptchaKey.IsNotBlank()) { bBreak = Resolve_reCaptcha_v1(bBreak, ruCaptchaKey); } else // ruCaptchaKey IsBlank { SystemSounds.Beep.Play(); ShowAlert( ResManager.GetString(ResKeys.FillCaptchaAndPress), false); bBreak = true; } break; #if (GoWithoutDates) case ProgressState.GetFirstDate: ShowAlert( ResManager.GetString(ResKeys.Fill_Calendar_And_Captcha), false); bBreak = true; break; #else //case ProgressState.SelectRegistrationTime: // SystemSounds.Beep.Play(); // ShowAlert(_crawlerRegistry.OutData, // true); // ShowAlert( // ResManager.GetString(ResKeys.FillCaptchaAndPress), // false); // bBreak = true; // break; #endif case ProgressState.BreakState: SetDefaultState(); bBreak = true; break; } } } while (!bBreak); _logger.Trace( $"End _crawlerWorker_DoWork. State = {_progressState}." + $" _crawlerRegistry.Error = {_crawlerRegistry?.Error}"); }
/// <summary> /// Run Setup via SetupManager /// </summary> public static void RunSetup() => SetupManager.RunSetup(new ChangeTrackerSetup());
public Task SetupUnsecured() { AssertOnlyInSetupMode(); using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) using (var setupInfoJson = context.ReadForMemory(RequestBodyStream(), "setup-unsecured")) { // Making sure we don't have leftovers from previous setup try { using (var tx = context.OpenWriteTransaction()) { ServerStore.Engine.DeleteTopology(context); tx.Commit(); } } catch (Exception) { // ignored } var setupInfo = JsonDeserializationServer.UnsecuredSetupInfo(setupInfoJson); BlittableJsonReaderObject settingsJson; using (var fs = new FileStream(ServerStore.Configuration.ConfigPath, FileMode.Open, FileAccess.Read)) { settingsJson = context.ReadForMemory(fs, "settings-json"); } settingsJson.Modifications = new DynamicJsonValue(settingsJson) { [RavenConfiguration.GetKey(x => x.Licensing.EulaAccepted)] = true, [RavenConfiguration.GetKey(x => x.Core.SetupMode)] = nameof(SetupMode.Unsecured), [RavenConfiguration.GetKey(x => x.Security.UnsecuredAccessAllowed)] = nameof(UnsecuredAccessAddressRange.PublicNetwork) }; if (setupInfo.Port == 0) { setupInfo.Port = 8080; } settingsJson.Modifications[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = string.Join(";", setupInfo.Addresses.Select(ip => IpAddressToUrl(ip, setupInfo.Port))); if (setupInfo.TcpPort == 0) { setupInfo.TcpPort = 38888; } settingsJson.Modifications[RavenConfiguration.GetKey(x => x.Core.TcpServerUrls)] = string.Join(";", setupInfo.Addresses.Select(ip => IpAddressToUrl(ip, setupInfo.TcpPort, "tcp"))); if (setupInfo.EnableExperimentalFeatures) { settingsJson.Modifications[RavenConfiguration.GetKey(x => x.Core.FeaturesAvailability)] = FeaturesAvailability.Experimental; } var modifiedJsonObj = context.ReadObject(settingsJson, "modified-settings-json"); var indentedJson = SetupManager.IndentJsonString(modifiedJsonObj.ToString()); SetupManager.WriteSettingsJsonLocally(ServerStore.Configuration.ConfigPath, indentedJson); } return(NoContent()); }
/// <summary> /// 开始安装 /// </summary> private void Setup() { int stepIndex = 0; Settings setting = Settings.Current; setting.RootPath = SiteInfo.Current.WebPath; string error = string.Empty; try { //解压文件 stepIndex++; installWaiter.UpZip(); ResetBar(); //数据库操作 sql stepIndex++; SetupManager.InstallDatabase(delegate(int percent, string message) { setting.ProgressAccess = new Progress("安装/更新数据库", percent, stepIndex); InstallBarDelegate delegateInstallDb = new InstallBarDelegate(InstallDb); installBars.BeginInvoke(delegateInstallDb); }); #if SQLITE if (Settings.Current.SetupMode == Max.Installs.SetupMode.New) { error = SetupManager.SetDatabase(); } #endif ResetBar(); //写入配置文件 stepIndex++; ConfigConnectionString(); SetupManager.AlterGolbals(SiteInfo.Current.WebPath + "\\"); #if SQLSERVER if (Settings.Current.SetupMode == Max.Installs.SetupMode.New) { SetupManager.CreateAdministrator();//创建管理员 } #endif setting.ProgressAccess = new Progress("写入配置文件", 100, stepIndex); InstallBarDelegate delegateSetConfig = new InstallBarDelegate(SetConfig); installBars.BeginInvoke(delegateSetConfig); ResetBar(); //特殊文件夹权限设置 SetSpecialPurview(); setting.ProgressAccess = new Progress("设置文件夹权限", 100, stepIndex); InstallBarDelegate delegateSetPurview = new InstallBarDelegate(SetPurview); installBars.BeginInvoke(delegateSetPurview); //完成 InstallBarDelegate delegateInstallFinish = new InstallBarDelegate(InstallFinish); installBars.BeginInvoke(delegateInstallFinish); } catch (Exception ex) { Thread.CurrentThread.Abort(); SetupManager.CreateLog(ex); MessageBox.Show(ex.Message, "bbsMax安装向导", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public async Task SetupUnsecured() { AssertOnlyInSetupMode(); using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context)) using (var setupInfoJson = context.ReadForMemory(RequestBodyStream(), "setup-unsecured")) { // Making sure we don't have leftovers from previous setup try { using (var tx = context.OpenWriteTransaction()) { ServerStore.Engine.DeleteTopology(context); tx.Commit(); } } catch (Exception) { // ignored } var setupInfo = JsonDeserializationServer.UnsecuredSetupInfo(setupInfoJson); BlittableJsonReaderObject settingsJson; using (var fs = new FileStream(ServerStore.Configuration.ConfigPath, FileMode.Open, FileAccess.Read)) { settingsJson = context.ReadForMemory(fs, "settings-json"); } settingsJson.Modifications = new DynamicJsonValue(settingsJson) { [RavenConfiguration.GetKey(x => x.Licensing.EulaAccepted)] = true, [RavenConfiguration.GetKey(x => x.Core.SetupMode)] = nameof(SetupMode.Unsecured), [RavenConfiguration.GetKey(x => x.Security.UnsecuredAccessAllowed)] = nameof(UnsecuredAccessAddressRange.PublicNetwork) }; if (setupInfo.Port == 0) { setupInfo.Port = 8080; } settingsJson.Modifications[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = string.Join(";", setupInfo.Addresses.Select(ip => IpAddressToUrl(ip, setupInfo.Port))); if (setupInfo.TcpPort == 0) { setupInfo.TcpPort = 38888; } settingsJson.Modifications[RavenConfiguration.GetKey(x => x.Core.TcpServerUrls)] = string.Join(";", setupInfo.Addresses.Select(ip => IpAddressToUrl(ip, setupInfo.TcpPort, "tcp"))); if (setupInfo.EnableExperimentalFeatures) { settingsJson.Modifications[RavenConfiguration.GetKey(x => x.Core.FeaturesAvailability)] = FeaturesAvailability.Experimental; } if (!string.IsNullOrEmpty(setupInfo.LocalNodeTag)) { ServerStore.EnsureNotPassive(nodeTag: setupInfo.LocalNodeTag); } if (setupInfo.Environment != StudioConfiguration.StudioEnvironment.None) { var res = await ServerStore.PutValueInClusterAsync(new PutServerWideStudioConfigurationCommand(new ServerWideStudioConfiguration { Disabled = false, Environment = setupInfo.Environment })); await ServerStore.Cluster.WaitForIndexNotification(res.Index); } var modifiedJsonObj = context.ReadObject(settingsJson, "modified-settings-json"); var indentedJson = SetupManager.IndentJsonString(modifiedJsonObj.ToString()); SetupManager.WriteSettingsJsonLocally(ServerStore.Configuration.ConfigPath, indentedJson); } NoContentStatus(); }
public Task GetHosts() { AssertOnlyInSetupMode(); using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) using (var certificateJson = context.ReadForMemory(RequestBodyStream(), "setup-certificate")) { var certDef = JsonDeserializationServer.CertificateDefinition(certificateJson); X509Certificate2 certificate = null; string cn; try { certificate = certDef.Password == null ? new X509Certificate2(Convert.FromBase64String(certDef.Certificate), (string)null, X509KeyStorageFlags.MachineKeySet) : new X509Certificate2(Convert.FromBase64String(certDef.Certificate), certDef.Password, X509KeyStorageFlags.MachineKeySet); cn = certificate.GetNameInfo(X509NameType.SimpleName, false); } catch (Exception e) { throw new BadRequestException($"Failed to extract the CN property from the certificate {certificate?.FriendlyName}. Maybe the password is wrong?", e); } if (cn == null) { throw new BadRequestException($"Failed to extract the CN property from the certificate. CN is null"); } if (cn.LastIndexOf('*') > 0) { throw new NotSupportedException("The wildcard CN name contains a '*' which is not at the first character of the string. It is not supported in the Setup Wizard, you can do a manual setup instead."); } try { SecretProtection.ValidateKeyUsages("Setup Wizard", certificate); } catch (Exception e) { throw new InvalidOperationException($"Failed to load the uploaded certificate. Did you accidentally upload a client certificate?", e); } using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream())) { writer.WriteStartObject(); writer.WritePropertyName("CN"); writer.WriteString(cn); writer.WriteComma(); writer.WritePropertyName("AlternativeNames"); writer.WriteStartArray(); var first = true; foreach (var value in SetupManager.GetCertificateAlternativeNames(certificate)) { if (first == false) writer.WriteComma(); first = false; writer.WriteString(value); } writer.WriteEndArray(); writer.WriteEndObject(); } } return Task.CompletedTask; }
private void Start() { setupMan = GameObject.FindGameObjectWithTag("Manager").GetComponent <SetupManager>(); }
public async Task UserDomains() { AssertOnlyInSetupMode(); using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var json = context.Read(RequestBodyStream(), "license activation"); var licenseInfo = JsonDeserializationServer.LicenseInfo(json); var content = new StringContent(JsonConvert.SerializeObject(licenseInfo), Encoding.UTF8, "application/json"); try { string error = null; object result = null; string responseString = null; string errorMessage = null; try { var response = await ApiHttpClient.Instance.PostAsync("/api/v1/dns-n-cert/user-domains", content).ConfigureAwait(false); HttpContext.Response.StatusCode = (int)response.StatusCode; responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (response.IsSuccessStatusCode == false) { error = responseString; errorMessage = GeneralDomainRegistrationError; } else { result = JsonConvert.DeserializeObject<JObject>(responseString); } } catch (Exception e) { result = responseString; HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; error = e.ToString(); errorMessage = DomainRegistrationServiceUnreachableError; } if (error != null) { JToken errorJToken = null; if (responseString != null) { JsonConvert.DeserializeObject<JObject>(responseString).TryGetValue("Error", out errorJToken); } using (var streamWriter = new StreamWriter(ResponseBodyStream())) { new JsonSerializer().Serialize(streamWriter, new { Message = errorMessage, Response = result, Error = errorJToken ?? error }); streamWriter.Flush(); } return; } var results = JsonConvert.DeserializeObject<UserDomainsResult>(responseString); var fullResult = new UserDomainsAndLicenseInfo { UserDomainsWithIps = new UserDomainsWithIps { Emails = results.Emails, RootDomains = results.RootDomains, Domains = new Dictionary<string, List<SubDomainAndIps>>() } }; foreach (var domain in results.Domains) { var list = new List<SubDomainAndIps>(); foreach (var subDomain in domain.Value) { try { list.Add(new SubDomainAndIps { SubDomain = subDomain, // The ip list will be populated on the next call (/setup/populate-ips), when we know which root domain the user selected }); } catch (Exception) { continue; } } fullResult.UserDomainsWithIps.Domains.Add(domain.Key, list); } var licenseStatus = await SetupManager .GetUpdatedLicenseStatus(ServerStore, licenseInfo.License) .ConfigureAwait(false); fullResult.MaxClusterSize = licenseStatus.MaxClusterSize; fullResult.LicenseType = licenseStatus.Type; using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream())) { var blittable = DocumentConventions.DefaultForServer.Serialization.DefaultConverter.ToBlittable(fullResult, context); context.Write(writer, blittable); } } catch (LicenseExpiredException) { throw; } catch (Exception e) { throw new InvalidOperationException(GeneralDomainRegistrationError, e); } } }
public void CreateFromAction_ReturnsSetupFromExpressionHelper() { var methodCallInfo = TestDataFactory.CreateMethodCallInfo(() => Console.WriteLine()); Expression<Action> expression = ReflectionUtility.GetExpression(() => Console.WriteLine()); _expressionHelperMock .Setup(helper => helper.GetMethod(expression)) .Returns(methodCallInfo); var subject = new SetupManager(_expressionHelperMock.Object); var result = subject.Create(expression) as IInternalSetup; Assert.AreSame(result.MethodCall, methodCallInfo); }
public async Task CanGetLetsEncryptCertificateAndRenewIt() { UseNewLocalServer(); var acmeStaging = "https://acme-staging.api.letsencrypt.org/directory"; Server.Configuration.Core.AcmeUrl = acmeStaging; Server.ServerStore.Configuration.Core.SetupMode = SetupMode.Initial; var domain = "RavenClusterTest" + Environment.MachineName.Replace("-", ""); string email; string rootDomain; Server.ServerStore.EnsureNotPassive(); var license = Server.ServerStore.LoadLicense(); using (var store = GetDocumentStore()) using (var commands = store.Commands()) using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var command = new ClaimDomainCommand(store.Conventions, context, new ClaimDomainInfo { Domain = domain, License = license }); await commands.RequestExecutor.ExecuteAsync(command, commands.Context); Assert.True(command.Result.RootDomains.Length > 0); rootDomain = command.Result.RootDomains[0]; email = command.Result.Email; } var setupInfo = new SetupInfo { Domain = domain, RootDomain = rootDomain, ModifyLocalServer = false, // N/A here RegisterClientCert = false, // N/A here Password = null, Certificate = null, License = license, Email = email, NodeSetupInfos = new Dictionary <string, SetupInfo.NodeInfo>() { ["A"] = new SetupInfo.NodeInfo { Port = 8080, Addresses = new List <string> { "127.0.0.1" } } } }; X509Certificate2 serverCert; string firstServerCertThumbprint; BlittableJsonReaderObject settingsJsonObject; using (var store = GetDocumentStore()) using (var commands = store.Commands()) using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { var command = new SetupLetsEncryptCommand(store.Conventions, context, setupInfo); await commands.RequestExecutor.ExecuteAsync(command, commands.Context); Assert.True(command.Result.Length > 0); var zipBytes = command.Result; try { settingsJsonObject = SetupManager.ExtractCertificatesAndSettingsJsonFromZip(zipBytes, "A", context, out serverCert, out _, out _, out _); firstServerCertThumbprint = serverCert.Thumbprint; } catch (Exception e) { throw new InvalidOperationException("Unable to extract setup information from the zip file.", e); } } // Finished the setup wizard, need to restart the server. // Since cannot restart we'll create a new server loaded with the new certificate and settings and use the server cert to connect to it settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Security.CertificatePassword), out string certPassword); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Security.CertificateLetsEncryptEmail), out string letsEncryptEmail); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.PublicServerUrl), out string publicServerUrl); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.ServerUrls), out string serverUrl); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.SetupMode), out SetupMode setupMode); settingsJsonObject.TryGet(RavenConfiguration.GetKey(x => x.Core.ExternalIp), out string externalIp); var tempFileName = Path.GetTempFileName(); byte[] certData = serverCert.Export(X509ContentType.Pfx); File.WriteAllBytes(tempFileName, certData); IDictionary <string, string> customSettings = new ConcurrentDictionary <string, string> { [RavenConfiguration.GetKey(x => x.Security.CertificatePath)] = tempFileName, [RavenConfiguration.GetKey(x => x.Security.CertificateLetsEncryptEmail)] = letsEncryptEmail, [RavenConfiguration.GetKey(x => x.Security.CertificatePassword)] = certPassword, [RavenConfiguration.GetKey(x => x.Core.PublicServerUrl)] = publicServerUrl, [RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = serverUrl, [RavenConfiguration.GetKey(x => x.Core.SetupMode)] = setupMode.ToString(), [RavenConfiguration.GetKey(x => x.Core.ExternalIp)] = externalIp, [RavenConfiguration.GetKey(x => x.Core.AcmeUrl)] = acmeStaging }; Server.Dispose(); DoNotReuseServer(customSettings); UseNewLocalServer(); using (var store = GetDocumentStore(new Options { AdminCertificate = serverCert, ClientCertificate = serverCert })) using (var commands = store.Commands()) using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context)) { Server.ServerStore.EnsureNotPassive(); Assert.Equal(firstServerCertThumbprint, Server.Certificate.Certificate.Thumbprint); Server.Time.UtcDateTime = () => DateTime.UtcNow.AddDays(80); var mre = new ManualResetEventSlim(); Server.ServerCertificateChanged += (sender, args) => mre.Set(); var command = new ForceRenewCertCommand(store.Conventions, context); await commands.RequestExecutor.ExecuteAsync(command, commands.Context); mre.Wait(Debugger.IsAttached ? TimeSpan.FromMinutes(10) : TimeSpan.FromMinutes(2)); Assert.NotEqual(firstServerCertThumbprint, Server.Certificate.Certificate.Thumbprint); } }
public string SendRecaptchav2Request(string goggleKey) { _logger.Trace($"Start SendRecaptchav2Request"); //POST try { System.Net.ServicePointManager.Expect100Continue = false; var request = (HttpWebRequest)WebRequest.Create("http://rucaptcha.com/in.php"); // "http://2captcha.com/in.php"); var ruCaptchaID = SetupManager.GetOptions().RuCaptchaKey; var pageUrl = _driver.Url; //Uri.EscapeUriString(_driver.Url) Uri.EscapeDataString(_driver.Url) var postData = $"key={ruCaptchaID}&method=userrecaptcha&googlekey={goggleKey}&pageurl={pageUrl}"; var data = System.Text.Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var readStream = new System.IO.StreamReader(response.GetResponseStream()); var responseString = readStream.ReadToEnd(); response.Close(); readStream.Close(); // GET if (responseString.Contains("OK|")) { _logger.Trace($"responseString: {responseString}"); var param = "?key=" + ruCaptchaID + "&action=get&id=" + responseString.Substring(3); string captchaResponse; int count = 0; (_driver as IJavaScriptExecutor).ExecuteScript( "document.getElementById('g-recaptcha-response').setAttribute('style', " + "document.getElementById('g-recaptcha-response').getAttribute('style').replace('display: none;',''))"); var gRecaptchaResponse = FindElementWithChecking(By.Id("g-recaptcha-response")); do { Thread.Sleep(5000); var request2 = (HttpWebRequest)WebRequest.Create("http://rucaptcha.com/res.php" + param); { using (var response2 = (HttpWebResponse)request2.GetResponse()) { System.IO.Stream receiveStream = response2.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. using (var readStream2 = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8)) { captchaResponse = readStream2.ReadToEnd(); } } } if (captchaResponse.IsNotBlank()) { _logger.Trace($"GetCaptchaResponse count == {count}, captchaResponse: {captchaResponse}"); } if (count > 15) { _logger.Trace($"End SendRecaptchav2Request with Error: count == {count} of try get response: {captchaResponse}"); return("Error: Try count==" + count); } count++; } while (!captchaResponse.Contains("OK")); gRecaptchaResponse.SendKeys(captchaResponse.Substring(3)); _logger.Trace($"End SendRecaptchav2Request"); return(captchaResponse); } else { _logger.Trace($"End SendRecaptchav2Request with Error: {responseString}"); return("Error: " + responseString); } } catch (Exception ex) { string tt = ex.Message; _logger.Error(ex.Message); _logger.Error(ex.StackTrace); _logger.Trace($"End SendRecaptchav2Request with Exception {tt}"); return(tt); } }
// [ServerCallback] void Awake() { //Singleton if (instance != null && instance != this) { Destroy(gameObject); } else { instance = this; DontDestroyOnLoad(gameObject); //Instantiate new color dictionary colorDictionary = new ColorDictionary(colorListTextAsset); //playerData = GetComponent<PlayerData>(); activeTerrain = _Levels.Neutral; //parse face and vertex data from input files parsedTerrainFaces = ParseFaces(textInputFaces); parsedTerrainVertices = ParseVertices(textInputVertices); } }