public void Run() { var ctx = System.Threading.SynchronizationContext.Current; var client = new WebClient(); var data = new JObject(); data["instanceId"] = InstanceId.ToString("N"); data["ports"] = new JArray(Ports); var succeeded = false; var stopwatch = new System.Diagnostics.Stopwatch(); int[] response_ports = null; try { stopwatch.Start(); var body = System.Text.Encoding.UTF8.GetBytes(data.ToString()); var response_body = System.Text.Encoding.UTF8.GetString(client.UploadData(Target, body)); var response = JToken.Parse(response_body); response_ports = response["ports"].Select(token => (int)token).ToArray(); stopwatch.Stop(); succeeded = true; } catch (WebException) { succeeded = false; } if (PortCheckCompleted != null) { PortCheckCompleted( this, new PortCheckCompletedEventArgs( succeeded, response_ports, stopwatch.Elapsed)); } }
public void WriteXml(XmlWriter writer) { writer.WriteStartElement("SceneObject"); writer.WriteAttributeString("id", Id); writer.WriteAttributeString("instanceId", InstanceId.ToString()); writer.WriteStartElement("Transform"); writer.WriteAttributeString("position", XmlUtils.Vector3ToString(Transform.LocalPosition)); writer.WriteAttributeString("rotation", XmlUtils.Vector4ToString(Transform.LocalRotation.ToAxisAngle())); writer.WriteAttributeString("scale", XmlUtils.Vector3ToString(Transform.LocalScale)); writer.WriteEndElement(); foreach (Component c in Components) { c.WriteXml(writer); } for (int i = 0; i < ChildCount; ++i) { GetChild(i).WriteXml(writer); } writer.WriteEndElement(); }
private void EstablishTempFolder() { //Delete old path and create new path for processed video RemoveTempFiles(); _tempFilePath = Path.Combine(TempPath, InstanceId.ToString()); Directory.CreateDirectory(_tempFilePath); }
public void SetHostBox(Box box) { Box = box; _browser.Source = new Uri(box.StartUrl); _titleBrowser.Source = new Uri("http://localhost:4300/Titlebar/" + InstanceId.ToString()); _browser.Width = ClientSize.Width - 4; _browser.Height = ClientSize.Height - 26; }
/// <param name="apiKey"></param> /// <returns></returns> public string GetMarketHashName(string apiKey) { var handler = new SteamEconomyHandler(apiKey); var data = new Dictionary <string, string> { { ClassId.ToString(), InstanceId.ToString() } }; AssetClassInfo info = handler.GetAssetClassInfo(Convert.ToUInt32(AppId), data); return(info.MarketHashName); }
//private void UpdateHeight() { // Height = Math.Max(MConnectors.Count(c => c.Type == ConnectorType.InputConnector), // MConnectors.Count(c => c.Type == ConnectorType.OutputConnector)) * 13 + 45; //} public void Serialize(XmlWriter writer, NodeEditor editor) { writer.WriteAttributeString("id", InstanceId.ToString()); writer.WriteAttributeString("factoryId", FactoryId.ToString()); writer.WriteAttributeString("uniqueName", UniqueName); writer.WriteAttributeString("x", Location.X.ToString()); writer.WriteAttributeString("y", Location.Y.ToString()); writer.WriteAttributeString("title", Title); Node.Serialize(writer); }
public async Task <PortCheckResult> RunAsync() { var client = new WebClient(); var data = new JObject(); data["instanceId"] = InstanceId.ToString("N"); data["ports"] = new JArray(this.Ports); var succeeded = false; var stopwatch = new System.Diagnostics.Stopwatch(); var cancel = new CancellationTokenSource(); string response_body = null; try { stopwatch.Start(); var body = System.Text.Encoding.UTF8.GetBytes(data.ToString()); using (cancel.Token.Register(() => client.CancelAsync())) { cancel.CancelAfter(5000); response_body = System.Text.Encoding.UTF8.GetString( await client.UploadDataTaskAsync(Target, body).ConfigureAwait(false) ); } stopwatch.Stop(); succeeded = true; var response = JToken.Parse(response_body); IPAddress response_ip; IPAddress.TryParse(response["ip"].ToString(), out response_ip); var response_ports = response["ports"].Select(token => (int)token); return(new PortCheckResult( succeeded, LocalAddress, response_ip, response_ports.ToArray(), stopwatch.Elapsed)); } catch (WebException) { succeeded = false; return(new PortCheckResult( succeeded, LocalAddress, null, new int[0], stopwatch.Elapsed)); } catch (Newtonsoft.Json.JsonReaderException) { succeeded = false; return(new PortCheckResult( succeeded, LocalAddress, null, new int[0], stopwatch.Elapsed)); } }
// -------------------------------------------------------------------- public override void WriteXml(XmlWriter writer) { writer.WriteStartElement(sXmlNodeName); writer.WriteAttributeString(sXmlAtttributeId, Id); writer.WriteAttributeString(sXmlAtttributeInstanceId, InstanceId.ToString()); writer.WriteAttributeString(sXmlAtttributeEntityGuid, EntityRef.LinkedProjectAsset.Guid.ToString()); Transform.WriteXml(writer); writer.WriteEndElement(); }
public TransportReceiveProcessor( ITransmissionConnection connection, ITransportProtocolDeserializer deserializer) { InstanceId = connection.Id; _log = LogManager.GetLogger <TransportReceiveProcessor>(InstanceId.ToString()); _receiveProcessor = new MessagingReceiveProcessor(connection, deserializer); _handler = new TransportHeaderHandler <Task, Maybe <IPooledBuffer> >( HandleConnetionHeaderAsync, HandleChannelHeaderAsync); _buffer.Out.PropagateCompletionFrom(ProcessAsync()); In.Completion.LogCompletion(_log); }
//#region Instance Equality ///// <remarks>Two signals are equal only if they are the same instance. Use <see cref="IsEquivalentTo"/> instead if you need to check for equivalent signals.</remarks> //public bool Equals(Signal other) //{ // return other != null && _iid.Equals(other.InstanceId); //} ///// <remarks>Two signals are equal only if they are the same instance. Use <see cref="IsEquivalentTo"/> instead if you need to check for equivalent signals.</remarks> //public override bool Equals(object obj) //{ // Signal other = obj as Signal; // if(other == null) // return false; // else // return _iid.Equals(other._iid); //} //public override int GetHashCode() //{ // return _iid.GetHashCode(); //} //#endregion public override string ToString() { string name = string.IsNullOrEmpty(Label) ? "Signal " + InstanceId.ToString() : "Signal " + Label; if (Value != null) { name += " (" + Value.ToString() + ")"; } string driven = IsDriven ? "driven" : "undriven"; string cyclic = IsCyclic ? "cyclic" : "noncyclic"; string hold = Hold ? "hold" : "nonhold"; return(name + " [" + driven + ";" + cyclic + ";" + hold + "]"); }
public ReadOnlyUrl GetUrl(ReadOnlyUrl clientUrl) { var instanceId = GetInstanceId(clientUrl); if (instanceId == null || instanceId.Value != InstanceId) { var url = clientUrl.AsNonReadOnly(); url.QueryString.Remove("instanceId"); url.QueryString["instanceId"] = InstanceId.ToString(); return(url); } return(clientUrl); }
public override string ToString() { var s = new StringBuilder() .AppendLine(WorkoutId.ToString()) .AppendLine(InstanceId.ToString()) .AppendLine(WorkoutStarted.ToString()) .AppendLine(WorkoutEnded.ToString()); foreach (var score in Scores) { s.AppendLine(score.ToString()); } return(s.ToString()); }
/// <summary> /// Adds seelcted values to global DynamicData parms dict, ref for clarity that it mutates the values /// </summary> /// <param name="dynamicData"></param> void AddStartInfoToDynamicData(ref Dictionary <string, string> dynamicData) { if (dynamicData == null) { dynamicData = new Dictionary <string, string>(); } string name = "PlanStartInfo_"; dynamicData[$"{name}{nameof( Name )}"] = Name; dynamicData[$"{name}{nameof( UniqueName )}"] = UniqueName; dynamicData[$"{name}{nameof( IsActive )}"] = IsActive.ToString(); dynamicData[$"{name}{nameof( InstanceId )}"] = InstanceId.ToString(); dynamicData[$"{name}{nameof( StartInfo.RequestNumber )}"] = StartInfo.RequestNumber; dynamicData[$"{name}{nameof( StartInfo.RequestUser )}"] = StartInfo.RequestUser; }
// -------------------------------------------------------------------- public virtual void WriteXml(XmlWriter writer) { writer.WriteStartElement("SceneObject"); writer.WriteAttributeString("id", Id); writer.WriteAttributeString("instanceId", InstanceId.ToString()); Transform.WriteXml(writer); foreach (Component c in Components) { c.WriteXml(writer); } for (int i = 0; i < ChildCount; ++i) { GetChild(i).WriteXml(writer); } writer.WriteEndElement(); }
private IEnumerable <ValidationFailure> ValidateOffline(string xmlText) { try { var license = License.Core.License.Load(xmlText); var validationFailures = Enumerable.Empty <ValidationFailure>(); if (license.Type == LicenseType.Commercial) { validationFailures = license.Validate() .Signature(publicKey) .And().Id(InstanceId.ToString()) .And().ExpirationDate() .And().Cores(Environment.ProcessorCount) .AssertValidLicense() .ToList(); } else { validationFailures = license.Validate() .Signature(publicKey) .And().Id(InstanceId.ToString()) .AssertValidLicense() .ToList(); } return(validationFailures); } catch (XmlException ex) { return(new List <ValidationFailure>() { new ValidationFailure() { Message = "Invaid XML format", HowToResolve = ex.Message } }); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldLogFirstHeartbeatAfterTimeout() public virtual void ShouldLogFirstHeartbeatAfterTimeout() { // given InstanceId instanceId = new InstanceId(1); InstanceId otherInstance = new InstanceId(2); ClusterConfiguration configuration = new ClusterConfiguration("whatever", NullLogProvider.Instance, "cluster://1", "cluster://2"); configuration.Members[otherInstance] = URI.create("cluster://2"); AssertableLogProvider internalLog = new AssertableLogProvider(true); TimeoutStrategy timeoutStrategy = mock(typeof(TimeoutStrategy)); Timeouts timeouts = new Timeouts(timeoutStrategy); Config config = mock(typeof(Config)); when(config.Get(ClusterSettings.max_acceptors)).thenReturn(10); MultiPaxosContext context = new MultiPaxosContext(instanceId, iterable(new ElectionRole("coordinator")), configuration, mock(typeof(Executor)), internalLog, mock(typeof(ObjectInputStreamFactory)), mock(typeof(ObjectOutputStreamFactory)), mock(typeof(AcceptorInstanceStore)), timeouts, mock(typeof(ElectionCredentialsProvider)), config); StateMachines stateMachines = new StateMachines(internalLog, mock(typeof(StateMachines.Monitor)), mock(typeof(MessageSource)), mock(typeof(MessageSender)), timeouts, mock(typeof(DelayedDirectExecutor)), ThreadStart.run, instanceId); stateMachines.AddStateMachine(new StateMachine(context.HeartbeatContext, typeof(HeartbeatMessage), HeartbeatState.Start, internalLog)); timeouts.Tick(0); when(timeoutStrategy.TimeoutFor(any(typeof(Message)))).thenReturn(5L); // when stateMachines.Process(Message.@internal(HeartbeatMessage.Join)); stateMachines.Process(Message.@internal(HeartbeatMessage.IAmAlive, new HeartbeatMessage.IAmAliveState(otherInstance)).setHeader(Message.HEADER_CREATED_BY, otherInstance.ToString())); for (int i = 1; i <= 15; i++) { timeouts.Tick(i); } // then verify(timeoutStrategy, times(3)).timeoutTriggered(argThat(new MessageArgumentMatcher <>() .onMessageType(HeartbeatMessage.TimedOut))); internalLog.AssertExactly(inLog(typeof(HeartbeatState)).debug("Received timed out for server 2"), inLog(typeof(HeartbeatContext)).info("1(me) is now suspecting 2"), inLog(typeof(HeartbeatState)).debug("Received timed out for server 2"), inLog(typeof(HeartbeatState)).debug("Received timed out for server 2")); internalLog.Clear(); // when stateMachines.Process(Message.@internal(HeartbeatMessage.IAmAlive, new HeartbeatMessage.IAmAliveState(otherInstance)).setHeader(Message.HEADER_CREATED_BY, otherInstance.ToString())); // then internalLog.AssertExactly(inLog(typeof(HeartbeatState)).debug("Received i_am_alive[2] after missing 3 (15ms)")); }
// initializes a new scope private Scope(ScopeProvider scopeProvider, ILogger logger, FileSystems fileSystems, Scope parent, ScopeContext scopeContext, bool detachable, IsolationLevel isolationLevel = IsolationLevel.Unspecified, RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified, IEventDispatcher eventDispatcher = null, bool?scopeFileSystems = null, bool callContext = false, bool autoComplete = false) { _scopeProvider = scopeProvider; _logger = logger; Context = scopeContext; _isolationLevel = isolationLevel; _repositoryCacheMode = repositoryCacheMode; _eventDispatcher = eventDispatcher; _scopeFileSystem = scopeFileSystems; _callContext = callContext; _autoComplete = autoComplete; Detachable = detachable; #if DEBUG_SCOPES _scopeProvider.RegisterScope(this); Console.WriteLine("create " + InstanceId.ToString("N").Substring(0, 8)); #endif if (detachable) { if (parent != null) { throw new ArgumentException("Cannot set parent on detachable scope.", nameof(parent)); } if (scopeContext != null) { throw new ArgumentException("Cannot set context on detachable scope.", nameof(scopeContext)); } if (autoComplete) { throw new ArgumentException("Cannot auto-complete a detachable scope.", nameof(autoComplete)); } // detachable creates its own scope context Context = new ScopeContext(); // see note below if (scopeFileSystems == true) { _fscope = fileSystems.Shadow(); } return; } if (parent != null) { ParentScope = parent; // cannot specify a different mode! // TODO: means that it's OK to go from L2 to None for reading purposes, but writing would be BAD! // this is for XmlStore that wants to bypass caches when rebuilding XML (same for NuCache) if (repositoryCacheMode != RepositoryCacheMode.Unspecified && parent.RepositoryCacheMode > repositoryCacheMode) { throw new ArgumentException($"Value '{repositoryCacheMode}' cannot be lower than parent value '{parent.RepositoryCacheMode}'.", nameof(repositoryCacheMode)); } // cannot specify a dispatcher! if (_eventDispatcher != null) { throw new ArgumentException("Value cannot be specified on nested scope.", nameof(eventDispatcher)); } // cannot specify a different fs scope! // can be 'true' only on outer scope (and false does not make much sense) if (scopeFileSystems != null && parent._scopeFileSystem != scopeFileSystems) { throw new ArgumentException($"Value '{scopeFileSystems.Value}' be different from parent value '{parent._scopeFileSystem}'.", nameof(scopeFileSystems)); } } else { // the FS scope cannot be "on demand" like the rest, because we would need to hook into // every scoped FS to trigger the creation of shadow FS "on demand", and that would be // pretty pointless since if scopeFileSystems is true, we *know* we want to shadow if (scopeFileSystems == true) { _fscope = fileSystems.Shadow(); } } }
public override string ToString() { return(string.Format("MemberIsAvailable[ Role: {0}, InstanceId: {1}, Role URI: {2}, Cluster URI: {3}]", _role, _instanceId.ToString(), _roleUri.ToString(), _clusterUri.ToString())); }
public void SetHostBox(Box box) { Box = box; _titleBrowser.Source = new Uri("http://localhost:4300/Titlebar/" + InstanceId.ToString()); }
private void CompleteInitObject() { var CurrOrganization = Micajah.Common.Bll.Providers.OrganizationProvider.GetOrganization(m_OrganizationId); byte _graceDays = (byte)CurrOrganization.GraceDays; DateTime _expire = DateTime.UtcNow.AddMonths(1); if (CurrOrganization.ExpirationTime != null) { _expire = (DateTime)CurrOrganization.ExpirationTime; } DateTime _now = DateTime.UtcNow; _expire = _expire.AddDays(_graceDays); if (_expire < _now) { throw new HttpError(HttpStatusCode.Forbidden, "Your organization's account has expired or inactivated. Contact SherpaDesk for assistance. Email: [email protected] Phone: +1 (866) 996-1200, then press 2"); } DataRow _row = bigWebApps.bigWebDesk.Data.Companies.SelectOne(m_OrganizationId, m_InstanceId); if (_row == null) { throw new HttpError(HttpStatusCode.NotFound, "Can't find department for OrganizationId/InstanceId=" + OrganizationId.ToString() + "/" + InstanceId.ToString()); } m_DepartmentId = (int)_row["company_id"]; m_DepartmentName = _row["company_name"].ToString(); int _userStatus = Logins.SelectLoginExists(m_OrganizationId, m_DepartmentId, m_LoginEmail, out m_UserId, out m_AccountId); if (_userStatus == 1) { throw new HttpError(HttpStatusCode.NotFound, "Can't find User \"" + m_LoginEmail + "\" in the bigWebApps database."); } else if (_userStatus == 2) { throw new HttpError(HttpStatusCode.Forbidden, "User \"" + m_LoginEmail + "\" is not associated with OrganizationId/InstanceId=" + OrganizationId.ToString() + "/" + InstanceId.ToString() + "."); } _row = Logins.SelectUserDetails(m_OrganizationId, m_DepartmentId, m_UserId); if (_row == null) { throw new HttpError(HttpStatusCode.Forbidden, "The user account is not associated with this Department."); } if ((bool)_row["btUserInactive"]) { throw new HttpError(HttpStatusCode.Forbidden, "The user account is Inactive in this Department."); } m_Skype = _row["Skype"].ToString(); m_AccountName = ((string)_row["AccountName"]); if (string.IsNullOrWhiteSpace(m_AccountName)) { m_AccountName = m_DepartmentName; } Micajah.Common.Dal.ClientDataSet.UserRow _uRow = UserProvider.GetUserRow(m_LoginEmail, m_OrganizationId); string TimeZoneId = null; if (_uRow != null) { m_TimeFormat = _uRow.IsTimeFormatNull() ? 0 : _uRow.TimeFormat; m_DateFormat = _uRow.IsTimeFormatNull() ? 0 : _uRow.DateFormat; if (!_uRow.IsTimeFormatNull()) { TimeZoneId = _uRow.TimeZoneId; } UpdateLastLoginDate(m_OrganizationId, _uRow.UserId); } if (string.IsNullOrEmpty(TimeZoneId) && !_row.IsNull("InstanceTimeZoneId")) { TimeZoneId = _row["InstanceTimeZoneId"].ToString(); } try { m_TimeZoneOffset = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId).GetUtcOffset(new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero)).Hours; m_TimeZoneId = TimeZoneId; } catch { m_TimeZoneOffset = DefaultTimeZoneOffset; } if (!_row.IsNull("tintTicketTimer")) { m_tintTicketTimer = (byte)_row["tintTicketTimer"]; } else { m_tintTicketTimer = (byte)_row["tintDTicketTimer"]; } bool isOrgAdmin = _row.Get <bool?>("OrganizationAdministrator") ?? false; m_IsUseWorkDaysTimer = tintTicketTimer > 0; int userType = (int)_row ["UserType_Id"]; if (userType == 2 || userType == 3 || userType == 6 || isOrgAdmin) { m_IsTechAdmin = true; } if (userType == 3 || isOrgAdmin) { m_IsAdmin = true; } m_Roles[0] = userType == 3 ? "admin" : ""; m_Roles[0] = userType == 5 ? "super" : m_Roles[0]; m_Role = (bigWebApps.bigWebDesk.UserAuth.UserRole)Enum.Parse(typeof(bigWebApps.bigWebDesk.UserAuth.UserRole), userType.ToString()); m_OrganizationLogoImageUrl = BWA.Api.Models.Files.GetOrganizationLogoUrl(OrganizationId); m_InstanceLogoImageUrl = BWA.Api.Models.Files.GetInstanceLogoUrl(m_InstanceId); bigWebApps.bigWebDesk.Data.Logins.UpdateUserLastLoginDate(m_OrganizationId, m_UserId); }
/// <summary> /// Converts this <see cref="PageText"/> control to it's html representation /// </summary> /// <param name="controlIndex">The sequence of the control inside the section</param> /// <returns>Html representation of this <see cref="PageText"/> control</returns> public override string ToHtml(float controlIndex) { // Can this control be hosted in this section type? if (Section.Type == CanvasSectionTemplate.OneColumnFullWidth) { throw new ClientException(ErrorType.Unsupported, PnPCoreResources.Exception_Page_ControlNotAllowedInFullWidthSection); } // Obtain the json data TextControlData controlData = new TextControlData() { ControlType = ControlType, Id = InstanceId.ToString("D"), Position = new CanvasControlPosition() { ZoneIndex = Section.Order, SectionIndex = Column.Order, SectionFactor = Column.ColumnFactor, LayoutIndex = Column.LayoutIndex, ControlIndex = controlIndex, }, Emphasis = new SectionEmphasis() { ZoneEmphasis = Column.VerticalSectionEmphasis ?? Section.ZoneEmphasis, }, EditorType = "CKEditor" }; // Persist the collapsible section settings if (Section.Collapsible) { controlData.ZoneGroupMetadata = new SectionZoneGroupMetadata() { // Set section type to 1 if it was not set (when new sections are added via code) Type = (Section as CanvasSection).SectionType == 0 ? 1 : (Section as CanvasSection).SectionType, DisplayName = Section.DisplayName, IsExpanded = Section.IsExpanded, ShowDividerLine = Section.ShowDividerLine, }; if (Section.IconAlignment.HasValue) { controlData.ZoneGroupMetadata.IconAlignment = Section.IconAlignment.Value.ToString().ToLower(); } else { controlData.ZoneGroupMetadata.IconAlignment = "true"; } } if (section.Type == CanvasSectionTemplate.OneColumnVerticalSection) { if (section.Columns.First().Equals(Column)) { controlData.Position.SectionFactor = 12; } } jsonControlData = JsonSerializer.Serialize(controlData); try { var nodeList = new HtmlParser().ParseFragment(Text, null); PreviewText = string.Concat(nodeList.Select(x => x.Text())); } catch { } StringBuilder html = new StringBuilder(); html.Append($@"<div {CanvasControlAttribute}=""{CanvasControlData}"" {CanvasDataVersionAttribute}=""{ DataVersion}"" {ControlDataAttribute}=""{jsonControlData.Replace("\"", """)}"">"); html.Append($@"<div {TextRteAttribute}=""{Rte}"">"); if (Text.Trim().StartsWith("<p>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h1>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h2>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h3>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h4>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<ul>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<blockquote>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<pre>", StringComparison.InvariantCultureIgnoreCase)) { html.Append(Text); } else { html.Append($@"<p>{Text}</p>"); } html.Append("</div>"); html.Append("</div>"); return(html.ToString()); }
public override string ToString() { return(string.Format("MemberIsUnavailable[ Role: {0}, InstanceId: {1}, ClusterURI: {2} ]", _role, _instanceId.ToString(), (_clusterUri == null) ? null : _clusterUri.ToString())); }
public StateMachineConversations(InstanceId me) { _serverId = me.ToString(); }
private void CompleteInitObject() { var CurrOrganization = Micajah.Common.Bll.Providers.OrganizationProvider.GetOrganization(m_OrganizationId); byte _graceDays = (byte)CurrOrganization.GraceDays; DateTime _expire = DateTime.UtcNow.AddMonths(1); if (CurrOrganization.ExpirationTime != null) { _expire = (DateTime)CurrOrganization.ExpirationTime; } DateTime _now = DateTime.UtcNow; _expire = _expire.AddDays(_graceDays); if (_expire < _now) { throw new HttpError(HttpStatusCode.Forbidden, "Your organization's account has expired."); } DataRow _row = bigWebApps.bigWebDesk.Data.Companies.SelectOne(m_OrganizationId, m_InstanceId); if (_row == null) { throw new HttpError(HttpStatusCode.NotFound, "Can't find department for OrganizationId/InstanceId=" + OrganizationId.ToString() + "/" + InstanceId.ToString()); } m_DepartmentId = (int)_row["company_id"]; int _userStatus = Logins.SelectLoginExists(m_OrganizationId, m_DepartmentId, m_LoginEmail, out m_UserId, out m_AccountId); if (_userStatus == 1) { throw new HttpError(HttpStatusCode.NotFound, "Can't find User \"" + m_LoginEmail + "\" in the bigWebApps database."); } else if (_userStatus == 2) { throw new HttpError(HttpStatusCode.Forbidden, "User \"" + m_LoginEmail + "\" is not associated with OrganizationId/InstanceId=" + OrganizationId.ToString() + "/" + InstanceId.ToString() + "."); } _row = Logins.SelectUserDetails(m_OrganizationId, m_DepartmentId, m_UserId); if (_row == null) { throw new HttpError(HttpStatusCode.Forbidden, "The user account is not associated with this Department."); } Micajah.Common.Dal.OrganizationDataSet.UserRow _uRow = UserProvider.GetUserRow(m_LoginEmail); string TimeZoneId = null; if (_uRow != null && !_uRow.IsTimeFormatNull()) { TimeZoneId = _uRow.TimeZoneId; } if (string.IsNullOrEmpty(TimeZoneId) && !_row.IsNull("InstanceTimeZoneId")) { TimeZoneId = _row["InstanceTimeZoneId"].ToString(); } try { m_TimeZoneOffset = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId).BaseUtcOffset.Hours; m_TimeZoneId = TimeZoneId; } catch { m_TimeZoneOffset = DefaultTimeZoneOffset; } if ((bool)_row["btUserInactive"]) { throw new HttpError(HttpStatusCode.Forbidden, "The user account is Inactive in this Department."); } if (!_row.IsNull("tintTicketTimer")) { m_IsUseWorkDaysTimer = (byte)_row["tintTicketTimer"] > 0; } else { m_IsUseWorkDaysTimer = (byte)_row["tintDTicketTimer"] > 0; } if ((int)_row["UserType_Id"] == 2 || (int)_row["UserType_Id"] == 3) { m_IsTechAdmin = true; } }
/// <summary> /// Returns a HTML representation of the client side web part /// </summary> /// <param name="controlIndex">The sequence of the control inside the section</param> /// <returns>HTML representation of the client side web part</returns> public override string ToHtml(float controlIndex) { if (!IsHeaderControl) { // Can this control be hosted in this section type? if (Section.Type == CanvasSectionTemplate.OneColumnFullWidth) { if (!SupportsFullBleed) { throw new ClientException(ErrorType.Unsupported, PnPCoreResources.Exception_Page_ControlNotAllowedInFullWidthSection); } } WebPartControlData controlData; if (UsingSpControlDataOnly) { controlData = new WebPartControlDataOnly(); } else { controlData = new WebPartControlData(); } // Obtain the json data controlData.ControlType = ControlType; controlData.Id = InstanceId.ToString("D"); controlData.WebPartId = WebPartId; controlData.Position = new CanvasControlPosition() { ZoneIndex = Section.Order, SectionIndex = Column.Order, SectionFactor = Column.ColumnFactor, LayoutIndex = Column.LayoutIndex, ControlIndex = controlIndex, }; if (section.Type == CanvasSectionTemplate.OneColumnVerticalSection) { if (section.Columns.First().Equals(Column)) { controlData.Position.SectionFactor = 12; } } controlData.Emphasis = new SectionEmphasis() { ZoneEmphasis = Column.VerticalSectionEmphasis.HasValue ? Column.VerticalSectionEmphasis.Value : Section.ZoneEmphasis, }; // Set the control's data version to the latest version...default was 1.0, but some controls use a higher version var webPartType = Page.IdToDefaultWebPart(controlData.WebPartId); // if we read the control from the page then the value might already be set to something different than 1.0...if so, leave as is if (DataVersion == "1.0") { if (webPartType == DefaultWebPart.Image) { dataVersion = "1.8"; } else if (webPartType == DefaultWebPart.ImageGallery) { dataVersion = "1.6"; } else if (webPartType == DefaultWebPart.People) { dataVersion = "1.2"; } else if (webPartType == DefaultWebPart.DocumentEmbed) { dataVersion = "1.1"; } else if (webPartType == DefaultWebPart.ContentRollup) { dataVersion = "2.1"; } else if (webPartType == DefaultWebPart.QuickLinks) { dataVersion = "2.0"; } } // Set the web part preview image url if (ServerProcessedContent.TryGetProperty("imageSources", out JsonElement imageSources)) { foreach (var property in imageSources.EnumerateObject()) { if (!string.IsNullOrEmpty(property.Value.ToString())) { WebPartPreviewImage = property.Value.ToString().ToLower(); break; } } } WebPartData webpartData = new WebPartData() { Id = controlData.WebPartId, InstanceId = controlData.Id, Title = Title, Description = Description, DataVersion = DataVersion, Properties = "jsonPropsToReplacePnPRules", DynamicDataPaths = "jsonDynamicDataPathsToReplacePnPRules", DynamicDataValues = "jsonDynamicDataValuesToReplacePnPRules", ServerProcessedContent = "jsonServerProcessedContentToReplacePnPRules" }; if (UsingSpControlDataOnly) { (controlData as WebPartControlDataOnly).WebPartData = "jsonWebPartDataToReplacePnPRules"; jsonControlData = JsonSerializer.Serialize(controlData); JsonWebPartData = JsonSerializer.Serialize(webpartData); JsonWebPartData = JsonWebPartData.Replace("\"jsonPropsToReplacePnPRules\"", Properties.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonServerProcessedContentToReplacePnPRules\"", ServerProcessedContent.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonDynamicDataPathsToReplacePnPRules\"", DynamicDataPaths.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonDynamicDataValuesToReplacePnPRules\"", DynamicDataValues.ToString()); jsonControlData = jsonControlData.Replace("\"jsonWebPartDataToReplacePnPRules\"", JsonWebPartData); } else { jsonControlData = JsonSerializer.Serialize(controlData); JsonWebPartData = JsonSerializer.Serialize(webpartData); JsonWebPartData = JsonWebPartData.Replace("\"jsonPropsToReplacePnPRules\"", Properties.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonServerProcessedContentToReplacePnPRules\"", ServerProcessedContent.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonDynamicDataPathsToReplacePnPRules\"", DynamicDataPaths.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonDynamicDataValuesToReplacePnPRules\"", DynamicDataValues.ToString()); } } else { HeaderControlData webpartData = new HeaderControlData() { Id = WebPartId, InstanceId = InstanceId.ToString("D"), Title = Title, Description = Description, DataVersion = DataVersion, Properties = "jsonPropsToReplacePnPRules", ServerProcessedContent = "jsonServerProcessedContentToReplacePnPRules" }; canvasDataVersion = DataVersion; JsonWebPartData = JsonSerializer.Serialize(webpartData); JsonWebPartData = JsonWebPartData.Replace("\"jsonPropsToReplacePnPRules\"", Properties.ToString()); JsonWebPartData = JsonWebPartData.Replace("\"jsonServerProcessedContentToReplacePnPRules\"", ServerProcessedContent.ToString()); jsonControlData = JsonWebPartData; } StringBuilder html = new StringBuilder(100); if (UsingSpControlDataOnly || IsHeaderControl) { html.Append($@"<div {CanvasControlAttribute}=""{CanvasControlData}"" {CanvasDataVersionAttribute}=""{DataVersion}"" {ControlDataAttribute}=""{JsonControlData.Replace("\"", """)}""></div>"); } else { html.Append($@"<div {CanvasControlAttribute}=""{CanvasControlData}"" {CanvasDataVersionAttribute}=""{DataVersion}"" {ControlDataAttribute}=""{JsonControlData.Replace("\"", """)}"">"); html.Append($@"<div {WebPartAttribute}=""{WebPartData}"" {WebPartDataVersionAttribute}=""{DataVersion}"" {WebPartDataAttribute}=""{JsonWebPartData.Replace("\"", """).Replace("<", "<").Replace(">", ">")}"">"); html.Append($@"<div {WebPartComponentIdAttribute}="""">"); html.Append(WebPartId); html.Append("</div>"); html.Append($@"<div {WebPartHtmlPropertiesAttribute}=""{HtmlProperties}"">"); RenderHtmlProperties(ref html); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); } return(html.ToString()); }
/// <summary> /// Constructs the timed scope correlation data /// </summary> /// <returns>Correlation data</returns> private CorrelationData ConstructCorrelationDataEntries(IMachineInformation machineInformation) { CorrelationData correlationData = TimedScopeData; CorrelationData scopeData = TimedScopeData.Clone(); scopeData.AddData(TimedScopeDataKeys.InternalOnly.ScopeName, Name); scopeData.AddData(TimedScopeDataKeys.InternalOnly.InstanceId, InstanceId.ToString()); scopeData.AddData(TimedScopeDataKeys.InternalOnly.IsSuccessful, IsSuccessful.HasValue ? IsSuccessful.Value.ToString() : bool.FalseString); scopeData.AddData(TimedScopeDataKeys.InternalOnly.IsRoot, IsRoot.ToString()); scopeData.AddData(TimedScopeDataKeys.InternalOnly.ScopeResult, Result.ToString()); bool isFailed = !IsSuccessful ?? false; if (isFailed && FailureDescription != null) { scopeData.AddData(TimedScopeDataKeys.InternalOnly.FailureDescription, FailureDescription.ToString()); } scopeData.AddData(TimedScopeDataKeys.InternalOnly.Duration, DurationInMilliseconds.ToString(CultureInfo.InvariantCulture)); long sequenceNumber = correlationData == null ? 0 : correlationData.NextEventSequenceNumber(); scopeData.AddData(TimedScopeDataKeys.InternalOnly.SequenceNumber, sequenceNumber.ToString(CultureInfo.InvariantCulture)); scopeData.AddData(TimedScopeDataKeys.InternalOnly.CallDepth, correlationData == null ? "0" : correlationData.CallDepth.ToString(CultureInfo.InvariantCulture)); IMachineInformation machineInfo = machineInformation; if (machineInfo != null) { scopeData.AddData(TimedScopeDataKeys.InternalOnly.MachineId, machineInfo.MachineId); scopeData.AddData(TimedScopeDataKeys.InternalOnly.MachineCluster, machineInfo.MachineCluster); scopeData.AddData(TimedScopeDataKeys.InternalOnly.MachineRole, machineInfo.MachineRole); scopeData.AddData(TimedScopeDataKeys.InternalOnly.AgentName, machineInfo.AgentName); } // if the user hash has been set, add it to the scope data if (!string.IsNullOrWhiteSpace(m_userHashOverride)) { ULSLogging.LogTraceTag(0x23817500 /* tag_96xua */, Categories.TimingGeneral, Levels.Verbose, "Overriding user hash metadata in the Timed Scope '{0}' with value '{1}'", Name, m_userHashOverride); scopeData.AddData(TimedScopeDataKeys.InternalOnly.UserHash, m_userHashOverride); } else if (correlationData != null && !string.IsNullOrWhiteSpace(correlationData.UserHash)) { scopeData.AddData(TimedScopeDataKeys.InternalOnly.UserHash, correlationData.UserHash); } // capture performance metrics if (PerfDiagnostics != null && PerfDiagnostics.LastStatus) { scopeData.AddData(TimedScopeDataKeys.InternalOnly.CpuCycles, PerfDiagnostics.CyclesUsed.ToString(CultureInfo.InvariantCulture)); scopeData.AddData(TimedScopeDataKeys.InternalOnly.UserModeDuration, PerfDiagnostics.UserModeMilliseconds.ToString(CultureInfo.InvariantCulture)); scopeData.AddData(TimedScopeDataKeys.InternalOnly.KernelModeDuration, PerfDiagnostics.KernelModeMilliseconds.ToString(CultureInfo.InvariantCulture)); scopeData.AddData(TimedScopeDataKeys.InternalOnly.HttpRequestCount, PerfDiagnostics.HttpRequestCount.ToString(CultureInfo.InvariantCulture)); scopeData.AddData(TimedScopeDataKeys.InternalOnly.ServiceCallCount, PerfDiagnostics.ServiceCallCount.ToString(CultureInfo.InvariantCulture)); } return(scopeData); }
/// <summary> /// Converts this <see cref="PageText"/> control to it's html representation /// </summary> /// <param name="controlIndex">The sequence of the control inside the section</param> /// <returns>Html representation of this <see cref="PageText"/> control</returns> public override string ToHtml(float controlIndex) { // Can this control be hosted in this section type? if (Section.Type == CanvasSectionTemplate.OneColumnFullWidth) { throw new ClientException(ErrorType.Unsupported, PnPCoreResources.Exception_Page_ControlNotAllowedInFullWidthSection); } // Obtain the json data TextControlData controlData = new TextControlData() { ControlType = ControlType, Id = InstanceId.ToString("D"), Position = new CanvasControlPosition() { ZoneIndex = Section.Order, SectionIndex = Column.Order, SectionFactor = Column.ColumnFactor, LayoutIndex = Column.LayoutIndex, ControlIndex = controlIndex, }, Emphasis = new SectionEmphasis() { ZoneEmphasis = Column.VerticalSectionEmphasis ?? Section.ZoneEmphasis, }, EditorType = "CKEditor" }; if (section.Type == CanvasSectionTemplate.OneColumnVerticalSection) { if (section.Columns.First().Equals(Column)) { controlData.Position.SectionFactor = 12; } } jsonControlData = JsonSerializer.Serialize(controlData); try { var nodeList = new HtmlParser().ParseFragment(Text, null); PreviewText = string.Concat(nodeList.Select(x => x.Text())); } #pragma warning disable CA1031 // Do not catch general exception types catch { } #pragma warning restore CA1031 // Do not catch general exception types StringBuilder html = new StringBuilder(100); html.Append($@"<div {CanvasControlAttribute}=""{CanvasControlData}"" {CanvasDataVersionAttribute}=""{ DataVersion}"" {ControlDataAttribute}=""{jsonControlData.Replace("\"", """)}"">"); html.Append($@"<div {TextRteAttribute}=""{Rte}"">"); if (Text.Trim().StartsWith("<p>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h1>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h2>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h3>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<h4>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<ul>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<blockquote>", StringComparison.InvariantCultureIgnoreCase) || Text.Trim().StartsWith("<pre>", StringComparison.InvariantCultureIgnoreCase)) { html.Append(Text); } else { html.Append($@"<p>{Text}</p>"); } html.Append("</div>"); html.Append("</div>"); return(html.ToString()); }
public override string ToString() { return(InstanceId.ToString()); }
public void RunAsync() { var ctx = System.Threading.SynchronizationContext.Current; System.Threading.ThreadPool.QueueUserWorkItem(state => { var client = new WebClient(); var data = new JObject(); data["instanceId"] = InstanceId.ToString("N"); data["ports"] = new JArray(Ports); var succeeded = false; var stopwatch = new System.Diagnostics.Stopwatch(); string response_body = null; try { stopwatch.Start(); var body = System.Text.Encoding.UTF8.GetBytes(data.ToString()); response_body = System.Text.Encoding.UTF8.GetString(client.UploadData(Target, body)); stopwatch.Stop(); succeeded = true; var response = JToken.Parse(response_body); var response_ports = response["ports"].Select(token => (int)token); if (PortCheckCompleted != null) { ctx.Post(s => { PortCheckCompleted( this, new PortCheckCompletedEventArgs( succeeded, response_ports.ToArray(), stopwatch.Elapsed)); }, null); } } catch (WebException) { succeeded = false; if (PortCheckCompleted != null) { ctx.Post(s => { PortCheckCompleted( this, new PortCheckCompletedEventArgs( succeeded, null, stopwatch.Elapsed)); }, null); } } catch (Newtonsoft.Json.JsonReaderException) { succeeded = false; if (PortCheckCompleted != null) { ctx.Post(s => { PortCheckCompleted( this, new PortCheckCompletedEventArgs( succeeded, null, stopwatch.Elapsed)); }, null); } } }); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void WhenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient() { InstanceId me = new InstanceId(1); StoreId storeId = newStoreIdForCurrentVersion(); HighAvailabilityMemberContext context = mock(typeof(HighAvailabilityMemberContext)); when(context.MyId).thenReturn(me); AvailabilityGuard guard = mock(typeof(DatabaseAvailabilityGuard)); ObservedClusterMembers members = mock(typeof(ObservedClusterMembers)); ClusterMember masterMember = mock(typeof(ClusterMember)); when(masterMember.HARole).thenReturn("master"); when(masterMember.HasRole("master")).thenReturn(true); when(masterMember.InstanceId).thenReturn(new InstanceId(2)); when(masterMember.StoreId).thenReturn(storeId); ClusterMember self = new ClusterMember(me); when(members.Members).thenReturn(Arrays.asList(self, masterMember)); when(members.CurrentMember).thenReturn(self); DependencyResolver dependencyResolver = mock(typeof(DependencyResolver)); FileSystemAbstraction fs = mock(typeof(FileSystemAbstraction)); when(fs.FileExists(any(typeof(File)))).thenReturn(true); when(dependencyResolver.ResolveDependency(typeof(FileSystemAbstraction))).thenReturn(fs); when(dependencyResolver.ResolveDependency(typeof(Monitors))).thenReturn(new Monitors()); NeoStoreDataSource dataSource = mock(typeof(NeoStoreDataSource)); when(dataSource.DependencyResolver).thenReturn(dependencyResolver); when(dataSource.StoreId).thenReturn(storeId); when(dependencyResolver.ResolveDependency(typeof(NeoStoreDataSource))).thenReturn(dataSource); when(dependencyResolver.ResolveDependency(typeof(TransactionIdStore))).thenReturn(new SimpleTransactionIdStore()); when(dependencyResolver.ResolveDependency(typeof(ObservedClusterMembers))).thenReturn(members); UpdatePuller updatePuller = mock(typeof(UpdatePuller)); when(updatePuller.TryPullUpdates()).thenReturn(true); when(dependencyResolver.ResolveDependency(typeof(UpdatePuller))).thenReturn(updatePuller); ClusterMemberAvailability clusterMemberAvailability = mock(typeof(ClusterMemberAvailability)); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final TriggerableClusterMemberEvents events = new TriggerableClusterMemberEvents(); TriggerableClusterMemberEvents events = new TriggerableClusterMemberEvents(); Election election = mock(typeof(Election)); HighAvailabilityMemberStateMachine stateMachine = new HighAvailabilityMemberStateMachine(context, guard, members, events, election, NullLogProvider.Instance); ClusterMembers clusterMembers = new ClusterMembers(members, stateMachine); when(dependencyResolver.ResolveDependency(typeof(ClusterMembers))).thenReturn(clusterMembers); stateMachine.Init(); stateMachine.Start(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.kernel.ha.DelegateInvocationHandler<org.neo4j.kernel.ha.com.master.Master> handler = new org.neo4j.kernel.ha.DelegateInvocationHandler<>(org.neo4j.kernel.ha.com.master.Master.class); DelegateInvocationHandler <Master> handler = new DelegateInvocationHandler <Master>(typeof(Master)); MasterClientResolver masterClientResolver = mock(typeof(MasterClientResolver)); MasterClient masterClient = mock(typeof(MasterClient)); when(masterClient.ProtocolVersion).thenReturn(MasterClient214.PROTOCOL_VERSION); when(masterClient.Handshake(anyLong(), any(typeof(StoreId)))).thenReturn(new ResponseAnonymousInnerClass(this, storeId, mock(typeof(ResourceReleaser)), handler)); when(masterClient.ToString()).thenReturn("TheExpectedMasterClient!"); when(masterClientResolver.Instantiate(anyString(), anyInt(), anyString(), any(typeof(Monitors)), any(typeof(StoreId)), any(typeof(LifeSupport)))).thenReturn(masterClient); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(2); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(2); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean switchedSuccessfully = new java.util.concurrent.atomic.AtomicBoolean(); AtomicBoolean switchedSuccessfully = new AtomicBoolean(); SwitchToSlave.Monitor monitor = new MonitorAnonymousInnerClass(this, latch, switchedSuccessfully); Config config = Config.defaults(ClusterSettings.server_id, me.ToString()); DatabaseTransactionStats transactionCounters = mock(typeof(DatabaseTransactionStats)); when(transactionCounters.NumberOfActiveTransactions).thenReturn(0L); PageCache pageCacheMock = mock(typeof(PageCache)); PagedFile pagedFileMock = mock(typeof(PagedFile)); when(pagedFileMock.LastPageId).thenReturn(1L); when(pageCacheMock.Map(any(typeof(File)), anyInt())).thenReturn(pagedFileMock); TransactionIdStore transactionIdStoreMock = mock(typeof(TransactionIdStore)); when(transactionIdStoreMock.LastCommittedTransaction).thenReturn(new TransactionId(0, 0, 0)); SwitchToSlaveCopyThenBranch switchToSlave = new SwitchToSlaveCopyThenBranch(DatabaseLayout.of(new File("")), NullLogService.Instance, mock(typeof(FileSystemAbstraction)), config, mock(typeof(HaIdGeneratorFactory)), handler, mock(typeof(ClusterMemberAvailability)), mock(typeof(RequestContextFactory)), mock(typeof(PullerFactory), RETURNS_MOCKS), Iterables.empty(), masterClientResolver, monitor, new Org.Neo4j.com.storecopy.StoreCopyClientMonitor_Adapter(), Suppliers.singleton(dataSource), Suppliers.singleton(transactionIdStoreMock), slave => { SlaveServer mock = mock(typeof(SlaveServer)); when(mock.SocketAddress).thenReturn(new InetSocketAddress("localhost", 123)); return(mock); }, updatePuller, pageCacheMock, mock(typeof(Monitors)), () => transactionCounters); ComponentSwitcherContainer switcherContainer = new ComponentSwitcherContainer(); HighAvailabilityModeSwitcher haModeSwitcher = new HighAvailabilityModeSwitcher(switchToSlave, mock(typeof(SwitchToMaster)), election, clusterMemberAvailability, mock(typeof(ClusterClient)), storeSupplierMock(), me, switcherContainer, NeoStoreDataSourceSupplierMock(), NullLogService.Instance); haModeSwitcher.Init(); haModeSwitcher.Start(); haModeSwitcher.ListeningAt(URI.create("http://localhost:12345")); stateMachine.AddHighAvailabilityMemberListener(haModeSwitcher); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<org.neo4j.kernel.ha.com.master.Master> ref = new java.util.concurrent.atomic.AtomicReference<>(null); AtomicReference <Master> @ref = new AtomicReference <Master>(null); //noinspection unchecked AbstractComponentSwitcher <object> otherModeSwitcher = new AbstractComponentSwitcherAnonymousInnerClass(this, mock(typeof(DelegateInvocationHandler)), handler, latch, @ref); switcherContainer.Add(otherModeSwitcher); // When events.SwitchToSlave(me); // Then latch.await(); assertTrue("mode switch failed", switchedSuccessfully.get()); Master actual = @ref.get(); // let's test the toString()s since there are too many wrappers of proxies assertEquals(masterClient.ToString(), actual.ToString()); stateMachine.Stop(); stateMachine.Shutdown(); haModeSwitcher.Stop(); haModeSwitcher.Shutdown(); }