public Task RegisterSources(IEnumerable <IConfigurationSource> sources) { List <IConfigurationSource> initial; List <IConfigurationSource> tmp; var latch = new Latch(); do { initial = _sources; tmp = new List <IConfigurationSource>(initial); foreach (var source in sources) { if (tmp.Contains(source)) { break; } source.OnInitialized = () => latch.Decrement(); tmp.Add(source); latch.Increment(); } }while (Interlocked.CompareExchange(ref _sources, tmp, initial) != initial); EnsuresPolling(); return(latch.Task); }
public void Reset() { StateLatch = new Latch(); CurrentValue = DefaultValue; PreviousActiveEdge = EdgeType.None; StartTime = 0; }
public UmbracoLatchResponse Pair(string token, int userId) { var application = GetApplication(); var latch = new Latch(application.ApplicationId, application.Secret); var response = latch.Pair(token); if (response.Error != null) { var errorMessage = GetPairingResponseMessage("error" + response.Error.Code); return(new UmbracoLatchResponse(false, errorMessage)); } if (response.Data == null || !response.Data.ContainsKey("accountId")) { var errorMessage = GetPairingResponseMessage("pairError"); return(new UmbracoLatchResponse(false, errorMessage)); } var pairedAccount = new LatchPairedAccount { UserId = userId, AccountId = response.Data["accountId"] as string }; latchRepo.AddPairedAccount(pairedAccount); var successMessage = GetPairingResponseMessage("pairSuccess"); return(new UmbracoLatchResponse(true, successMessage)); }
public override int GetHashCode() { int hash = 1; if (Type != 0) { hash ^= Type.GetHashCode(); } if (Mode != 0) { hash ^= Mode.GetHashCode(); } if (MessageHistoryLimit != 0) { hash ^= MessageHistoryLimit.GetHashCode(); } if (Latch != false) { hash ^= Latch.GetHashCode(); } if (Topic.Length != 0) { hash ^= Topic.GetHashCode(); } return(hash); }
public UmbracoLatchResponse Unpair() { var application = GetApplication(); var account = latchRepo.GetPairedAccount(); if (account == null) { var errorMessage = GetPairingResponseMessage("alreadyUnpaired"); return(new UmbracoLatchResponse(false, errorMessage)); } var latch = new Latch(application.ApplicationId, application.Secret); var response = latch.Unpair(account.AccountId); if (response.Error != null) { var errorMessage = GetPairingResponseMessage("error" + response.Error.Code); return(new UmbracoLatchResponse(false, errorMessage)); } latchRepo.DeletePairedAccount(); var successMessage = GetPairingResponseMessage("unpairSuccess"); return(new UmbracoLatchResponse(true, successMessage)); }
public void WaitOnBorrowWhenExausted() { int n = 100; object[] objects = new object[n]; pool = new SimplePool(new MyFactory(), n); for (int i = 0; i < n; i++) { objects[i] = pool.BorrowObject(); } Latch latch = new Latch(); ISync sync = new Latch(); Helper helper = new Helper(latch, sync, pool); Thread thread = new Thread(new ThreadStart(helper.UsePool)); thread.Start(); Assert.AreEqual(n, pool.NumActive); Assert.AreEqual(0, pool.NumIdle); object released = objects[n - 1]; pool.ReturnObject(released); latch.Acquire(); Assert.AreEqual(n, pool.NumActive); Assert.AreEqual(0, pool.NumIdle); Assert.IsNotNull(helper.gotFromPool, "helper did not get from pool"); Assert.AreSame(released, helper.gotFromPool, "got unexpected object"); }
public Lockifi() { global::LockifiApp.Properties.Settings.Default.Reload(); InitializeComponent(); notifyIcon1.Text = "Lockifi"; notifyIcon1.ContextMenuStrip = contextMenuStripNotifyIcon; users = new List <User>(); routers = new List <Router>(); listening = false; onNotify = false; router_current_status = false; current_script_router = ""; FromXML(); latch = new Latch(global::LockifiApp.Properties.Settings.Default.latch_appid, global::LockifiApp.Properties.Settings.Default.latch_seckey); Fill_ComboBoxRouters(); Fill_comboBoxWifiStatus(); this.Show(); Fill_dataGridViewUsers(); }
public Boolean getLatchStatus(Latch latch) { LatchResponse statusResponse = null; try { statusResponse = latch.Status(accountId); } catch (Exception es) { string message = "You do not have internet connection"; string caption = "Problem with internet connection"; DialogResult result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } if (statusResponse.Error != null && statusResponse.Error.Message != "") { string message = statusResponse.Error.Message; string caption = "Latch connection: " + statusResponse.Error.Code; DialogResult result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } else { Dictionary <string, object> op = (Dictionary <string, object>)statusResponse.Data["operations"]; Dictionary <string, object> st = (Dictionary <string, object>)op[global::LockifiApp.Properties.Settings.Default.latch_appid]; return(st["status"].ToString() == "on"); } }
public void Dispose() { if (Interlocked.CompareExchange(ref _release, Released, UnReleased) == UnReleased) { switch (Flags) { case LatchFlags.Read: Latch.ExitReadScope(); break; case LatchFlags.Write: Latch.ExitWriteScope(); break; case LatchFlags.RWRead: Latch.ExitReadWriteScope(); break; case LatchFlags.RWWrite: Latch.ExitWriteScope(); Latch.ExitReadWriteScope(); break; } } }
protected override void ProcessRecord() { try { if (String.IsNullOrEmpty(AppId)) { AppId = InputHelper.GetUserInput(this, "AppId"); } if (String.IsNullOrEmpty(SecretKey)) { SecretKey = InputHelper.GetUserInput(this, "SecretKey"); } if (String.IsNullOrEmpty(Token)) { Token = InputHelper.GetUserInput(this, "Token"); } Latch latch = new Latch(AppId, SecretKey); WriteObject(latch.Pair(Token), true); } catch (Exception ex) { InvokeCommand.InvokeScript(String.Format("Write-Host Error: \"{0}\"", ex.Message)); } }
protected override void ProcessRecord() { try { if (String.IsNullOrEmpty(AppId)) { AppId = InputHelper.GetUserInput(this, "AppId"); } if (String.IsNullOrEmpty(SecretKey)) { SecretKey = InputHelper.GetUserInput(this, "SecretKey"); } if (String.IsNullOrEmpty(AccountId)) { AccountId = InputHelper.GetUserInput(this, "AccountId"); } if (String.IsNullOrEmpty(From)) { From = InputHelper.GetUserInput(this, "From"); } if (String.IsNullOrEmpty(To)) { To = InputHelper.GetUserInput(this, "To"); } Latch latch = new Latch(AppId, SecretKey); WriteObject(latch.History(AccountId, DateTime.Parse(From), DateTime.Parse(To)), true); } catch (Exception ex) { InvokeCommand.InvokeScript(String.Format("Write-Host Error: \"{0}\"", ex.Message)); } }
public bool LatchIsOpen(string operationId) { var application = GetApplication(); var account = GetPairedAccount(); var latch = new Latch(application.ApplicationId, application.Secret); var response = latch.OperationStatus(account.AccountId, operationId); if (response.Error != null) { return(true); } var isOpen = true; if (response.Data.ContainsKey("operations")) { var operations = response.Data["operations"] as Dictionary <string, object>; if (operations.ContainsKey(operationId)) { var currentOperation = operations[operationId] as Dictionary <string, object>; if (currentOperation.ContainsKey("status")) { var currentStatus = currentOperation["status"] as string; var latchIsOpen = currentStatus.Equals("on", StringComparison.InvariantCultureIgnoreCase); isOpen = latchIsOpen; } } } return(isOpen); }
public UmbracoLatchResponse DeleteOperation(int operationId) { if (!OperationExists(operationId)) { var errorMessage = GetResponseMessage("notFound"); return(new UmbracoLatchResponse(false, errorMessage)); } var currentOperation = latchRepo.GetOperationById(operationId); var application = GetApplication(); var latch = new Latch(application.ApplicationId, application.Secret); var response = latch.RemoveOperation(currentOperation.OperationId); // The 301 error code means that the operation wasn't found on Latch // so it's probably that the user deleted the operation from the Latch app // and we only need to delete it from the local database. if (response.Error != null && response.Error.Code != 301) { var errorMessage = GetResponseMessage("error" + response.Error.Code); return(new UmbracoLatchResponse(false, errorMessage)); } latchRepo.DeleteOperation(currentOperation); var successMessage = GetResponseMessage("editSuccess"); return(new UmbracoLatchResponse(true, successMessage)); }
//private log4net.ILog log = log4net.LogManager.GetLogger("MyLogger"); public ProcThread() { UsbTxPrepare(); txQueue = usb.TxQueue; rxQueue = usb.RxQueue; latch = usb.Latch; }
public BooleanResult AuthorizeUser(SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); if (!ReferenceEquals(null, Settings.ApplicationID) && !ReferenceEquals(null, Settings.Secret)) { string applicationID = Util.GetSettingsString((string)Settings.ApplicationID); string secret = Util.GetSettingsString((string)Settings.Secret); string accountID = Util.GetSettingsString((string)Settings.AccountID); //m_logger.InfoFormat("ApplicationID: {0}", applicationID); //m_logger.InfoFormat("Secret: {0}", secret); //m_logger.InfoFormat("AccountID: {0}", accountID); Latch latch = new Latch(applicationID, secret); LatchResponse response = latch.Status(accountID); // One of the ugliest lines of codes I ever wrote, but quickest way to access the object without using json serialization try { Dictionary <string, object> operations = ((Dictionary <string, object>)response.Data["operations"]); Dictionary <string, object> appSettings = ((Dictionary <string, object>)operations[(applicationID)]); string status = ((string)appSettings["status"]); m_logger.InfoFormat("Latch status is {0}", status); if (status == "on") { return new BooleanResult() { Success = true, Message = "Ready to go!" } } ; else { return new BooleanResult() { Success = false, Message = "Latch is protecting this account!" } }; } catch (Exception) { return(new BooleanResult() { Success = true, Message = "Something went wrong, letting you in because I don't want to lock you out!" }); } } else { return(new BooleanResult() { Success = false, Message = "Latch is not correctly configured." }); } }
public void WeakReference_Generic() { object o1 = new char[10]; WeakReference <object> w = new WeakReference <object>(o1); VerifyStillAlive(w); object v1; Assert.IsTrue(w.TryGetTarget(out v1)); Assert.IsTrue(Object.ReferenceEquals(v1, o1)); GC.KeepAlive(o1); object o2 = new char[100]; w.SetTarget(o2); VerifyStillAlive(w); object v2; Assert.IsTrue(w.TryGetTarget(out v2)); Assert.IsTrue(Object.ReferenceEquals(v2, o2)); GC.KeepAlive(o2); Latch l = new Latch(); w = MakeWeakReferenceOfObject(() => new C(l), null); GC.Collect(); VerifyIsDead(w); // WARN: Compact Framework does not support to track resurrection #if !WindowsCE l = new Latch(); w = MakeWeakReferenceOfObject(() => new ResurrectingC(l), true); GC.Collect(); GC.WaitForPendingFinalizers(); if (!l.FinalizerRan) { Console.WriteLine("Attempted GC but could not force test object to finalize. Test skipped."); } else { VerifyStillAlive(w); } l = new Latch(); w = MakeWeakReferenceOfObject(() => new C(l), true); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); if (!l.FinalizerRan) { Console.WriteLine("Attempted GC but could not force test object to finalize. Test skipped."); } else { VerifyIsDead(w); } #endif }
void ICompactSerializable.Deserialize(CompactReader reader) { _bucketId = reader.ReadInt32(); _tempAddress = (Address)reader.ReadObject(); _permanentAddress = (Address)reader.ReadObject(); byte status = reader.ReadByte(); _stateTxfrLatch = new Latch(status); }
private void Initialize(Broker container, OnCommandRecieved commandRecieved, OnServerLost serverLost, Logs logs, PerfStatsCollector perfStatsCollector, ResponseIntegrator rspIntegraotr, string bindIP, string cacheName) { _commandRecieved = null; _serverLost = null; _isConnected = true; _primaryClient = null; _secondaryClient = null; _ipAddress = string.Empty; _intendedRecipientIPAddress = string.Empty; _port = 0; _connectionMutex = new object(); _connectionStatusLatch = new Latch(ConnectionStatus.Disconnected); s_receiveBufferSize = 2048000; _processID = System.Diagnostics.Process.GetCurrentProcess().Id; _primaryReceiveThread = null; _secondaryReceiveThread = null; _notificationsRegistered = false; _isReconnecting = false; _forcedDisconnect = false; _nagglingEnabled = false; _nagglingSize = 5 * 100 * 1024; //500k _supportDualSocket = false; _syncLock = new object(); _perfStatsColl = null; _socketSelectionMutex = new object(); _usePrimary = true; _optimized = false; _isIdle = false; _container = container; _commandRecieved = commandRecieved; _serverLost = serverLost; _logger = logs; _responseIntegrator = rspIntegraotr; _cacheId = cacheName; _perfStatsColl = perfStatsCollector; SetBindIP(bindIP); if (System.Configuration.ConfigurationSettings.AppSettings["EnableNaggling"] != null) { _nagglingEnabled = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["EnableNaggling"]); } //read the naggling size from app.config and covert it to bytes. if (System.Configuration.ConfigurationSettings.AppSettings["NagglingSize"] != null) { _nagglingSize = 1024 * Convert.ToInt64(System.Configuration.ConfigurationSettings.AppSettings["NagglingSize"]); } if (System.Configuration.ConfigurationSettings.AppSettings["EnableDualSockets"] != null) { _supportDualSocket = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["EnableDualSockets"]); } }
public virtual void Deserialize(CompactReader reader) { //Trace.error("HashMapBucket.Deserialize", "Deserialize Called"); _bucketId = reader.ReadInt32(); _finalShard = (string)reader.ReadObject(); _currentShard = (string)reader.ReadObject(); byte status = reader.ReadByte(); _stateTxfrLatch = new Latch(status); }
public void ctor_IsNotLatched() { // Arrange var classUnderTest = new Latch(); // Act // Assert Assert.IsFalse(classUnderTest.IsLatched); }
void ICompactSerializable.Deserialize(CompactReader reader) { //Trace.error("HashMapBucket.Deserialize", "Deserialize Called"); _bucketId = reader.ReadInt32(); _tempAddress = (Address)reader.ReadObject(); _permanentAddress = (Address)reader.ReadObject(); byte status = reader.ReadByte(); _stateTxfrLatch = new Latch(status); }
public StateAnimator(Func <double, float> PositiveEasingFunction, Func <double, float> NegativeEasingFunction, double AnimationDuration) { this.PositiveEasingFunction = PositiveEasingFunction; this.NegativeEasingFunction = NegativeEasingFunction; this.AnimationDuration = AnimationDuration; StateLatch = new Latch(); CurrentValue = PositiveEasingFunction(0); }
public static void Generic() { object o1 = new char[10]; WeakReference <object> w = new WeakReference <object>(o1); VerifyStillAlive(w); object v1; Assert.True(w.TryGetTarget(out v1)); Assert.True(object.ReferenceEquals(v1, o1)); GC.KeepAlive(o1); object o2 = new char[100]; w.SetTarget(o2); VerifyStillAlive(w); object v2; Assert.True(w.TryGetTarget(out v2)); Assert.True(object.ReferenceEquals(v2, o2)); GC.KeepAlive(o2); Latch l = new Latch(); w = MakeWeakReferenceOfObject(() => new C(l)); GC.Collect(); VerifyIsDead(w); l = new Latch(); w = MakeWeakReferenceOfObject(() => new ResurrectingC(l), true); GC.Collect(); GC.WaitForPendingFinalizers(); if (!l.FinalizerRan) { Console.WriteLine("Attempted GC but could not force test object to finalize. Test skipped."); } else { VerifyStillAlive(w); } l = new Latch(); w = MakeWeakReferenceOfObject(() => new C(l), true); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); if (!l.FinalizerRan) { Console.WriteLine("Attempted GC but could not force test object to finalize. Test skipped."); } else { VerifyIsDead(w); } }
public void SetUp() { springAssembliesDeployer = new SpringAssembliesDeployer("."); location = new FileSystemDeployLocation(deployPath); location.StartWatching(); sync = new Latch(); defaultDeployer = new SyncedDeployer(sync); deployManager = new DeployManager(springAssembliesDeployer, location, defaultDeployer); deployManager.Start(); }
public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return(false); } Latch other = (Latch)obj; return(Target == other.Target && Eater == other.Eater && Val == other.Val); }
public void RunInsideLatch_CallInLatch_BarIsNotCalled() { // Arrange var classUnderTest = new Latch(); var foo = A.Fake <IFoo>(); // Act classUnderTest.RunInsideLatch(() => classUnderTest.RunInsideLatch(foo.Bar)); // Assert A.CallTo(() => foo.Bar()).MustNotHaveHappened(); }
public PairUser(String usernameI, Latch latchI) { username = usernameI; latch = latchI; InitializeComponent(); accountId = ""; textBoxUsername.Text = username; textBoxUsername.Enabled = false; textBoxPairCode.Select(); }
public void WeakReference_NonGeneric() { object o1 = new char[10]; WeakReference w = new WeakReference(o1); VerifyStillAlive(w); Assert.IsTrue(RuntimeHelpers.ReferenceEquals(o1, w.Target)); Assert.IsFalse(w.TrackResurrection); GC.KeepAlive(o1); object o2 = new char[100]; w.Target = o2; VerifyStillAlive(w); Assert.IsTrue(RuntimeHelpers.ReferenceEquals(o2, w.Target)); GC.KeepAlive(o2); Latch l = new Latch(); w = MakeWeakReference(() => new C(l), null); GC.Collect(); VerifyIsDead(w); // WARN: Compact Framework does not support to track resurrection #if !WindowsCE l = new Latch(); w = MakeWeakReference(() => new ResurrectingC(l), true); GC.Collect(); GC.WaitForPendingFinalizers(); if (!l.FinalizerRan) { Console.WriteLine("Attempted GC but could not force test object to finalize. Test skipped."); } else { VerifyStillAlive(w); } l = new Latch(); w = MakeWeakReference(() => new C(l), true); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); if (!l.FinalizerRan) { Console.WriteLine("Attempted GC but could not force test object to finalize. Test skipped."); } else { VerifyIsDead(w); } #endif }
public override void HandleModelShutdown(object model, ShutdownEventArgs reason) { // keep track of duplicates if (Latch.Wait(0)) { DuplicateLatch.Set(); } else { Latch.Set(); } }
protected void SetUp_() { deployPath = Guid.NewGuid().ToString(); sampleDir = Path.Combine(deployPath, deploy); sampleDir2 = Path.Combine(deployPath, deploy + "2"); serviceXml = Path.Combine(sampleDir, Application.ServiceXml); watcherXml = Path.Combine(sampleDir, Application.WatcherXml); triggeredLatch = new Latch(); trigger = new ThreadingTimerTrigger(50); trigger.Triggered += new EventHandler(trigger_Triggered); dispatcher = new AggregatedDeployEventDispatcher(trigger); TestUtils.ConfigureLog4Net(); }
public void setLatch(int currentState, int lower, int increment, int decrement, int upper, int inter, bool mayInterrupt) { latch = new Latch(currentState, lower, increment, decrement, upper, inter, mayInterrupt); }