public static void Main(string[] args) { Options options; try { options = Options.Parse(args); } catch (Exception e) { MessageBox.Show(e.Message, "Error in command line - disfr"); return; } if (!options.SingleInstance) { var app = new App(); app.Run(); } else { var ipc_port = CreateUniquePort(typeof(App).Assembly); var uri = "Run"; // If two or more process started executing this program at some critical timing, // or an existing App (running as IPC server) is terminating when a new process tried to start, // the IPC channel connection may fail. // We need to detect the case and try again, // but don't retry too much, since the failure may be by other reason (e.g., system resource exhaust.) for (int i = 0; i < 10; i++) { try { // Try to be an IPC server. var server_channel = new IpcServerChannel(ipc_port); ChannelServices.RegisterChannel(server_channel, true); RemotingConfiguration.RegisterWellKnownServiceType(typeof(SingleInstance), uri, WellKnownObjectMode.Singleton); // We've got a server-side IPC channel. Run as a server. try { var app = new App(); app.Run(); } catch (Exception) { // The program may got an exception and terminates, due to a bug. // We SHOULD NOT retry IPC connection in the case. Just terminate. } return; } catch (Exception) { } // When we got here, it is very likely that an IPC server is already running. Thread.Sleep(50); try { // Try to be an IPC client. var client_channel = new IpcClientChannel(); ChannelServices.RegisterChannel(client_channel, true); var instance = Activator.GetObject(typeof(SingleInstance), "ipc://" + ipc_port + "/" + uri) as SingleInstance; if (instance.Run(args)) { return; } } catch (Exception) { } // When we got here, it is likely that an IPC server was running but terminated. Thread.Sleep(50); } MessageBox.Show("Appliation failed: Couldn't establish remoting.", "Error - disfr"); } }
static void Main(string[] args) { Dictionary <string, string> pid_Client = new Dictionary <string, string>(); //PID,PCS_URL Dictionary <string, string> pid_Server = new Dictionary <string, string>(); //PID,PCS_URL Dictionary <string, Tuple <bool, string> > url_Client = new Dictionary <string, Tuple <bool, string> >(); //PID,CLIENT_URL Dictionary <string, Tuple <bool, string> > url_Servers = new Dictionary <string, Tuple <bool, string> >(); //PID,SERVER_URL TcpChannel channel = new TcpChannel(); ChannelServices.RegisterChannel(channel, false); void process(string[] input) { IPCS pcs = null; switch (input[0]) { case "StartClient": if (url_Servers.Count == 0) { Console.WriteLine("Need to start one server first!"); break; } //StartClient PID PCS_URL CLIENT_URL MSEC_PER_ROUND NUM_PLAYERS [filename] if (input.Count() > 7) { Console.WriteLine("Invalid number of arguments to start server, expected 5/6 delimited by a space"); break; } if (!pid_Client.ContainsKey(input[1])) { try { pcs = (IPCS)Activator.GetObject(typeof(IPCS), input[2]); } catch (RemotingException) { Console.WriteLine("Problems getting Object IPCS interface from: " + input[2]); break; } catch (ArgumentNullException) { Console.WriteLine("Url: " + input[2] + "or type is null."); break; } catch (Exception e) { Console.WriteLine("Problems trying to get PCS, exception: "); Console.WriteLine(e.ToString()); break; } string urlToSend = ""; foreach (Tuple <bool, string> url in url_Servers.Values) { if (!url.Item2.Equals(input[2])) { urlToSend += url.Item2 + ";"; } } if (!url_Client.ContainsKey(input[1])) { if (input.Count() == 6) { if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, "noFile")) { pid_Client.Add(input[1], input[2]); url_Client.Add(input[1], new Tuple <bool, string>(true, input[3])); Console.WriteLine("Client with PID: " + input[1] + " started."); } } if (input.Count() == 7) { if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, input[6])) { pid_Client.Add(input[1], input[2]); url_Client.Add(input[1], new Tuple <bool, string>(true, input[3])); Console.WriteLine("Client with PID: " + input[1] + " started."); } } } if (url_Client.ContainsKey(input[1]) && !url_Client[input[1]].Item1) { if (input.Count() == 6) { if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, "noFile")) { pid_Client.Add(input[1], input[2]); url_Client[input[1]] = new Tuple <bool, string>(true, input[3]); Console.WriteLine("Client with PID: " + input[1] + " started."); } } if (input.Count() == 7) { if (pcs.StartClient(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend, input[6])) { pid_Client.Add(input[1], input[2]); url_Client[input[1]] = new Tuple <bool, string>(true, input[3]); Console.WriteLine("Client with PID: " + input[1] + " started."); } } } } else { Console.WriteLine("PID already exists!"); } break; case "StartServer": //StartServer PID PCS_URL SERVER_URL MSEC_PER_ROUND NUM_PLAYERS if (input.Count() > 6) { Console.WriteLine("Invalid number of arguments to start server, expected 5 delimited by a space"); break; } if (!pid_Server.ContainsKey(input[1])) { if (url_Servers.Count == 0) { try { pcs = (IPCS)Activator.GetObject(typeof(IPCS), input[2]); } catch (RemotingException) { Console.WriteLine("Problems getting Object IPCS interface from: " + input[2]); break; } catch (ArgumentNullException) { Console.WriteLine("Url: " + input[2] + "or type is null."); break; } catch (Exception e) { Console.WriteLine("Problems trying to get PCS, exception: "); Console.WriteLine(e.ToString()); break; } if (!url_Servers.ContainsKey(input[1])) { if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), "")) { pid_Server.Add(input[1], input[2]); url_Servers.Add(input[1], new Tuple <bool, string>(true, input[3])); Console.WriteLine("Server with PID: " + input[1] + " started."); } } if (url_Servers.ContainsKey(input[1]) && !url_Servers[input[1]].Item1) { if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), "")) { pid_Server.Add(input[1], input[2]); url_Servers[input[1]] = new Tuple <bool, string>(true, input[3]); Console.WriteLine("Server with PID: " + input[1] + " started."); } } } else { pcs = (IPCS)Activator.GetObject(typeof(IPCS), input[2]); string urlToSend = ""; foreach (Tuple <bool, string> url in url_Servers.Values) { if (!url.Item2.Equals(input[2])) { urlToSend += url.Item2 + ";"; } } if (!url_Servers.ContainsKey(input[1])) { if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend)) { pid_Server.Add(input[1], input[2]); url_Servers.Add(input[1], new Tuple <bool, string>(true, input[3])); Console.WriteLine("Server with PID: " + input[1] + " started."); } } if (url_Servers.ContainsKey(input[1]) && !url_Servers[input[1]].Item1) { if (pcs.StartServer(input[1], input[3], Int32.Parse(input[4]), Int32.Parse(input[5]), urlToSend)) { pid_Server.Add(input[1], input[2]); url_Servers[input[1]] = new Tuple <bool, string>(true, input[3]); Console.WriteLine("Server with PID: " + input[1] + " started."); } } } } else { Console.WriteLine("PID already exists!"); } break; case "GlobalStatus": Parallel.ForEach(url_Servers, (s) => { try { GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject( typeof(GameApi.IServerApi), s.Value.Item2); Console.WriteLine(server.globalStatus()); } catch { Console.WriteLine("Not Connected to Server: " + s.Key); } Console.WriteLine(); }); Console.WriteLine("CLIENTS"); Console.WriteLine(); Parallel.ForEach(url_Client, (c) => { try { GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject( typeof(GameApi.IClientApi), c.Value.Item2); Console.WriteLine(client.globalStatus()); } catch { Console.WriteLine("Client with PID: " + c.Key + " crashed"); } Console.WriteLine(); }); break; case "Crash": if (pid_Server.ContainsKey(input[1])) { try { GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject( typeof(GameApi.IServerApi), url_Servers[input[1]].Item2); if (server.crash()) { Console.WriteLine("Problems trying to crash: " + input[1]); } } catch { pid_Server.Remove(input[1]); url_Servers[input[1]] = new Tuple <bool, string>(false, ""); Console.WriteLine("Server with PID: " + input[1] + " crashed"); } } else if (pid_Client.ContainsKey(input[1])) { try { GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject( typeof(GameApi.IClientApi), url_Client[input[1]].Item2); if (client.crash()) { Console.WriteLine("Problems trying to crash: " + input[1]); } } catch { pid_Client.Remove(input[1]); url_Client[input[1]] = new Tuple <bool, string>(false, ""); Console.WriteLine("Client with PID: " + input[1] + " crashed"); } } else { Console.WriteLine("PID do not exists!"); } break; case "Freeze": if (pid_Server.ContainsKey(input[1])) { GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject( typeof(GameApi.IServerApi), url_Servers[input[1]].Item2); server.freeze(true); } else if (pid_Client.ContainsKey(input[1])) { GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject( typeof(GameApi.IClientApi), url_Client[input[1]].Item2); client.freeze(true); } else { Console.WriteLine("PID do not exists!"); } break; case "Unfreeze": if (pid_Server.ContainsKey(input[1])) { GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject( typeof(GameApi.IServerApi), url_Servers[input[1]].Item2); server.freeze(false); } else if (pid_Client.ContainsKey(input[1])) { GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject( typeof(GameApi.IClientApi), url_Client[input[1]].Item2); client.freeze(false); } else { Console.WriteLine("PID do not exists!"); } break; case "InjectDelay": if (pid_Server.ContainsKey(input[1])) { GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject( typeof(GameApi.IServerApi), url_Servers[input[1]].Item2); if (server.InjectDelay(input[1], input[2])) { Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + " added"); } else { Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + "wasn't possible"); } } else if (pid_Client.ContainsKey(input[1])) { GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject( typeof(GameApi.IClientApi), url_Client[input[1]].Item2); if (client.InjectDelay(pid_Server.Keys.First(), input[2])) { Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + " added"); } else { Console.WriteLine("Delay injected between Server " + input[1] + " and PID: " + input[2] + "wasn't possible"); } } break; case "LocalState": String state = ""; if (input.Count() > 3) { Console.WriteLine("Invalid number of arguments to LocalState, expected 2 delimited by a space"); break; } if (pid_Server.ContainsKey(input[1])) { GameApi.IServerApi server = (GameApi.IServerApi)Activator.GetObject( typeof(GameApi.IServerApi), url_Servers[input[1]].Item2); state = server.LocalState(Int32.Parse(input[2])); } else if (pid_Client.ContainsKey(input[1])) { GameApi.IClientApi client = (GameApi.IClientApi)Activator.GetObject( typeof(GameApi.IClientApi), url_Client[input[1]].Item2); state = client.LocalState(Int32.Parse(input[2])); } if (!state.Equals("")) { Console.Write(state); System.IO.File.WriteAllText(Environment.CurrentDirectory + @"\..\..\LocalState-" + input[1] + "-" + input[2] + ".txt", state); } else { Console.WriteLine("Local state for that PID does not exist"); } break; case "Wait": System.Threading.Thread.Sleep(Int32.Parse(input[1])); break; default: Console.WriteLine("Command not allowed"); break; } } for (;;) { Console.Write("-> "); String command = Console.ReadLine(); String[] words = command.Split(delimiterChars); if (words[0].Equals("ReadFromScript")) { Thread t1 = new Thread(() => { String[] commands = System.IO.File.ReadAllLines(words[1]); foreach (string s in commands) { process(s.Split(delimiterChars)); } }); t1.Start(); } else { process(words); } } }
public void Dispose() { channel.StopListening(null); RemotingServices.Disconnect(factory); ChannelServices.UnregisterChannel(channel); }
static void Main(string[] args) { try { RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; bool secure = false; int port = 12345; string ipc = String.Empty; bool showhelp = false; TypeFilterLevel typefilter = TypeFilterLevel.Low; OptionSet p = new OptionSet() { { "s|secure", "Enable secure mode", v => secure = v != null }, { "p|port=", "Specify the local TCP port to listen on", v => port = int.Parse(v) }, { "t|typefilter=", "Specify the type filter level (low,full), default low", v => typefilter = (TypeFilterLevel)Enum.Parse(typeof(TypeFilterLevel), v, true) }, { "i|ipc=", "Specify listening pipe name for IPC channel", v => ipc = v }, { "h|?|help", v => showhelp = v != null }, }; p.Parse(args); if (showhelp) { Console.WriteLine("Example .NET Remoting Server"); Console.WriteLine("Copyright (c) James Forshaw 2014"); p.WriteOptionDescriptions(Console.Out); } else { Trace.Listeners.Add(new ConsoleTraceListener(true)); IChannel chan; IDictionary properties = new Hashtable(); BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider(); serverSinkProvider.TypeFilterLevel = typefilter; if (!String.IsNullOrEmpty(ipc)) { properties["portName"] = ipc; properties["authorizedGroup"] = "Everyone"; chan = new IpcChannel(properties, new BinaryClientFormatterSinkProvider(), serverSinkProvider); } else { properties["port"] = port; chan = new TcpChannel(properties, new BinaryClientFormatterSinkProvider(), serverSinkProvider); } ChannelServices.RegisterChannel(chan, secure); //register channel RemotingConfiguration.RegisterWellKnownServiceType( typeof(RemoteType), "RemotingServer", WellKnownObjectMode.Singleton); bool isipc = chan is IpcChannel; Console.WriteLine("Server Activated at {0}://{1}/RemotingServer", isipc ? "ipc" : "tcp", isipc ? ipc : "HOST:" + port.ToString()); Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private void frmRemotingServer_Load(object sender, EventArgs e) { //获取配置信息 string pstr = Environment.GetFolderPath(Environment.SpecialFolder.System); //string newStr = System.IO.Path.GetDirectoryName(str); //File.Exists(); filename = pstr + "\\" + "r_emr_regist.txt"; string link = Decrypt(File.ReadAllText("datalink.txt").Split(',')[0]); string mysqllink = Decrypt(File.ReadAllText("mysqldatalink.txt")); string orcl_connectionString = string.Format(@"Persist Security Info=False;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SID={2})));user id={3};password={4}", link.Split(',')[0], link.Split(',')[1], link.Split(',')[2], link.Split(',')[3], link.Split(',')[4]); Operater = new DbHelp(); //Operater.orcl_connectionString = orcl_connectionString; Operater.mysql_connectionString = "data source=localhost;database=emrbzb;user id=root;password=111111;pooling=true;charset=utf8;Convert Zero Datetime=True;Allow Zero Datetime=True"; //mysqllink; bool yy = Operater.ConnectTest_MySql(); // DataSet ds = Operater.GetDataSet_MySql("select a.id,a.patient_name as 姓名,a.pid as 住院号,a.section_name as 科室 from t_in_patient a where a.id in (select patient_id from t_patients_doc where tid in (select tid from t_patient_doc_colb)) order by id desc"); //DataSet ds = Operater.GetDataSet_MySql("select * from T_ACCOUNT where upper(ACCOUNT_NAME)='FK' and PASSWORD='******'"); DataSet ds = Operater.GetDataSet_MySql("select n.ACCOUNT_ID,n.ENABLE_START_TIME from t_account n where n.ENABLE_START_TIME is not NULL LIMIT 1"); if (File.Exists(filename)) { regiestCode = File.ReadAllText(filename).Split(',')[1]; if (regiestCode != "") { if (frmRemotingServer.Encrypt(GetCpuID()) != regiestCode) { File.Delete(filename); MessageBox.Show("注册码被恶意修改,请重新注册!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); Application.Restart(); } } } if (Port == 0) { if (!File.Exists(filename)) { //首次使用 DateTime dte = Operater.GetSystemTime().AddDays(100); string w = Encrypt(dte.ToString()) + ","; File.WriteAllText(filename, w); //regiestCode = File.ReadAllText(filename).Split(',')[1]; } frmPortSet fc = new frmPortSet(); fc.ShowDialog(); } timer1.Enabled = true; TimeSpan ff = new TimeSpan(0); if (RemotingType == "tcp") { #region TCP模式 RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; RemotingConfiguration.CustomErrorsEnabled(false); System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime = ff; BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; IDictionary props = new Hashtable(); props["port"] = Port; TcpChannel chan = new TcpChannel(props, null, provider); ChannelServices.RegisterChannel(chan, false); ObjRef obj = RemotingServices.Marshal(Operater, "Tcpservice"); //Tcpservice RemotingServices.Unmarshal(obj); #endregion } else { #region Http模式 HttpServerChannel serverChannel = new HttpServerChannel(Port); //RemoteObject.soap ChannelServices.RegisterChannel(serverChannel, false); // Expose an object for remote calls. RemotingConfiguration.RegisterWellKnownServiceType( typeof(DbHelp), "RemoteObject.soap", WellKnownObjectMode.Singleton); #endregion } notifyIcon1.Text = "端口号:" + Port.ToString() + "remoting服务正在运行中,协议模式" + RemotingType; this.Visible = false; lbllimit.Text = "CPUID:" + GetCpuID(); }
/// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { var c = new Control(); c.CreateControl(); s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); }
private void PrivateInvoke(ref MessageData msgData, int type) { IMessage message1 = (IMessage)null; CallType callType = (CallType)type; IMessage message2 = (IMessage)null; int msgFlags = -1; RemotingProxy remotingProxy = (RemotingProxy)null; if (CallType.MethodCall == callType) { Message message3 = new Message(); MessageData msgData1 = msgData; message3.InitFields(msgData1); message1 = (IMessage)message3; msgFlags = message3.GetCallType(); } else if (CallType.ConstructorCall == callType) { msgFlags = 0; remotingProxy = this as RemotingProxy; bool flag = false; ConstructorCallMessage constructorCallMessage1; if (!this.IsRemotingProxy()) { constructorCallMessage1 = new ConstructorCallMessage((object[])null, (object[])null, (object[])null, (RuntimeType)this.GetProxiedType()); } else { constructorCallMessage1 = remotingProxy.ConstructorMessage; Identity identityObject = remotingProxy.IdentityObject; if (identityObject != null) { flag = identityObject.IsWellKnown(); } } if (constructorCallMessage1 == null | flag) { ConstructorCallMessage constructorCallMessage2 = new ConstructorCallMessage((object[])null, (object[])null, (object[])null, (RuntimeType)this.GetProxiedType()); constructorCallMessage2.SetFrame(msgData); message1 = (IMessage)constructorCallMessage2; if (flag) { remotingProxy.ConstructorMessage = (ConstructorCallMessage)null; if (constructorCallMessage2.ArgCount != 0) { throw new RemotingException(Environment.GetResourceString("Remoting_Activation_WellKnownCTOR")); } } message2 = (IMessage) new ConstructorReturnMessage((MarshalByRefObject)this.GetTransparentProxy(), (object[])null, 0, (LogicalCallContext)null, (IConstructionCallMessage)constructorCallMessage2); } else { constructorCallMessage1.SetFrame(msgData); message1 = (IMessage)constructorCallMessage1; } } ChannelServices.IncrementRemoteCalls(); if (!this.IsRemotingProxy() && (msgFlags & 2) == 2) { message2 = RealProxy.EndInvokeHelper(message1 as Message, true); } if (message2 == null) { Thread currentThread = Thread.CurrentThread; LogicalCallContext logicalCallContext = currentThread.GetMutableExecutionContext().LogicalCallContext; this.SetCallContextInMessage(message1, msgFlags, logicalCallContext); logicalCallContext.PropagateOutgoingHeadersToMessage(message1); message2 = this.Invoke(message1); this.ReturnCallContextToThread(currentThread, message2, msgFlags, logicalCallContext); Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext.PropagateIncomingHeadersToCallContext(message2); } if (!this.IsRemotingProxy() && (msgFlags & 1) == 1) { Message m = message1 as Message; AsyncResult asyncResult = new AsyncResult(m); IMessage msg = message2; asyncResult.SyncProcessMessage(msg); // ISSUE: variable of the null type __Null local1 = null; int outArgsCount = 0; // ISSUE: variable of the null type __Null local2 = null; Message message3 = m; message2 = (IMessage) new ReturnMessage((object)asyncResult, (object[])local1, outArgsCount, (LogicalCallContext)local2, (IMethodCallMessage)message3); } RealProxy.HandleReturnMessage(message1, message2); if (CallType.ConstructorCall != callType) { return; } IConstructionReturnMessage constructionReturnMessage = message2 as IConstructionReturnMessage; if (constructionReturnMessage == null) { throw new RemotingException(Environment.GetResourceString("Remoting_Proxy_BadReturnTypeForActivation")); } ConstructorReturnMessage constructorReturnMessage = constructionReturnMessage as ConstructorReturnMessage; MarshalByRefObject marshalByRefObject; if (constructorReturnMessage != null) { marshalByRefObject = (MarshalByRefObject)constructorReturnMessage.GetObject(); if (marshalByRefObject == null) { throw new RemotingException(Environment.GetResourceString("Remoting_Activation_NullReturnValue")); } } else { marshalByRefObject = (MarshalByRefObject)RemotingServices.InternalUnmarshal((ObjRef)constructionReturnMessage.ReturnValue, this.GetTransparentProxy(), true); if (marshalByRefObject == null) { throw new RemotingException(Environment.GetResourceString("Remoting_Activation_NullFromInternalUnmarshal")); } } if (marshalByRefObject != (MarshalByRefObject)this.GetTransparentProxy()) { throw new RemotingException(Environment.GetResourceString("Remoting_Activation_InconsistentState")); } if (!this.IsRemotingProxy()) { return; } remotingProxy.ConstructorMessage = (ConstructorCallMessage)null; }
public void StopHttpServer() { ChannelServices.UnregisterChannel(serverChannel); }
public ChannelInfo() { channelData = ChannelServices.GetCurrentChannelInfo(); }
public void CloseConnection() { ChannelServices.UnregisterChannel(TcpChannelInst); }
static void Main(string[] args) { try { string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; ValueManager.ValueManagerType = typeof(MultiThreadValueManager <>).GetGenericTypeDefinition(); ServerApplication serverApplication = new ServerApplication(); serverApplication.ApplicationName = "BPIWABK"; serverApplication.CheckCompatibilityType = CheckCompatibilityType.DatabaseSchema; if (System.Diagnostics.Debugger.IsAttached && serverApplication.CheckCompatibilityType == CheckCompatibilityType.DatabaseSchema) { serverApplication.DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways; } serverApplication.Modules.BeginInit(); serverApplication.Modules.Add(new DevExpress.ExpressApp.Security.SecurityModule()); serverApplication.Modules.Add(new BPIWABK.Module.BPIWABKModule()); serverApplication.Modules.Add(new BPIWABK.Module.Win.BPIWABKWindowsFormsModule()); serverApplication.Modules.Add(new BPIWABK.Module.Web.BPIWABKAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.AuditTrail.AuditTrailModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Objects.BusinessClassLibraryCustomizationModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Chart.ChartModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Chart.Win.ChartWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Chart.Web.ChartAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.CloneObject.CloneObjectModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.ConditionalAppearance.ConditionalAppearanceModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Dashboards.DashboardsModule() { DashboardDataType = typeof(DevExpress.Persistent.BaseImpl.DashboardData) }); serverApplication.Modules.Add(new DevExpress.ExpressApp.Dashboards.Win.DashboardsWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Dashboards.Web.DashboardsAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.FileAttachments.Win.FileAttachmentsWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.FileAttachments.Web.FileAttachmentsAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.HtmlPropertyEditor.Win.HtmlPropertyEditorWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.HtmlPropertyEditor.Web.HtmlPropertyEditorAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.PivotChart.PivotChartModuleBase()); serverApplication.Modules.Add(new DevExpress.ExpressApp.PivotChart.Win.PivotChartWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.PivotChart.Web.PivotChartAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.PivotGrid.PivotGridModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.PivotGrid.Win.PivotGridWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.PivotGrid.Web.PivotGridAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.ReportsV2.ReportsModuleV2() { ReportDataType = typeof(DevExpress.Persistent.BaseImpl.ReportDataV2) }); serverApplication.Modules.Add(new DevExpress.ExpressApp.ReportsV2.Win.ReportsWindowsFormsModuleV2()); serverApplication.Modules.Add(new DevExpress.ExpressApp.ReportsV2.Web.ReportsAspNetModuleV2()); serverApplication.Modules.Add(new DevExpress.ExpressApp.TreeListEditors.TreeListEditorsModuleBase()); serverApplication.Modules.Add(new DevExpress.ExpressApp.TreeListEditors.Win.TreeListEditorsWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.TreeListEditors.Web.TreeListEditorsAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Validation.ValidationModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Validation.Win.ValidationWindowsFormsModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.Validation.Web.ValidationAspNetModule()); serverApplication.Modules.Add(new DevExpress.ExpressApp.ViewVariantsModule.ViewVariantsModule()); serverApplication.Modules.EndInit(); serverApplication.DatabaseVersionMismatch += new EventHandler <DatabaseVersionMismatchEventArgs>(serverApplication_DatabaseVersionMismatch); serverApplication.CreateCustomObjectSpaceProvider += new EventHandler <CreateCustomObjectSpaceProviderEventArgs>(serverApplication_CreateCustomObjectSpaceProvider); serverApplication.ConnectionString = connectionString; Console.WriteLine("Mempersiapkan..."); serverApplication.Setup(); Console.WriteLine("Memeriksa kompatibilitas..."); serverApplication.CheckCompatibility(); serverApplication.Dispose(); WcfDataServerHelper.AddKnownType(typeof(ExportPermissionRequest)); Console.WriteLine("Memulai layanan..."); //ServerPermissionPolicyRequestProcessor.UseAutoAssociationPermission = true; QueryRequestSecurityStrategyHandler securityProviderHandler = delegate() { SecurityStrategyComplex security = new SecurityStrategyComplex( typeof(Pegawai), typeof(Peran), new AuthenticationStandard()); security.CustomizeRequestProcessors += delegate(object sender, CustomizeRequestProcessorsEventArgs e) { List <IOperationPermission> result = new List <IOperationPermission>(); if (security != null) { Pegawai user = security.User as Pegawai; if (user != null) { foreach (Peran role in user.Roles) { if (role.CanExport) { result.Add(new ExportPermission()); } } } } IPermissionDictionary permissionDictionary = new PermissionDictionary((IEnumerable <IOperationPermission>)result); e.Processors.Add(typeof(ExportPermissionRequest), new ExportPermissionRequestProcessor(permissionDictionary)); }; return(security); }; SecuredDataServer dataServer = new SecuredDataServer(connectionString, XpoTypesInfoHelper.GetXpoTypeInfoSource().XPDictionary, securityProviderHandler); RemoteSecuredDataServer.Initialize(dataServer); //"Authentication with the TCP Channel" at http://msdn.microsoft.com/en-us/library/59hafwyt(v=vs.80).aspx IDictionary t = new Hashtable(); t.Add("port", 8082); //t.Add("secure", true); //t.Add("impersonate", false); if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Test"]) == false) { Console.WriteLine("Test"); } TcpChannel channel = new TcpChannel(t, null, null); ChannelServices.RegisterChannel(channel, true); RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteSecuredDataServer), "DataServer", WellKnownObjectMode.Singleton); Console.WriteLine("Layanan telah dimulai..."); Console.WriteLine(""); Console.WriteLine("PERINGATAN: aplikasi Analisis Beban Kerja tidak dapat digunakan apabila layanan di hentikan!"); Console.WriteLine("Apabila layanan telah di hentikan, jalankan BPIWABK.Console.exe untuk kembali memulai layanan."); Console.WriteLine("Tekan tombol Enter untuk menghentikan layanan."); Console.ReadLine(); Console.WriteLine("Menghetikan..."); ChannelServices.UnregisterChannel(channel); Console.WriteLine("Layanan telah dihentikan."); } catch (Exception e) { Console.WriteLine("Kesalahan terjadi: " + e.Message); Console.WriteLine("Tekan tombol Enter untuk menutup."); Console.ReadLine(); } }
static void Main(string[] args) { string Url = "tcp://localhost:50001/S"; int MinDelay = 0; int MaxDelay = 0; int Port; string Name; List <String> Servers = new List <string>(); string serverid2 = "none"; List <ITuple> newState = new List <ITuple>(); View newview = new View(); string mode = "b"; //Type of algorithm for server string algorithm = "x"; if (args.Length > 0) { Url = args[0]; algorithm = args[1]; } Port = getPortFromURL(Url); Name = getNameFromURL(Url); channel = new TcpChannel(Port); ChannelServices.RegisterChannel(channel, true); if (args.Length == 5) { MinDelay = Int32.Parse(args[1]); MaxDelay = Int32.Parse(args[2]); algorithm = args[3]; mode = args[4]; } if (args.Length == 6) { MinDelay = Int32.Parse(args[1]); MaxDelay = Int32.Parse(args[2]); algorithm = args[4]; serverid2 = args[3]; mode = args[5]; } if (algorithm == "x") { if (mode == "a") { //Server we are going to execute TSpaceAdvServerXL TS = null; //Server we are going to get our state from TSpaceAdvServerXL server = null; if (!serverid2.Equals("none")) { TS = new TSpaceAdvServerXL(Url, MinDelay, MaxDelay); } else { Console.WriteLine("no previous state exists"); //if we dont get a state we initialize with an empty view TS = new TSpaceAdvServerXL(Url, MinDelay, MaxDelay, newview); } RemotingServices.Marshal(TS, Name, typeof(TSpaceAdvServerXL)); try { if (!serverid2.Equals("none")) { //get the remote server server = (TSpaceAdvServerXL)Activator.GetObject(typeof(TSpaceAdvServerXL), serverid2); //execute changestate on the server we are going to execute TS.ChangeState(server, Url); } else { Console.WriteLine("No previous state"); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.GetType().ToString()); Console.WriteLine(e.StackTrace); } } if (mode == "b") { TSpaceServerXL TS = null; TSpaceServerXL server = null; if (!serverid2.Equals("none")) { TS = new TSpaceServerXL(Url, MinDelay, MaxDelay); } else { Console.WriteLine("no previous state exists"); TS = new TSpaceServerXL(Url, MinDelay, MaxDelay, newview); } RemotingServices.Marshal(TS, Name, typeof(TSpaceServerXL)); try { if (!serverid2.Equals("none")) { server = (TSpaceServerXL)Activator.GetObject(typeof(TSpaceServerXL), serverid2); TS.changeState(server, Url); } else { Console.WriteLine("No previous state"); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.GetType().ToString()); Console.WriteLine(e.StackTrace); } } } if (algorithm == "s") { if (mode == "a") { TSpaceAdvServerSMR TS = null; TSpaceAdvServerSMR server = null; if (!serverid2.Equals("none")) { TS = new TSpaceAdvServerSMR(Url, MinDelay, MaxDelay); } else { Console.WriteLine("no previous state exists"); TS = new TSpaceAdvServerSMR(Url, MinDelay, MaxDelay, newview); } RemotingServices.Marshal(TS, Name, typeof(TSpaceAdvServerSMR)); try { if (!serverid2.Equals("none")) { server = (TSpaceAdvServerSMR)Activator.GetObject(typeof(TSpaceAdvServerSMR), serverid2); TS.ChangeState(server, Url); } else { Console.WriteLine("No previous state"); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.GetType().ToString()); Console.WriteLine(e.StackTrace); } } if (mode == "b") { TSpaceServerSMR TS = null; TSpaceServerSMR server = null; if (!serverid2.Equals("none")) { TS = new TSpaceServerSMR(Url, MinDelay, MaxDelay); } else { Console.WriteLine("no previous state exists"); TS = new TSpaceServerSMR(Url, MinDelay, MaxDelay, newview); } RemotingServices.Marshal(TS, Name, typeof(TSpaceServerSMR)); try { if (!serverid2.Equals("none")) { server = (TSpaceServerSMR)Activator.GetObject(typeof(TSpaceServerSMR), serverid2); TS.changeState(server, Url); } else { Console.WriteLine("No previous state"); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.GetType().ToString()); Console.WriteLine(e.StackTrace); } } } System.Console.WriteLine("<enter> para sair..."); System.Console.ReadLine(); }
public static void EndRemotingService(TcpChannel channel) { ChannelServices.UnregisterChannel(channel); }
static void Main(string[] args) { try { RemotingConfiguration.Configure("..\\..\\App.config", true); String userName = args[1]; String clientUrl = args[2]; String serverUrl = args[3]; String scriptFileName = args[4]; Uri clientUri = new Uri(clientUrl); BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = clientUri.Port; //props["timeout"] = 10000; // in milliseconds TcpChannel channel = new TcpChannel(props, null, provider); //TcpChannel channel = new TcpChannel(clientUri.Port); ChannelServices.RegisterChannel(channel, false); Console.WriteLine(userName); ClientImpl MeetingClient = new ClientImpl(userName); RemotingServices.Marshal(MeetingClient, clientUri.Segments[1], typeof(ClientImpl)); ServerInterface server = (ServerInterface)Activator.GetObject(typeof(ServerInterface), serverUrl); server.Connect(clientUrl, userName); bool interactive = true; StreamReader file = new StreamReader(scriptFileName); string command = file.ReadLine(); Console.Write(" h - imprimir esta ajuda\r\n n - executar o próximo comando\r\n l - imprimir próximo comando\r\n r - correr todos os comandos restantes\r\n"); while (command != null) { if (interactive) { Console.Write("> "); switch (Console.ReadLine()) { case "n": Console.WriteLine(command); MeetingClient.ReadCommands(command); command = file.ReadLine(); break; case "l": Console.WriteLine(command); break; case "r": interactive = false; break; case "h": Console.Write(" h - imprimir esta ajuda\r\n n - executar o próximo comando\r\n l - imprimir próximo comando\r\n r - correr todos os comandos restantes\r\n"); break; } } else { MeetingClient.ReadCommands(command); command = file.ReadLine(); } } file.Close(); while (true) { command = Console.ReadLine(); MeetingClient.ReadCommands(command); } } catch (Exception e) { Console.WriteLine(e.StackTrace); Console.WriteLine(e.Message); Console.ReadLine(); } }
static void Main(string[] args) { var config = new DataTypes.ConfigurationFileObject(PuppetSettings.Default.ConfigFile); //Use this to read configuration files. //var v = DataTypes.ConfigurationFileObject.ReadConfig("Test.config"); //or this var pcsaddresses = config.ConfigurationNodes.SelectMany(i => i.PCSAddress).Distinct().ToList(); INodeManager pcs = null; TcpChannel channel = new TcpChannel(9999); ChannelServices.RegisterChannel(channel, true); int port = 10000; int portNodes = 11000; foreach (var address in config.ConfigurationNodes.SelectMany(i => i.Addresses)) //Config node = details of one operation { nodeAddressMapping.Add(address, "tcp://localhost:" + portNodes + "/op" + portNodes); //Creates the same mapping but for the nodes instead of the pcs portNodes += 1; } portNodes = 11000; foreach (var uniqAddress in pcsaddresses) //Iteration over all the PCSs { pcsAddressMapping.Add(uniqAddress, "localhost:" + port++); //Create a mapping for the real (localhost) address pcs = (INodeManager)Activator.GetObject(typeof(INodeManager), "tcp://" + pcsAddressMapping[uniqAddress] + "/NodeManagerService"); List <DADStorm.DataTypes.NodeOperatorData> ListOfNodeInformations = new List <DADStorm.DataTypes.NodeOperatorData>(); var ConfigNodesWherePCSIsIncluded = config.getNodesFromPCS(uniqAddress); foreach (var ConfigNode in ConfigNodesWherePCSIsIncluded) //Iteration over all the configuration nodes for that PCS { var NodeAddresses = ConfigNode.Addresses.Where(i => i.Contains(uniqAddress)).ToList(); //Fake (remote) Addresses of the node foreach (var NodeAddress in NodeAddresses) { List <DADStorm.DataTypes.Downstream> downstream = new List <DADStorm.DataTypes.Downstream>(); List <string> siblings = new List <string>(); foreach (var node in ConfigNode.Addresses) //Creation of a list of siblings { if (!node.Equals(NodeAddress)) { siblings.Add(nodeAddressMapping[node]); } } foreach (var OperatorConfig in config.getNodesRequiringOPName(ConfigNode.NodeName)) //Configuration nodes that require our operation (downstreams) { var listOfDownstreamNodes = new List <string>(); foreach (var downstreamnode in OperatorConfig.Addresses) { listOfDownstreamNodes.Add(nodeAddressMapping[downstreamnode]); } downstream.Add(new DADStorm.DataTypes.Downstream() { Routing = OperatorConfig.Routing, TargetIPs = listOfDownstreamNodes }); } List <DADTuple> initialTuples; if (ConfigNode.TargetData.Contains(".")) { initialTuples = DADTuple.InputFileReader(ConfigNode.TargetData); } else { initialTuples = new List <DADTuple>(); } List <string> Opargs; if (ConfigNode.Operation == DADStorm.DataTypes.OperatorType.custom) { byte[] code = File.ReadAllBytes(ConfigNode.OperationArgs[0]); Opargs = new List <string>() { code.ToString(), ConfigNode.OperationArgs[1] }; } else { Opargs = ConfigNode.OperationArgs; } DADStorm.DataTypes.NodeOperatorData data = new DADStorm.DataTypes.NodeOperatorData() { OperatorID = ConfigNode.NodeName, ConnectionPort = portNodes++, OperatorName = "op", //TODO:Change this to come from config TypeofRouting = ConfigNode.Routing, Siblings = siblings, Downstream = downstream, TypeofOperation = ConfigNode.Operation, OperationArgs = Opargs, Initialtuples = initialTuples, NodeAddress = NodeAddress, LogTuples = (config.Logging == DataTypes.LoggingLevel.full) }; ListOfNodeInformations.Add(data); //New node that will be created by the PCS with the data stated right up here. } } //DADStorm.DataTypes.NodeOperatorData nop = new DADStorm.DataTypes.NodeOperatorData() //{ //} var bo = pcs.init(ListOfNodeInformations); GC.KeepAlive(pcs); pcsServers.Add(uniqAddress, pcs); } //TcpChannel channelLog = new TcpChannel(9999); //ChannelServices.RegisterChannel(channelLog, true); System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType( typeof(Logger), "logger", System.Runtime.Remoting.WellKnownObjectMode.Singleton); System.Console.WriteLine("Logging Service open on port: 9999"); ILogger Logger = (ILogger)Activator.GetObject(typeof(ILogger), "tcp://localhost:9999/logger"); //var test = config.ConfigurationNodes.Where(i => i.NodeName == "OP1").ToList().First().PCSAddress.First(); GC.KeepAlive(Logger); /* if (pcsLocalhost == null) { * System.Console.WriteLine("Could not locate server."); * return; * }*/ foreach (var line in config.Script) { Logger.log(line.ToString()); string[] command = line.ToString().Split(null); try { handleInput(config, command); } catch (IndexOutOfRangeException) { Console.WriteLine("Invalid Arguments"); } } Console.WriteLine(); Console.WriteLine("Available commands are:"); Console.WriteLine(" start OP_ID"); Console.WriteLine(" status"); Console.WriteLine(" interval time"); Console.WriteLine(" crash OP_ID Rep_ID"); Console.WriteLine(" freeze OP_ID Rep_ID"); Console.WriteLine(" unfreeze OP_ID Rep_ID"); Console.WriteLine(); while (true) { string commandLine = Console.ReadLine(); Logger.log(commandLine); string[] command = commandLine.Split(null); try { handleInput(config, command); } catch (IndexOutOfRangeException) { Console.WriteLine("Invalid Arguments"); } } }
public virtual ManagerStateEnum Start(long priority, IServiceDescriptor serviceDescriptor) { if (this.ManagerState != ManagerStateEnum.Started) { if (priority < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("priority"); } if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("{0}, initializing service...", LOG_PREFIX)); } OnStart(ManagerEventStateEnum.Before); try { ChannelServices.Initialize(); this.ChannelId = ConfigurationAccessHelper.GetValueByPath(NetworkServiceConfiguration.Settings.CategoryPropertyItems, string.Format("Services/{0}", Id)); if (string.IsNullOrEmpty(this.ChannelId)) { this.ChannelId = Id; } Channel channel = LookUpChannel(); if (channel.ServerEndpoints.Count == 0) { throw new InvalidConfigurationException(string.Format("Channel '{0}' has not got listening server endpoint(s).", channel.ChannelId)); } ServiceBaseServices.Initialize(); if (!ServiceBaseServices.IsContractRegistered(typeof(TIServiceProxyType))) { ServiceBaseServices.RegisterContract(typeof(TIServiceProxyType), typeof(TServiceProxyImplementationType)); } this.mPriority = priority; this.mServiceDescriptor = serviceDescriptor; RegisterToPeerContext(channel, priority, serviceDescriptor); this.ManagerState = ManagerStateEnum.Started; if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("{0}, service successfully initialized.", LOG_PREFIX)); } } catch (Exception) { this.ManagerState = ManagerStateEnum.Fault; throw; } OnStart(ManagerEventStateEnum.After); } return(this.ManagerState); }
static void Main(string[] args) { if (args.Length == 0) { TcpChannel channel = new TcpChannel(8086); ChannelServices.RegisterChannel(channel, false); System.Console.WriteLine("Desired game rate:"); MSEC_PER_ROUND = Console.ReadLine(); System.Console.WriteLine("Number of players:"); NUM_PLAYERS = Int32.Parse(Console.ReadLine()); } else { string url = args[0]; string[] urlSplit = url.Split(':', '/'); TcpChannel channel = new TcpChannel(Int32.Parse(urlSplit[4])); ChannelServices.RegisterChannel(channel, false); System.Console.WriteLine("Desired game rate:"); MSEC_PER_ROUND = args[1]; System.Console.WriteLine(args[1]); System.Console.WriteLine("Number of players:"); NUM_PLAYERS = Int32.Parse(Console.ReadLine()); System.Console.WriteLine(args[2]); } //Alternative 1 //RemotingConfiguration.RegisterWellKnownServiceType( // typeof(ServerServices), "Server", // WellKnownObjectMode.Singleton); //Alternative 2 ServerServices service = new ServerServices(); RemotingServices.Marshal(service, "Server", typeof(ServerServices)); if (MSEC_PER_ROUND == "") { MSEC_PER_ROUND = "20"; } gamesettings = true; Console.WriteLine("Clients number -> " + clients.Count); while (clients.Count != NUM_PLAYERS) { lock (_lock) { Monitor.Wait(_lock); } } foreach (IClient client in clients.ToList()) { System.Console.WriteLine(client.GetHashCode()); client.startGame(MSEC_PER_ROUND, NUM_PLAYERS.ToString()); } while (service.ready < NUM_PLAYERS) { lock (_lock1) { Monitor.Wait(_lock1); } } gamestarted = true; //indicates that a game as started engine.start(); System.Threading.Thread.Sleep(1000); engine.startTimer(MSEC_PER_ROUND); engine.seePacmans(); System.Console.WriteLine("Press <enter> to terminate game server..."); System.Console.ReadLine(); }
/// <summary> /// Stop this service. /// </summary> protected override void OnStop() { ChannelServices.UnregisterChannel(myChannel); }
public static int Main(string[] args) { AgentId = new Guid(args[0]); AgencyUrl = args[1]; #if DEBUG bool pause = false; #endif bool verbose = false; for (int i = 2; i < args.Length; i++) { switch (args[i]) { #if DEBUG case "--pause": pause = true; break; #endif case "--verbose": verbose = true; break; } } #if DEBUG if (pause) { System.Windows.Forms.MessageBox.Show("Attach debugger if desired, then press OK", "NUnit-Agent"); } #endif // Create SettingsService early so we know the trace level right at the start SettingsService settingsService = new SettingsService(false); //InternalTrace.Initialize("nunit-agent_%p.log", (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Default)); //log.Info("Agent process {0} starting", Process.GetCurrentProcess().Id); //log.Info("Running under version {0}, {1}", // Environment.Version, // RuntimeFramework.CurrentFramework.DisplayName); if (verbose) { Console.WriteLine("Agent process {0} starting", Process.GetCurrentProcess().Id); Console.WriteLine("Running under version {0}, {1}", Environment.Version, RuntimeFramework.CurrentFramework.DisplayName); } // Create TestEngine - this program is // conceptually part of the engine and // can access it's internals as needed. TestEngine engine = new TestEngine(); // Custom Service Initialization //log.Info("Adding Services"); engine.Services.Add(settingsService); engine.Services.Add(new ProjectService()); engine.Services.Add(new DomainManager()); engine.Services.Add(new InProcessTestRunnerFactory()); engine.Services.Add(new DriverFactory()); //engine.Services.Add( new TestLoader() ); // Initialize Services //log.Info("Initializing Services"); engine.Services.ServiceManager.InitializeServices(); Channel = ServerUtilities.GetTcpChannel(); //log.Info("Connecting to TestAgency at {0}", AgencyUrl); try { Agency = Activator.GetObject(typeof(ITestAgency), AgencyUrl) as ITestAgency; } catch (Exception ex) { Console.WriteLine("Unable to connect\r\n{0}", ex); //log.Error("Unable to connect", ex); } if (Channel != null) { //log.Info("Starting RemoteTestAgent"); RemoteTestAgent agent = new RemoteTestAgent(AgentId, Agency, engine.Services); try { if (agent.Start()) { //log.Debug("Waiting for stopSignal"); agent.WaitForStop(); //log.Debug("Stop signal received"); } else { Console.WriteLine("Failed to start RemoteTestAgent"); } //log.Error("Failed to start RemoteTestAgent"); } catch (Exception ex) { //log.Error("Exception in RemoteTestAgent", ex); Console.WriteLine("Exception in RemoteTestAgent", ex); } //log.Info("Unregistering Channel"); try { ChannelServices.UnregisterChannel(Channel); } catch (Exception ex) { //log.Error("ChannelServices.UnregisterChannel threw an exception", ex); Console.WriteLine("ChannelServices.UnregisterChannel threw an exception\r\n{0}", ex); } } if (verbose) { Console.WriteLine("Agent process {0} exiting", Process.GetCurrentProcess().Id); } //log.Info("Agent process {0} exiting", Process.GetCurrentProcess().Id); //InternalTrace.Close(); return(0); }
/// <summary> /// Instantiates a new SingleInstanceTracker object. /// When using this constructor overload and enforcerRetriever is null, the SingleInstanceTracker object can only be used to determine whether the application is already running. /// </summary> /// <param name="name">The unique name used to identify the application.</param> /// <param name="enforcerRetriever">The method which would be used to retrieve an ISingleInstanceEnforcer object when instantiating the new object.</param> /// <exception cref="System.ArgumentNullException">name is null or empty.</exception> /// <exception cref="SingleInstancing.SingleInstancingException">A general error occured while trying to instantiate the SingleInstanceInteractor. See InnerException for more details.</exception> public SingleInstanceTracker(string name, SingleInstanceEnforcerRetriever enforcerRetriever) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name", @"name cannot be null or empty."); } try { // Do not attempt to construct the IPC channel if there is no need for messages if (enforcerRetriever != null) { #if IPC_SUPPORTS fSingleInstanceMutex = new Mutex(true, name, out fIsFirstInstance); const string proxyObjectName = "SingleInstanceProxy"; string proxyUri = "ipc://" + name + "/" + proxyObjectName; // If no previous instance was found, create a server channel which will provide the proxy to the first created instance if (fIsFirstInstance) { // Create an IPC server channel to listen for SingleInstanceProxy object requests fIpcChannel = new IpcServerChannel(name); // Register the channel and get it ready for use ChannelServices.RegisterChannel(fIpcChannel, false); // Register the service which gets the SingleInstanceProxy object, so it can be accessible by IPC client channels RemotingConfiguration.RegisterWellKnownServiceType(typeof(SingleInstanceProxy), proxyObjectName, WellKnownObjectMode.Singleton); // Attempt to retrieve the enforcer from the delegated method ISingleInstanceEnforcer enforcer = enforcerRetriever(); // Validate that an enforcer object was returned if (enforcer == null) { throw new InvalidOperationException("The method delegated by the enforcerRetriever argument returned null. The method must return an ISingleInstanceEnforcer object."); } // Create the first proxy object fProxy = new SingleInstanceProxy(enforcer); // Publish the first proxy object so IPC clients requesting a proxy would receive a reference to it RemotingServices.Marshal(fProxy, proxyObjectName); } else { // Create an IPC client channel to request the existing SingleInstanceProxy object. fIpcChannel = new IpcClientChannel(); // Register the channel and get it ready for use ChannelServices.RegisterChannel(fIpcChannel, false); // Retreive a reference to the proxy object which will be later used to send messages fProxy = (SingleInstanceProxy)Activator.GetObject(typeof(SingleInstanceProxy), proxyUri); // Notify the first instance of the application that a new instance was created fProxy.Enforcer.OnNewInstanceCreated(new EventArgs()); } #else fIsFirstInstance = IpcFake.CreateMutex(name, true); if (fIsFirstInstance) { // Attempt to retrieve the enforcer from the delegated method ISingleInstanceEnforcer enforcer = enforcerRetriever(); // Validate that an enforcer object was returned if (enforcer == null) { throw new InvalidOperationException("The method delegated by the enforcerRetriever argument returned null. The method must return an ISingleInstanceEnforcer object."); } // Create the first proxy object fProxy = new SingleInstanceProxy(enforcer); IpcFake.StartServer(enforcer); } else { } #endif } } catch (Exception ex) { throw new SingleInstancingException("Failed to instantiate a new SingleInstanceTracker object. See InnerException for more details.", ex); } }
private static void Main(string[] args) { string game; int mseconsRound; int numberPlayers; TcpChannel channel; string ip; string port; string url; string masterUrl; switch (args.Length) { case 5: game = args[0]; mseconsRound = int.Parse(args[1]); numberPlayers = int.Parse(args[2]); ip = args[3]; port = args[4]; channel = new TcpChannel(int.Parse(port)); ChannelServices.RegisterChannel(channel, false); Console.WriteLine(game); Console.WriteLine(mseconsRound); Console.WriteLine(numberPlayers); Console.WriteLine(ip); Console.WriteLine(port); if (game.Equals("Pacman")) { url = "tcp://" + ip + ":" + port; var server = new PacManServer(mseconsRound, numberPlayers, url); RemotingServices.Marshal(server, "PacManServer", typeof(PacManServer)); } break; case 6: game = args[0]; mseconsRound = int.Parse(args[1]); numberPlayers = int.Parse(args[2]); ip = args[3]; port = args[4]; channel = new TcpChannel(int.Parse(port)); ChannelServices.RegisterChannel(channel, false); masterUrl = args[5]; if (game.Equals("Pacman")) { url = "tcp://" + ip + ":" + port; Console.WriteLine(game); Console.WriteLine(mseconsRound); Console.WriteLine(numberPlayers); Console.WriteLine(ip); Console.WriteLine(port); Console.WriteLine(url); Console.WriteLine(masterUrl); var server = new PacManServer(mseconsRound, numberPlayers, url, masterUrl); RemotingServices.Marshal(server, "PacManServer", typeof(PacManServer)); } break; } /*var channel = new TcpChannel(8086); * ChannelServices.RegisterChannel(channel, false); * * Console.WriteLine("What is the game you want to play?"); * var game = Console.ReadLine(); * * Console.WriteLine("Enter miliseconds per round"); * var msecondsRound = Console.ReadLine(); * * Console.WriteLine("Enter number of players"); * var numberPlayers = Console.ReadLine(); * * switch (game){ * case "PacMan": * var server = new PacManServer(int.Parse(msecondsRound), int.Parse(numberPlayers)); * RemotingServices.Marshal(server, "PacManServer", typeof(PacManServer)); * break; * } */ Console.WriteLine("Press <enter> to exit"); Console.ReadLine(); }
public Shell() { chan = new TcpChannel(); ChannelServices.RegisterChannel(chan, false); obj = (SharedObject)Activator.GetObject(typeof(SortLibrary.SharedObject), "tcp://localhost:8081/DataPool"); }
internal void TcpConnect() { TcpChannel channel = new TcpChannel(PORT); ChannelServices.RegisterChannel(channel, true); }
static void Main(string[] args) { if (args.Length != 6) { System.Console.WriteLine("<usage> Client username client_port network_name server_url script_file client_ip"); Environment.Exit(1); } TcpChannel channel = new TcpChannel(Int32.Parse(args[1])); ChannelServices.RegisterChannel(channel, false); IMSDADServer server = (IMSDADServer)Activator.GetObject(typeof(IMSDADServer), args[3]); Console.WriteLine("This is the first server I'm connecting to!" + args[3]); if (server == null) { System.Console.WriteLine("Server could not be contacted"); Environment.Exit(1); } else { Console.WriteLine("CLIENT BEGINING"); String url = "tcp://" + args[5] + ":" + args[1] + "/" + args[2]; Client client = new Client(server, args[0], args[3], url); RemotingServices.Marshal(client, args[2], typeof(Client)); //Register Client with server client.KnownServers = server.NewClient(url, args[0]); string randomClientUrl = server.GetRandomClient(client.ClientId); if (randomClientUrl != null) { Console.WriteLine("THE RANDOM CLIENT IS: " + randomClientUrl); IMSDADClientToClient otherClient = (IMSDADClientToClient)Activator.GetObject(typeof(IMSDADClientToClient), randomClientUrl); client.Meetings = otherClient.SendMeetings(); } else { Console.WriteLine("NO OTHER CLIENT IN THE SYSTEM"); } if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + args[4])) { StreamReader reader = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + args[4]); Console.WriteLine("Press R to run the entire script, or S to start run step by step. Enter Key to each step"); int state = 0; //To run everything, press R if (Console.ReadLine().Equals("R")) { state = 1; } client.ParseScript(reader.ReadLine, state); reader.Close(); } else { Console.WriteLine("Error: File provided does not exist"); } client.ParseScript(Console.ReadLine, 1); } }
public void Stop() { ChannelServices.UnregisterChannel(channel); Log.Print("Server has stopped"); }
public VisualStudioInstance(Process hostProcess, DTE dte, ImmutableHashSet <string> supportedPackageIds, string installationPath, bool isUsingLspEditor) { HostProcess = hostProcess; Dte = dte; SupportedPackageIds = supportedPackageIds; InstallationPath = installationPath; IsUsingLspEditor = isUsingLspEditor; if (System.Diagnostics.Debugger.IsAttached) { // If a Visual Studio debugger is attached to the test process, attach it to the instance running // integration tests as well. var debuggerHostDte = GetDebuggerHostDte(); var targetProcessId = Process.GetCurrentProcess().Id; var localProcess = debuggerHostDte?.Debugger.LocalProcesses.OfType <EnvDTE80.Process2>().FirstOrDefault(p => p.ProcessID == hostProcess.Id); localProcess?.Attach2("Managed"); } StartRemoteIntegrationService(dte); _integrationServiceChannel = new IpcClientChannel(GetIpcClientChannelName(HostProcess), sinkProvider: null); ChannelServices.RegisterChannel(_integrationServiceChannel, ensureSecurity: true); // Connect to a 'well defined, shouldn't conflict' IPC channel _integrationService = IntegrationService.GetInstanceFromHostProcess(hostProcess); // Create marshal-by-ref object that runs in host-process. _inProc = ExecuteInHostProcess <VisualStudio_InProc>( type: typeof(VisualStudio_InProc), methodName: nameof(VisualStudio_InProc.Create) ); // There is a lot of VS initialization code that goes on, so we want to wait for that to 'settle' before // we start executing any actual code. _inProc.WaitForSystemIdle(); AddParameterDialog = new AddParameterDialog_OutOfProc(this); ChangeSignatureDialog = new ChangeSignatureDialog_OutOfProc(this); CodeDefinitionWindow = new CodeDefinitionWindow_OutOfProc(this); InteractiveWindow = new CSharpInteractiveWindow_OutOfProc(this); ObjectBrowserWindow = new ObjectBrowserWindow_OutOfProc(this); Debugger = new Debugger_OutOfProc(this); Editor = new Editor_OutOfProc(this); ErrorList = new ErrorList_OutOfProc(this); ExtractInterfaceDialog = new ExtractInterfaceDialog_OutOfProc(this); GenerateTypeDialog = new GenerateTypeDialog_OutOfProc(this); InlineRenameDialog = new InlineRenameDialog_OutOfProc(this); ImmediateWindow = new ImmediateWindow_OutOfProc(this); LocalsWindow = new LocalsWindow_OutOfProc(this); MoveToNamespaceDialog = new MoveToNamespaceDialog_OutOfProc(this); PickMembersDialog = new PickMembersDialog_OutOfProc(this); Shell = new Shell_OutOfProc(this); SolutionExplorer = new SolutionExplorer_OutOfProc(this); Workspace = new VisualStudioWorkspace_OutOfProc(this); StartPage = new StartPage_OutOfProc(this); SendKeys = new SendKeys(this); // Ensure we are in a known 'good' state by cleaning up anything changed by the previous instance CleanUp(); }
static void Main(string[] args) { // TODO Guomao: Read the port from the configuration file if (args.Length != 8) { Console.WriteLine("ProcessNode.exe -port xxx -datadir xxx -datadirsharename xxx -jobcount xxx"); return; } if (args[0].ToLower().CompareTo("-port") != 0) { Console.WriteLine("ProcessNode.exe -port xxx -datadir xxx -datadirsharename xxx -jobcount xxx"); return; } int iPortNumber = Int32.Parse(args[1]); if (args[2].ToLower().CompareTo("-datadir") != 0) { Console.WriteLine("ProcessNode.exe -port xxx -datadir xxx -datadirsharename xxx -jobcount xxx"); return; } string strDataRootDir = args[3]; if (args[4].ToLower().CompareTo("-datadirsharename") != 0) { Console.WriteLine("ProcessNode.exe -port xxx -datadir xxx -datadirsharename xxx -jobcount xxx"); return; } string strDataRootDirShareName = args[5]; if (args[6].ToLower().CompareTo("-jobcount") != 0) { Console.WriteLine("ProcessNode.exe -port xxx -datadir xxx -datadirsharename xxx -jobcount xxx"); return; } int iMaxConcurrentJobCount = Int32.Parse(args[7]); // Register the channel try { BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider(); serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = iPortNumber; TcpChannel tcpChannel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(tcpChannel, true); } catch (RemotingException) { Console.WriteLine("The channel tcp:" + iPortNumber.ToString() + " is already existed!"); return; } catch (System.Net.Sockets.SocketException) { Console.WriteLine("The port number:" + iPortNumber + " is busy!"); return; } catch (Exception) { Console.WriteLine("Error occurs when registering the channel!"); return; } // Register the remote object try { RemotingConfiguration.RegisterWellKnownServiceType( Type.GetType("Galaxy.ProcessNode.JobStatusManager, RemoteImpLib"), "GalaxyJobStatusManager", WellKnownObjectMode.Singleton); RemotingConfiguration.RegisterWellKnownServiceType( Type.GetType("Galaxy.ProcessNode.JobAgent, RemoteImpLib"), "GalaxyJobAgent", WellKnownObjectMode.Singleton); } catch (Exception) { Console.WriteLine("Error occurs when registering the remote object!"); return; } // Run the job agent List <JobAgentDataDir> dataDirs = new List <JobAgentDataDir>(); JobAgentDataDir dataDir = new JobAgentDataDir(); dataDir.DataDirName = strDataRootDir; dataDir.DataDirShareName = strDataRootDirShareName; dataDirs.Add(dataDir); IJobAgent jobAgent = Activator.GetObject( typeof(IJobAgent), "tcp://localhost:" + iPortNumber.ToString() + "/GalaxyJobAgent") as IJobAgent; jobAgent.MaximumJobIdleTime = 2; if (jobAgent.Run(iPortNumber, dataDirs, iMaxConcurrentJobCount) != 0) { Console.WriteLine("Process node instance run error!"); } }
public static IpcServerChannel IpcCreateServer <TRemoteObject>( ref String RefChannelName, WellKnownObjectMode InObjectMode, TRemoteObject ipcInterface, params WellKnownSidType[] InAllowedClientSIDs) where TRemoteObject : MarshalByRefObject { String ChannelName = RefChannelName ?? GenerateName(); /////////////////////////////////////////////////////////////////// // create security descriptor for IpcChannel... System.Collections.IDictionary Properties = new System.Collections.Hashtable(); Properties["name"] = ChannelName; Properties["portName"] = ChannelName; DiscretionaryAcl DACL = new DiscretionaryAcl(false, false, 1); if (InAllowedClientSIDs.Length == 0) { if (RefChannelName != null) { throw new System.Security.HostProtectionException("If no random channel name is being used, you shall specify all allowed SIDs."); } // allow access from all users... Channel is protected by random path name! DACL.AddAccess( AccessControlType.Allow, new SecurityIdentifier( WellKnownSidType.WorldSid, null), -1, InheritanceFlags.None, PropagationFlags.None); } else { for (int i = 0; i < InAllowedClientSIDs.Length; i++) { DACL.AddAccess( AccessControlType.Allow, new SecurityIdentifier( InAllowedClientSIDs[i], null), -1, InheritanceFlags.None, PropagationFlags.None); } } CommonSecurityDescriptor SecDescr = new CommonSecurityDescriptor(false, false, ControlFlags.GroupDefaulted | ControlFlags.OwnerDefaulted | ControlFlags.DiscretionaryAclPresent, null, null, null, DACL); ////////////////////////////////////////////////////////// // create IpcChannel... BinaryServerFormatterSinkProvider BinaryProv = new BinaryServerFormatterSinkProvider(); BinaryProv.TypeFilterLevel = TypeFilterLevel.Full; IpcServerChannel Result = new IpcServerChannel(Properties, BinaryProv, SecDescr); ChannelServices.RegisterChannel(Result, false); if (ipcInterface == null) { RemotingConfiguration.RegisterWellKnownServiceType( typeof(TRemoteObject), ChannelName, InObjectMode); } else { RemotingServices.Marshal(ipcInterface, ChannelName); } RefChannelName = ChannelName; return(Result); }
/// <summary> /// Opens a .NET Remoting connection to the PetraServer's ClientManager. /// /// </summary> /// <param name="ConfigFile">File name of the .NET (Remoting) Configuration file</param> /// <param name="ARemote">.NET Remoting Proxy object for the ClientManager object /// </param> /// <returns>void</returns> public virtual void GetRemoteServerConnection(string ConfigFile, out IClientManagerInterface ARemote) { ARemote = null; try { if (!FRemotingConfigurationSetup) { FRemotingConfigurationSetup = true; if (TAppSettingsManager.HasValue("Server.Port")) { IChannel[] regChannels = ChannelServices.RegisteredChannels; foreach (IChannel ch in regChannels) { ChannelServices.UnregisterChannel(ch); } ChannelServices.RegisterChannel(new TcpChannel(0), false); } else if (TAppSettingsManager.HasValue("OpenPetra.ChannelEncryption.PublicKeyfile")) { IClientChannelSinkProvider TCPSink = new BinaryClientFormatterSinkProvider(); Hashtable properties = new Hashtable(); properties.Add("HttpsPublicKeyXml", TAppSettingsManager.GetValue("OpenPetra.ChannelEncryption.PublicKeyfile")); TCPSink.Next = new EncryptionClientSinkProvider(properties); Hashtable ChannelProperties = new Hashtable(); TcpChannel Channel = new TcpChannel(ChannelProperties, TCPSink, null); ChannelServices.RegisterChannel(Channel, false); } else { // The following call must be done only once while the application runs (otherwise a RemotingException occurs) RemotingConfiguration.Configure(ConfigFile, false); } } DetermineServerIPAddress(); ARemote = (IClientManagerInterface) Activator.GetObject(typeof(IClientManagerInterface), String.Format("tcp://{0}:{1}/Clientmanager", FServerIPAddr, FServerPort)); if (ARemote != null) { if (TLogging.DebugLevel >= CONNECTOR_LOGGING) { TLogging.Log("GetRemoteServerConnection: connected.", TLoggingType.ToLogfile); } } } catch (Exception exp) { TLogging.Log("Error in GetRemoteServerConnection(), Possible reasons :-" + exp.ToString(), TLoggingType.ToLogfile); throw; } }
/// <summary> /// オブジェクト生成。 /// 利用後にはDispose()で開放してください。 /// </summary> public BouyomiChanClient() { ClientChannel = new IpcClientChannel("hogehoge", null); //チャンネル名は何でもいい ChannelServices.RegisterChannel(ClientChannel, false); RemotingObject = (BouyomiChanRemoting)Activator.GetObject(typeof(BouyomiChanRemoting), "ipc://BouyomiChan/Remoting"); }