public void Start(Action<TcpClient, byte[]> onData, Action<TcpClient> onDisconnect) { TcpListener listener = new TcpListener(port); listener.Start(); running = true; AutoResetEvent are = new AutoResetEvent(false); agent = new Agent<Action>( () => { }, () => { }, nextaction => { nextaction(); if (running) { return NextAction.WaitForNextMessage; } are.Set(); return NextAction.Finish; }); agent.Start(); agent.SendMessage(() => { StartAccepting(listener, onData, onDisconnect); }); are.WaitOne(); listener.Stop(); }
static void Main(string[] args) { SetTitle("Starting..."); Agent agent = new Agent(); agent.Start(); SetTitle("Started"); System.Console.ReadLine(); agent.Stop(); SetTitle("Stopped"); }
// test methods public static void TestViaCmdLine() { var sendResponse = Agent.Start((FxRateResponse res) => WriteLine($"{res.CcyPair}: {res.Rate}")); var rateLookup = StartReqProcessor(sendResponse); WriteLine("Enter a currency pair like 'EURUSD' to get a quote, or 'q' to quit"); for (string input; (input = ReadLine().ToUpper()) != "Q";) { rateLookup.Tell(new FxRateRequest { CcyPair = input, Sender = "Sender" }); } }
public Connection( IConnectionHandle connectionHandle, IRfcRuntime rfcRuntime) { _connectionHandle = connectionHandle; RfcRuntime = rfcRuntime; _stateAgent = Agent.Start <IConnectionHandle, AgentMessage, Either <RfcErrorInfo, object> >( connectionHandle, (handle, msg) => { if (handle == null) { return(null, new RfcErrorInfo(RfcRc.RFC_INVALID_HANDLE, RfcErrorGroup.EXTERNAL_RUNTIME_FAILURE, "", "Connection already destroyed", "", "E", "", "", "", "", "")); }
public LogAgent(Func <LogMsg, Unit>[] handlers) { _agent = Agent <LogMsg, Unit> .Start(Unit.Default, (inbox, u) => { var msg = inbox.Receive().RunSynchronously(); foreach (var handler in handlers) { handler(msg); } return(Unit.Default); }); SharedAgent = this; }
static Agent <string> StartAgentFor (string ccyPair, Agent <FxRateResponse> sendResponse) => Agent.Start <Option <decimal>, string>(None, async(optRate, recipient) => { decimal rate = await optRate.Map(Async) .GetOrElse(() => Yahoo.GetRate(ccyPair)); sendResponse.Tell(new FxRateResponse { CcyPair = ccyPair, Rate = rate, Recipient = recipient, }); return(Some(rate)); });
public void StartDemoAgent(string playerName) { var agentTask = Task.Factory.StartNew(() => { string endpoint = ""; if (IsRunningLocally) { endpoint = "http://localhost:52802"; } else { endpoint = "http://planetwars.azurewebsites.net"; } var sweetDemoAgent = new Agent(playerName, endpoint); sweetDemoAgent.Start().Wait(); }); }
public AccountProcess(AccountState initialState, Func <Event, Task <Unit> > saveAndPublish) { agent = Agent.Start(initialState , async(AccountState state, Command cmd) => { Result result = new Pattern { (MakeTransfer transfer) => state.Debit(transfer), (FreezeAccount freeze) => state.Freeze(freeze), } .Match(cmd); await result.Traverse(tpl => saveAndPublish(tpl.Event)); // persist within block, so that the agent doesn't process new messages in a non-persisted state var newState = result.Map(tpl => tpl.NewState).GetOrElse(state); return(Tuple(newState, result)); }); }
public AccountRegistry(Func <Guid, Task <Option <AccountState> > > loadAccount , Func <Event, Task <Unit> > saveAndPublish) { this.loadAccount = loadAccount; this.agent = Agent.Start(AccountsCache.Empty, (AccountsCache cache, Msg msg) => new Pattern <(AccountsCache, Option <AccountProcess>)> { (LookupMsg m) => (cache, cache.Lookup(m.Id)), (RegisterMsg m) => cache.Lookup(m.Id).Match( Some: acc => (cache, Some(acc)), None: () => { var account = new AccountProcess(m.AccountState, saveAndPublish); return(cache.Add(m.Id, account), Some(account)); }) }
public void StartDemoAgent(int gameId, bool advanced) { if (advanced) { var agentTask = Task.Factory.StartNew(async() => { var sweetDemoAgent = new AdvancedAgent(gameId); await sweetDemoAgent.Start(); }); } else { var agentTask = Task.Factory.StartNew(async() => { var sweetDemoAgent = new Agent(gameId); await sweetDemoAgent.Start(); }); } }
public void Run() { // Producer/consumer using TPL Dataflow List <string> urls = new List <string> { @"http://www.google.com", @"http://www.microsoft.com", @"http://www.bing.com", @"http://www.google.com" }; var agentStateful = Agent.Start(ImmutableDictionary <string, string> .Empty, async(ImmutableDictionary <string, string> state, string url) => { // #A if (!state.TryGetValue(url, out string content)) { using (var webClient = new WebClient()) { content = await webClient.DownloadStringTaskAsync(url); await File.WriteAllTextAsync(createFileNameFromUrl(url), content); return(state.Add(url, content)); // #B } } return(state); // #B }); urls.ForEach(url => agentStateful.Post(url)); // Agent fold over state and messages - Aggregate urls.Aggregate(ImmutableDictionary <string, string> .Empty, (state, url) => { if (!state.TryGetValue(url, out string content)) { using (var webClient = new WebClient()) { content = webClient.DownloadString(url); System.IO.File.WriteAllText(createFileNameFromUrl(url), content); return(state.Add(url, content)); } } return(state); }); }
public void Run() { // Producer/consumer using TPL Dataflow List <string> urls = new List <string> { @"http://www.google.com", @"http://www.microsoft.com", @"http://www.bing.com", @"http://www.google.com" }; // TODO 5.3 // Agent fold over state and messages - Aggregate urls.Aggregate(ImmutableDictionary <string, string> .Empty, (state, url) => { if (!state.TryGetValue(url, out string content)) { using (var webClient = new WebClient()) { content = webClient.DownloadString(url); System.IO.File.WriteAllText(createFileNameFromUrl(url), content); return(state.Add(url, content)); } } return(state); }); // TODO : 5.3 // (1) replace the implementation using the urls.Aggregate with a new one that uses an Agent // Suggestion, instead of the Dictionary you should try to use an immutable structure var agentStateful = Agent.Start <Dictionary <string, string> >(msg => { }); // (2) complete this code urls.ForEach(url => { // agentStateful.Post(url); }); }
private void startButton_Click(object sender, EventArgs e) { dialogueListCheckedListBox.Enabled = false; TimerResolution.TimeBeginPeriod(1); // Sets the timer resolution to 1 ms (default in Windows 7: 15.6 ms) startButton.Enabled = false; exitToolStripMenuItem.Enabled = false; // Check which processes should be enabled: for (int ii = 0; ii < dialogueListCheckedListBox.Items.Count; ii++) { string context = dialogueListCheckedListBox.Items[ii].ToString(); int dialogueIndex = agent.DialogueList.FindIndex(d => d.Context == context); if (dialogueIndex > 0) // Not allowed to remove dialogue 0 (startup dialogue) { if (dialogueListCheckedListBox.GetItemChecked(ii) == false) { agent.DialogueList.RemoveAt(dialogueIndex); } } } agent.AutoArrangeWindows = autoarrangeWindowsToolStripMenuItem.Checked; Boolean startSuccessful = agent.StartProcesses(); if (startSuccessful) { agent.Start(agent.DialogueList[0].Context); // Start from the first dialogue in the list workingMemoryViewer.SetWorkingMemory(agent.WorkingMemory); workingMemoryViewer.ShowMemory(); stopButton.Enabled = true; } else { startButton.Enabled = true; stopButton.Enabled = false; } //other initializatiosn ItemHandler.LoadShortcuts(agent); }
static Agent <string> StartAgentFor (string ccyPair, Agent <FxRateResponse> sendResponse) => Agent.Start <Option <decimal>, string> ( initialState: None, process: async(optRate, recipient) => { decimal rate = await optRate.Map(Async) .GetOrElse(() => RatesApi.GetRateAsync(ccyPair)); sendResponse.Tell(new FxRateResponse ( CcyPair: ccyPair, Rate: rate, Recipient: recipient )); return(Some(rate)); } );
private void button1_Click(object sender, EventArgs e) { try { agent.Start(80); } catch (AgentException exp) { String msg = exp.Message; if (exp.InnerException != null) { msg = msg + "\n" + exp.InnerException.Message; } MessageBox.Show(this, msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Dispose(); } this.button1.Enabled = false; this.button2.Enabled = true; //this.textBox1.Text = "Agent Started"; }
public static IAgent <FlipToggleMessage> Create( IAgent <StocksCoordinatorMessage> coordinatorActor, StockToggleButtonViewModel viewModel, string stockSymbol) { return(Agent.Start <bool, FlipToggleMessage>(false, (isToggledOn, message) => { if (isToggledOn) { coordinatorActor.Post(new UnWatchStockMessage(stockSymbol)); viewModel.UpdateButtonTextToOff(); } else { coordinatorActor.Post(new WatchStockMessage(stockSymbol)); viewModel.UpdateButtonTextToOn(); } return !isToggledOn; })); }
private Log() { _agent = Agent <AgentMsg, Unit> .Start(ImmutableList <Handler> .Empty, (inbox, handlers) => { var msg = inbox.Receive().RunSynchronously(); return(Pattern <Handlers> .Match(msg) .Case <AddHandlerMsg>(h => handlers.Add(h.Handler)) .Case <Msg>(l => { foreach (var handler in handlers) { handler(l); } return handlers; }) .Default(handlers) .Run()); }); }
public void TestAgents() { Agent <string> logger, ping, pong = null; int totalCount = 0, pingCount = 0, pongCount = 0; logger = Agent.Start <string>(msg => ++ totalCount); ping = Agent.Start((string msg) => { pingCount++; if (msg == "STOP") { return; } logger.Tell($"Received '{msg}'; Sending 'PING'"); Task.Delay(500).Wait(); pong.Tell("PING"); }); pong = Agent.Start(0, (int count, string msg) => { int newCount = count + 1; pongCount++; string nextMsg = (newCount < 5) ? "PONG" : "STOP"; logger.Tell($"Received '{msg}' #{newCount}; Sending '{nextMsg}'"); Task.Delay(500).Wait(); ping.Tell(nextMsg); return(newCount); }); ping.Tell("START"); Thread.Sleep(10000); Assert.Equal(10, totalCount); Assert.Equal(6, pingCount); Assert.Equal(5, pongCount); }
public async Task ReceiverGetsExpectedContext_IfHappyPath() { // Arrange var spyReceiver = new SpyReceiver(); var sut = new Agent( new AgentConfig(name: "Agent with Normal Pipeline"), spyReceiver, Transformer <StubSubmitTransformer>(), exceptionHandler: new SpyAgentExceptionHandler(), stepConfiguration: new StepConfiguration { NormalPipeline = AS4MessageSteps(), ErrorPipeline = null }); // Act await sut.Start(CancellationToken.None); // Assert Assert.True(spyReceiver.IsCalled); Assert.Equal(AS4Message.Empty, spyReceiver.Context.AS4Message); }
public async Task NoStepsAreExecuted_IfNoStepsAreDefined() { // Arrange var spyReceiver = new SpyReceiver(); var sut = new Agent( new AgentConfig("Agent with non-defined Normal Steps"), spyReceiver, Transformer <StubSubmitTransformer>(), exceptionHandler: new SpyAgentExceptionHandler(), stepConfiguration: new StepConfiguration { NormalPipeline = new Step[] { null }, ErrorPipeline = null }); // Act await sut.Start(CancellationToken.None); // Assert Assert.True(spyReceiver.IsCalled); Assert.NotNull(spyReceiver.Context.SubmitMessage); }
protected override void OnStart(string[] args) { agent = new Agent(); try { agent.Start(); } catch (AgentException exp) { String msg = exp.Message; if (exp.InnerException != null) { msg = msg + "\n" + exp.InnerException.Message; } eventLog1.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error); } catch (System.UnauthorizedAccessException eu) { eventLog1.WriteEntry("Access denied. Please specify the user account that the MTConnect service can use to log on.", System.Diagnostics.EventLogEntryType.Error); throw eu; } }
public AccountRegistry_Naive(Func <Guid, Task <Option <AccountState> > > loadAccount , Func <Event, Task <Unit> > saveAndPublish) { agent = Agent.Start(AccountsCache.Empty , async(AccountsCache cache, Guid id) => { AccountProcess account; if (cache.TryGetValue(id, out account)) { return(cache, Some(account)); } var optAccount = await loadAccount(id); return(optAccount.Map(accState => { var process = new AccountProcess(accState, saveAndPublish); return (cache.Add(id, process), Some(process)); }) .GetOrElse(() => (cache, (Option <AccountProcess>)None))); }); }
override protected void Action() { Agent newAgent = Activator.CreateInstance(type, args) as Agent; newAgent.Start(); }
/// <summary> /// register an Agent for inclusion in the simulation /// </summary> /// <param name="inAgent">Agent to register</param> public void Databind(ref Agent inAgent) { inAgent.Start(); Agents.Add(inAgent); }
public void StartAgent(CancellationToken cancellationToken) { Agent.Start(cancellationToken); }
public void Agent_opens_tcp_connection_on_port_7894() { var agent = new Agent(); agent.Start(); Assert_Port_Open("127.0.0.1", PORT); }
public static void Main() { SetUpGemParty(); theAgent.Start(); }
public void MyProgramSetup() { bTerminating = false; // Configuration try { nDebug = Convert.ToInt32(ConfigurationManager.AppSettings["Debug"]); Logger.debuglevel = nDebug; nMTCPort = Convert.ToInt32(ConfigurationManager.AppSettings["MTConnectPort"]); opcflag = Convert.ToBoolean(ConfigurationManager.AppSettings["opcflag"]); nResetCycleWait = Convert.ToInt32(ConfigurationManager.AppSettings["ResetCycleWait"]); nShdrScanDelay = Convert.ToInt32(ConfigurationManager.AppSettings["ShdrScanDelay"]); dtResetTime = TimeSpan.Parse(ConfigurationManager.AppSettings["ResetTime"]); bReset = Convert.ToBoolean(ConfigurationManager.AppSettings["ResetFlag"]); sports = ConfigurationManager.AppSettings["shdrports"].Split(',');// other.AppSettings.Settings["devices"].Value.Split(','); for (int j = 0; j < sports.Count(); j++) { ports.Add(Convert.ToInt16(sports[j].Trim())); } ipaddrs = ConfigurationManager.AppSettings["opcipaddrs"].Split(',');// other.AppSettings.Settings["devices"].Value.Split(','); for (int i = 0; i < ipaddrs.Count(); i++) { ipaddrs[i] = ipaddrs[i].Trim(); } devices = ConfigurationManager.AppSettings["devices"].Split(',');// other.AppSettings.Settings["devices"].Value.Split(','); for (int i = 0; i < devices.Count(); i++) { devices[i] = devices[i].Trim(); } /* Create timer */ aTimer = new System.Timers.Timer(); aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 1000; aTimer.AutoReset = false; if (opcflag) { for (int i = 0; i < ipaddrs.Count(); i++) { Agent agent = new Agent(ports[i], nShdrScanDelay); OPCMgr opc = new OPCMgr(agent, devices[i], ipaddrs[i]); opc.Init(); opcClients.Add(opc); agent.StoreEvent(DateTime.Now.ToString("s"), devices[i], "power", "OFF", null, null, null, null, null, null); agent.Start(); } if (opcClients.Count < 1) { throw new Exception("Illegal Host Name"); } aTimer.Interval = opcClients[0].nServerUpdatePeriod; } } catch (Exception e) { dtResetTime = new TimeSpan(0, 0, 0, 60, 0); Logger.LogMessage("Configuration Error: " + e.Message, Logger.FATAL); } }
public void Setup() { _agent = new Agent(); _agent.Start(); }
public void Agent_closes_tcp_connection() { var agent = new Agent(); agent.Start(); agent.Stop(); Assert_Port_Closed("127.0.0.1", PORT); }
/// <summary> /// Methode qui lance les boucles de l'environnement et de l'aspirateur. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Start(object sender, RoutedEventArgs e) { Aspirateur.Start(); ((Button)sender).IsEnabled = false; }
public void Setup() { _printer = Agent.Start((string msg) => WriteLine($"{msg} on thread {Thread.CurrentThread.ManagedThreadId}")); }