/// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="clientMode"><see cref="T:TcmCoreService.Configuration.ClientMode" /></param> /// <param name="targetUri">Target <see cref="T:System.Uri" /></param> /// <param name="domain">Optional domain</param> /// <param name="userName">Optional username</param> /// <param name="password">Optional password</param> public Session(ClientMode clientMode, Uri targetUri, String domain, String userName, String password) : base(targetUri, userName, password) { mClientMode = clientMode; mTargetUri = targetUri; switch (clientMode) { case ClientMode.HttpClient: mClient = new SessionAwareCoreServiceClient(ClientConfiguration.ClientWSHttpBinding, new EndpointAddress(ClientConfiguration.ClientWSHttpUri(targetUri))); break; case ClientMode.TcpClient: default: if (ClientConfiguration.IsRunningOnMono) throw new NotImplementedException ("NetTcpBinding on Mono cannot be used with Tridion CoreService"); mClient = new SessionAwareCoreServiceClient(ClientConfiguration.ClientTcpBinding, new EndpointAddress(ClientConfiguration.ClientTcpUri(targetUri))); break; } if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password)) { if (!String.IsNullOrEmpty(domain)) mCredentials = new NetworkCredential(userName, password, domain); else mCredentials = new NetworkCredential(userName, password); } else mCredentials = CredentialCache.DefaultNetworkCredentials; mClient.ClientCredentials.Windows.ClientCredential = mCredentials; }
public Task <ServiceResult <UserInformationModel> > LoginAsync(ClientMode mode, string username, string password) { return(Task.Run(() => { if (mode == ClientMode.Offline) { using (var context = _contextFactory.Create()) { var userInfo = context.Employees.FirstOrDefault(e => e.Username == username); if (userInfo == null || userInfo?.Password != password) { return ServiceResult <UserInformationModel> .Fail("Incorrect username/password"); } return ServiceResult.Ok(new UserInformationModel() { ClientMode = mode, FullName = $"{userInfo.LastName} {userInfo.FirstName} {userInfo.MiddleName}", IsSuperUser = userInfo.IsSuperUser, UserId = userInfo.Id }); } } return ServiceResult <UserInformationModel> .Fail("Unsupported client mode login method"); })); }
/// <summary> /// Initializes a new instance of the <see cref="SimpleOAuth2Client"/> class. /// </summary> /// <param name="authorizeUri">The authorize URI.</param> /// <param name="accessTokenUri">The access token URI.</param> /// <param name="clientId">The client id.</param> /// <param name="clientSecret">The client secret.</param> /// <param name="scope">The scope.</param> /// <param name="redirectUri">The redirect URI.</param> /// <param name="mode"></param> public SimpleOAuth2Client(Uri authorizeUri, Uri accessTokenUri, string clientId, string clientSecret, string scope, Uri redirectUri, ClientMode mode = ClientMode.ThreeLegged) { if (authorizeUri == null) { throw new ArgumentNullException("authorizeUri"); } if (accessTokenUri == null) { throw new ArgumentNullException("accessTokenUri"); } if (clientId == null) { throw new ArgumentNullException("clientId"); } if (clientSecret == null) { throw new ArgumentNullException("clientSecret"); } if (scope == null) { throw new ArgumentNullException("scope"); } if (redirectUri == null) { throw new ArgumentNullException("redirectUri"); } AuthorizeUri = authorizeUri; AccessTokenUri = accessTokenUri; ClientId = clientId; ClientSecret = clientSecret; Scope = scope; RedirectUri = redirectUri; Mode = mode; }
public Player AddClient(string playerName, string connectionId, ClientMode mode) { Player player; if (Players.TryGetValue(connectionId, out player)) { _sendTo.Client(connectionId).Error( String.Format("Player {0} already within Team", playerName) ); return(player); } player = new Player { Name = playerName, Mode = mode }; Players[connectionId] = player; switch (mode) { case ClientMode.Player: case ClientMode.ParticipatingHost: NotifyViewersOfNewPlayer(connectionId, player); break; case ClientMode.Viewer: NotifyNewConnectionOfPlayers(connectionId); break; } return(player); }
public static string GetUrl(string host, ClientMode mode) { var token = host.Split(':'); var url = token.ElementAtOrDefault(0); var port = token.ElementAtOrDefault(1); if (string.IsNullOrEmpty(port)) { port = DefaultPort; } switch (Mode) { case ClientMode.Http: return("http://" + url + ":" + port + GetPath() + @"/{0}/basic"); case ClientMode.WSHttp: return("http://" + url + ":" + port + GetPath() + @"/{0}"); //case ClientMode.Server: // return "http://" + host + ":" + port + @"/RosService/{0}/binary"; case ClientMode.GZip: return("http://" + url + ":" + port + GetPath() + @"/{0}/gzip"); case ClientMode.Tcp: case ClientMode.Server: return("net.tcp://" + url + GetPath() + @"/{0}/tcp"); case ClientMode.NamedPipe: return("net.pipe://" + url + GetPath() + @"/{0}/pipe"); } return(null); }
public Player AddClient(string playerName, string connectionId, ClientMode mode) { if (Players.ContainsKey(connectionId)) { throw new Exception("Player already within Team"); } var player = new Player { Name = playerName, Mode = mode }; Players[connectionId] = player; switch (mode) { case ClientMode.Player: case ClientMode.ParticipatingHost: NotifyViewersOfNewPlayer(connectionId, player); break; case ClientMode.Viewer: NotifyNewConnectionOfPlayers(connectionId); break; } return(player); }
public void waitForOffline(string IP, int port) { int secs = 3600; ClientMode modeClient = clientMode; clientMode = ClientMode.WAITFOROFFLINE; pictureBoxChange(); while (clientMode == ClientMode.WAITFOROFFLINE) { try { updateAccountStatus("Waiting for server to go offline"); TcpClient tcpClient = new TcpClient(IP, port); if (tcpClient.Connected) { tcpClient.Close(); Thread.Sleep(secs * 1000); } else { updateLog("Servers have went offline at " + DateTime.Now); updateAccountStatus("Servers have went offline"); clientMode = modeClient; break; } } catch { updateLog("Servers have went offline at " + DateTime.Now); updateAccountStatus("Servers have went offline"); clientMode = modeClient; break; } } }
public void SetMode(ClientMode modeToSet) { //Create a new mode mMode = new ClientMode(); //Store mode mMode = modeToSet; }
public void SetMode(ClientMode modeToSet) { //Create a new mode mMode = new ClientMode(); //Store mode mMode = modeToSet; }
public NetConnection(ClientMode clientMode) { mode = clientMode; if (mode == ClientMode.bufferMode) { rxTimer.Elapsed += new ElapsedEventHandler(RxTimerEvent); rxTimer.Interval = rxTimerFreq; } rxTimer.Enabled = false; }
private static CommandInfo getCommandInfo(DirectoryInfo directory, int port, ClientMode mode, int clientTimeout = 1000) { var configPath = getConfigPath(directory, mode); var serverConfig = new ServerConfig(); return(new CommandInfo { FileName = @"C:\ProgramData\Oracle\Java\javapath\java.EXE", Args = $"-Xms100m -Xmx1g -jar \"{_clientName.FullName}\" 127.0.0.1 {port} {serverConfig.UIToken} {clientTimeout} {mode} \"{configPath}\"", }); }
public static string GetUrlStreaming(string host, ClientMode mode) { var token = host.Split(':'); var url = token.ElementAtOrDefault(0); var port = token.ElementAtOrDefault(1); if (string.IsNullOrEmpty(port)) { port = DefaultPort; } return("http://" + url + ":" + port + GetPath() + @"/{0}/binary"); }
/// <summary> /// Creates a new client for communicating with TransIP services. /// </summary> /// <param name="serviceName">The name of the service.</param> /// <param name="uri">The URI of the service.</param> /// <param name="login">The login name from TransIP.</param> /// <param name="mode">The mode.</param> /// <param name="privateKey">The private key.</param> protected ClientBase(string serviceName, string uri, string login, ClientMode mode, string privateKey) { _uri = uri; _privateKey = privateKey; ServiceName = serviceName; Login = login; Mode = mode; Cookies = new CookieContainer(); Client = CreateClient(BasicHttpBinding, new EndpointAddress(_uri)); Client.ChannelFactory.Endpoint.Behaviors.Add(new CookieEndpointBehavior(Cookies, _uri)); // Set the static cookies. AddCookie("login", Login); AddCookie("mode", Mode.ToString().ToLower()); }
public AsyncTcpClient(string server, int port, int receiveBufferSize, int timeout, ClientMode mode) : base() { _tracer = new Tracer("TcpClient[" + server + ':' + port.ToString() + ']'); _server = server; _port = port; _receiveBufferSize = receiveBufferSize; _readStream = new JetMemoryStream(_defaultReceiveBufferSize); _currentLineBuilder = new StringBuilder(); State = ClientState.NotStarted; _mode = mode; Timeout = timeout; OnTimeout += new MethodInvoker(OnOperationFailed); _sendMethod = new MethodInvoker(BeginSend); _receiveMethod = new MethodInvoker(BeginReceive); _endSendMethod = new MethodInvoker(EndSend); _endReceiveMethod = new MethodInvoker(EndReceive); }
public static void LoadGdax(ClientMode mode, out string apiKey, out string apiSecret, out string passphrase) { using (var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (var key = registry.OpenSubKey(@"SOFTWARE\GDAX", false)) { if (mode == ClientMode.Sandbox) { apiKey = (string)key.GetValue("GdaxSandboxApiKey"); apiSecret = (string)key.GetValue("GdaxSandboxApiSecret"); passphrase = (string)key.GetValue("GdaxSandboxPassphrase"); } else { apiKey = (string)key.GetValue("ApiKey"); apiSecret = (string)key.GetValue("ApiSecret"); passphrase = (string)key.GetValue("Passphrase"); } } }
/// <summary> /// Activates TET C# Client and all underlying routines. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion"/>Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode"/>Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <param name="hostname"/>The host name or IP address where the eye tracking server is running.</param> /// <param name="portnumber"/>The port number used for the eye tracking server</param> /// <returns>True is succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber) { //if already running, deactivate before starting anew if (isActive) { Deactivate(); } //lock calling thread while initializing initializationLock = Thread.CurrentThread; lock (initializationLock) { apiManager = new GazeApiManager(this); apiManager.Connect(hostname, portnumber); if (apiManager.IsConnected()) { apiManager.RequestTracker(mode, apiVersion); apiManager.RequestAllStates(); //We wait untill above requests have been handled by server or timeout occours bool waitSuccess = Monitor.Wait(initializationLock, TimeSpan.FromSeconds(20)); if (waitSuccess == false) { Debug.WriteLine("Error initializing GazeManager"); return(false); } //init heartbeat heartbeatHandler = new Heartbeat(apiManager); heartbeatHandler.Start(); isActive = true; } else { Debug.WriteLine("Error initializing GazeManager"); } return(isActive); } }
private void FixEndpoint() { switch (_settings.ConnectionMode) { case ClientMode.Broadcast: _currentEndpoint.Port = _settings.PortBroadcast; if (!_currentEndpoint.IsEnabled) { _currentEndpoint.Name = "(SELECT VEHICLE)"; _currentEndpoint.IpAddress = ""; } if (_lastClientMode != ClientMode.Broadcast) { _deviceWatcher.Start(); } break; case ClientMode.HttpDirect: _currentEndpoint.Name = _settings.TitleHttp; _currentEndpoint.IpAddress = _settings.IpAddressHttp; _currentEndpoint.Port = _settings.PortHttp; _currentEndpoint.IsEnabled = true; if (_lastClientMode == ClientMode.Broadcast) { _deviceWatcher.Stop(); } break; case ClientMode.None: _currentEndpoint.Name = _settings.TitleNone; _currentEndpoint.IpAddress = ""; _currentEndpoint.Port = ""; _currentEndpoint.IsEnabled = false; if (_lastClientMode == ClientMode.Broadcast) { _deviceWatcher.Stop(); } break; } _lastClientMode = _settings.ConnectionMode; }
/// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="clientMode"><see cref="T:TcmCoreService.Configuration.ClientMode" /></param> /// <param name="targetUri">Target <see cref="T:System.Uri" /></param> /// <param name="domain">Optional domain</param> /// <param name="userName">Optional username</param> /// <param name="password">Optional password</param> public Session(ClientMode clientMode, Uri targetUri, String domain, String userName, String password) : base(targetUri, userName, password) { mClientMode = clientMode; mTargetUri = targetUri; switch (clientMode) { case ClientMode.HttpClient: mClient = new SessionAwareCoreServiceClient(ClientConfiguration.ClientWSHttpBinding, new EndpointAddress(ClientConfiguration.ClientWSHttpUri(targetUri))); break; case ClientMode.TcpClient: default: if (ClientConfiguration.IsRunningOnMono) { throw new NotImplementedException("NetTcpBinding on Mono cannot be used with Tridion CoreService"); } mClient = new SessionAwareCoreServiceClient(ClientConfiguration.ClientTcpBinding, new EndpointAddress(ClientConfiguration.ClientTcpUri(targetUri))); break; } if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password)) { if (!String.IsNullOrEmpty(domain)) { mCredentials = new NetworkCredential(userName, password, domain); } else { mCredentials = new NetworkCredential(userName, password); } } else { mCredentials = CredentialCache.DefaultNetworkCredentials; } mClient.ClientCredentials.Windows.ClientCredential = mCredentials; }
/// <summary> /// Creates a new instance of the Gengo API client with the specified mode /// </summary> /// <param name="privateKey">API public key</param> /// <param name="publicKey">API private key</param> /// <param name="mode">Wether to run in Production or Sandbox mdoe</param> public GengoClient(string privateKey, string publicKey, ClientMode mode) { if (string.IsNullOrWhiteSpace(privateKey)) { throw new ArgumentException("Private key not specified", "privateKey"); } if (string.IsNullOrWhiteSpace(publicKey)) { throw new ArgumentException("Public key not specified", "publicKey"); } _privateKey = privateKey; _publicKey = publicKey; var uri = mode == ClientMode.Production ? ProductionBaseUri : SandboxBaseUri; _baseUri = new Uri(uri); initClient(); }
public void Init(ClientMode mode, string address, int port = 8080) { if (this.isInitialized) { this.Error("ActionDispatcher was initialized already."); return; } this.Mode = mode; pendingMessages = new Queue <Protocol.Message>(); OnReceivedActionResponse = new Action <Protocol.TurnResp> [Enum.GetNames(typeof(Protocol.TurnType)).Length]; // SETUP CLIENT if (Mode == ClientMode.Log) { client = new OfflineClient(address); } else { client = new OnlineClient(address, port); } client.OnMessageReceived += new EventHandler <string>(this.ProcessServerMessage); if (this.client.Connect()) { if (this.OnClientReady != null) { OnClientReady(); OnClientReady = null; this.Log("Connected to the server."); } } else { this.Error("Could not connect to the server."); } IsHalted = false; }
//* Inicializa o cliente e registra os eventos de Neutron. protected void Initialize(ClientMode clientMode) { This = (Neutron)this; ClientMode = clientMode; Internal_OnNeutronConnected += OnNeutronConnected; Internal_OnNeutronAuthenticated += OnNeutronAuthenticated; Internal_OnPlayerConnected += OnPlayerConnected; Internal_OnPlayerDisconnected += OnPlayerDisconnected; Internal_OnMessageReceived += OnMessageReceived; Internal_OnChannelsReceived += OnChannelsReceived; Internal_OnRoomsReceived += OnRoomsReceived; Internal_OnRoomPropertiesChanged += OnRoomPropertiesChanged; Internal_OnPlayerPropertiesChanged += OnPlayerPropertiesChanged; Internal_OnPlayerNicknameChanged += OnPlayerNicknameChanged; Internal_OnPlayerCustomPacketReceived += OnPlayerCustomPacketReceived; Internal_OnPlayerCreatedRoom += OnPlayerCreatedRoom; Internal_OnPlayerJoinedChannel += OnPlayerJoinedChannel; Internal_OnPlayerJoinedRoom += OnPlayerJoinedRoom; Internal_OnPlayerLeftChannel += OnPlayerLeftChannel; Internal_OnPlayerLeftRoom += OnPlayerLeftRoom; Internal_OnError += OnError; //* Define nome da cena principal do cliente. _sceneName = $"Client(Container) - {SceneHelper.GetSideTag(IsServer)} - [{clientMode}] - ({UnityEngine.Random.Range(1, int.MaxValue)})"; }
/// <summary> /// Disconnect / Restart /// </summary> public void forceDisconnect(bool restart, int secs, bool ignoreMessage, string reason, bool userTerminate = false) { if (clientMode != ClientMode.DISCONNECTED && clientMode != ClientMode.WAITFOROFFLINE && clientMode != ClientMode.WAITFORONLINE && clientMode != ClientMode.LOGIN && clientMode != ClientMode.LOGGEDIN && !userTerminate) { disconnectProcess(restart, secs, ignoreMessage, reason); } else if (clientMode == ClientMode.DISCONNECTED && !userTerminate) { return; } else if ((clientMode == ClientMode.WAITFOROFFLINE || clientMode == ClientMode.WAITFORONLINE || clientMode == ClientMode.LOGIN || clientMode == ClientMode.LOGGEDIN) && !userTerminate) { ClientMode Compare = clientMode; Thread.Sleep(1500); if ((clientMode == Compare) && !userTerminate) { disconnectProcess(restart, secs, ignoreMessage, reason); } } else if (userTerminate) { disconnectProcess(restart, secs, ignoreMessage, reason); } }
/// <summary> /// Activates TET C# Client and all underlying routines using default values. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion">Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode">Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <param name="listener">Listener to notify once the connection to EyeTribe Server has been established</param> /// <returns>True if succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode, IConnectionStateListener listener) { AddConnectionStateListener(listener); return Activate(apiVersion, mode, GazeApiManager.DEFAULT_SERVER_HOST, GazeApiManager.DEFAULT_SERVER_PORT); }
/* OLD LOGIN METHOD * public void checkValidNexonCookie() * { * if (nexonCookie == string.Empty || getNexonCookieTimeout() == 0) * { * nexonCookie = string.Empty; * nexonCookieTimeout = DateTime.Now.AddSeconds(120); * updateLog("[Auth] Grabbing nexon auth..."); * nexonCookie = getNexonCookie(LoginID, Password); * if (nexonCookie == string.Empty) * { * if (Program.usingProxy) * { * authFailures++; * if (authFailures < 4) * { * updateLog("[Auth] Failed to get auth, restarting."); * forceDisconnect(true, 1, false, "Auth: General failure"); * } * else if (authFailures >= 4 && authFailures < 6) * { * proxyServer = ""; * Program.iniFile.WriteValue(accountProfile, "AccProxy", ""); * updateLog("[Auth] Failed to get auth 8 times. Disconnecting."); * forceDisconnect(false, 1, false, "Failed to get auth 8 times"); * } * else * { * proxyServer = ""; * Program.iniFile.WriteValue(accountProfile, "AccProxy", ""); * updateLog("[Auth] Failed to get auth 3 times, restarting with different proxy."); * forceDisconnect(true, 1, false, "Auth: Restarting with different proxy"); * } * * } * else * { * updateLog("[Auth] Failed to get auth, restarting in " + Program.nexonAuthRestartTime.ToString() + " secs"); * forceDisconnect(true, Program.nexonAuthRestartTime, false, "Auth: General failure"); * } * } * updateLog("[Auth] Nexon Auth grabbed"); * return; * } * return; * } * ----END OLD LOGIN*/ private void ses_OnInitPacketHandler(object sender, HandshakeEventArgs e) { try { Thread t = new Thread(delegate() { updateLog("[Connection] Established at: " + connector.ip + ":" + connector.port); //if (clientMode == ClientMode.DISCONNECTED) if (connector.ip == Program.serverip & connector.port == Program.port) { sw.Reset(); sw.Start(); clientMode = ClientMode.LOGIN; pictureBoxChange(); Program.mapleVersion = (short)e.Version; ses.SendPacket(PacketHandler.ValidateLogin(e.Locale, e.Version, e.Subversion).ToArray()); /* OLD LOGIN METHOD * Thread th = null; * if (nexonCookie == string.Empty || getNexonCookieTimeout() == 0) * { * th = new Thread(() => checkValidNexonCookie()); * workerThreads.Add(th); * th.Start(); * } * if (th != null) * th.Join(); */ nexonCookie = string.Empty; nexonCookie = getNexonCookie(LoginID, Password); while (nexonCookie == string.Empty) { Thread.Sleep(1); } if (nexonCookie != null || nexonCookie != string.Empty || nexonCookie != "Error" || nexonCookie != "Invalid" || nexonCookie != "Incorrect") { /* * while (clientMode == ClientMode.LOGIN) * { * if (checkWorldStatus()) * break; * else * updateLog("[Status] Checking world server status"); * Thread.Sleep(1); * } */ if (!Program.webLogin) { ses.SendPacket(PacketHandler.ClientLogin(this, nexonCookie, Password).ToArray()); } else { ses.SendPacket(PacketHandler.LoginResponse(this, nexonCookie, world, channel, Password).ToArray()); } mapleVersion = string.Concat("MapleStory v", e.Version.ToString(), ".", e.Subversion.ToString()); updateLog("[Version] " + mapleVersion); updateAccountStatus("Logged in"); Thread loginCheckThread = new Thread(delegate() { DateTime startCheck = DateTime.Now; while (!loginCheck) { if ((DateTime.Now - startCheck).TotalSeconds > 10) { updateLog("[Login] No login response! Restarting!"); forceDisconnect(true, 0, false, "No login Response"); return; } Thread.Sleep(1); } return; }); workerThreads.Add(loginCheckThread); loginCheckThread.Start(); } else { string x = string.Empty; if (nexonCookie == "Error") { x = "Auth Error"; } if (nexonCookie == "Invalid") { x = "Invalid Response;"; } if (nexonCookie == "Incorrect") { x = "Incorrect Info"; } updateLog("[Nexon Auth] Failed to retrieve auth."); updateLog("[Nexon Auth] " + x); forceDisconnect(true, 1, false, "Failed to retrieve auth."); } } else { if (!remoteHackPacket) { ses.SendPacket(PacketHandler.EnterChannel(myCharacter.uid, RAND1, RAND2, cauth, worldID).ToArray()); //Thread.Sleep(1000); //ses.SendPacket(PacketHandler.Custom("2F 01 01").ToArray()); } else { remoteHackPacket = false; } } }); workerThreads.Add(t); t.Start(); } catch { updateLog("[Error] Debug Error 0"); } }
public Client(string apiKey, string apiSecret, ClientMode mode, IGdaxLog logger = null, bool useTimeApi = false) : base(apiKey, apiSecret, null, mode == ClientMode.Production ? Constants.LiveApiUrl : Constants.TestApiUrl, mode == ClientMode.Production ? Constants.LiveCheckoutUrl : Constants.TestCheckoutUrl, useTimeApi) { }
/// <summary> /// Activates TET C# Client and all underlying routines. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion">Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode">Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <param name="hostname">The host name or IP address where the eye tracking server is running.</param> /// <param name="portnumber">The port number used for the eye tracking server</param> /// <param name="listener">Listener to notify once the connection to EyeTribe Server has been established</param> /// <returns>True if succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber, IConnectionStateListener listener) { AddConnectionStateListener(listener); return Activate(apiVersion, mode, hostname, portnumber, listener); }
public NetClient(ClientMode clientMode) : base(clientMode) { }
public static ICoinbaseClient CreateCoinbaseClient(string apiKey, string apiSecret, ClientMode mode) { switch (mode) { case ClientMode.Production: case ClientMode.Sandbox: return(new Coinbase.Client(apiKey, apiSecret, mode)); //case ClientMode.Sandbox: // break; //case ClientMode.Simulated: // break; default: throw new ArgumentOutOfRangeException(nameof(mode), mode, null); } }
/// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="clientMode"><see cref="T:TcmCoreService.Configuration.ClientMode" /></param> /// <param name="targetUri">Target <see cref="T:System.Uri" /></param> public Session(ClientMode clientMode, Uri targetUri) : this(clientMode, targetUri, null, null, null) { }
/// <summary> /// Activates TET C# Client and all underlying routines. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion"/>Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode"/>Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <param name="hostname"/>The host name or IP address where the eye tracking server is running.</param> /// <param name="portnumber"/>The port number used for the eye tracking server</param> /// <returns>True is succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber) { //if already running, deactivate before starting anew if (isActive) Deactivate(); //lock calling thread while initializing initializationLock = Thread.CurrentThread; lock (initializationLock) { apiManager = new GazeApiManager(this); apiManager.Connect(hostname, portnumber); if (apiManager.IsConnected()) { apiManager.RequestTracker(mode, apiVersion); apiManager.RequestAllStates(); //We wait untill above requests have been handled by server or timeout occours bool waitSuccess = Monitor.Wait(initializationLock, TimeSpan.FromSeconds(20)); if (waitSuccess == false) { Debug.WriteLine("Error initializing GazeManager"); return false; } //init heartbeat heartbeatHandler = new Heartbeat(apiManager); heartbeatHandler.Start(); isActive = true; } else Debug.WriteLine("Error initializing GazeManager"); return isActive; } }
internal Client(string apiKey, string apiSecret, string apiPassphrase, ClientMode clientMode, bool useTimeApi = false) : base(apiKey, apiSecret, apiPassphrase, clientMode == ClientMode.Production ? Constants.Url.ProductionRest : Constants.Url.SandboxRest, null, useTimeApi) { _clientMode = clientMode; }
public void OnGazeApiResponse(String response) { var reply = JsonConvert.DeserializeObject <ReplyBase>(response); if (reply.StatusCode == (int)HttpStatusCode.OK) { switch (reply.Category) { case Protocol.CATEGORY_TRACKER: if (reply.Request.Equals(Protocol.TRACKER_REQUEST_GET)) { var jsreader = new JsonTextReader(new StringReader(response)); var json = (JObject) new JsonSerializer().Deserialize(jsreader); JObject values = json[Protocol.KEY_VALUES].ToObject <JObject>(); JToken value; if (null != values) { if (values.TryGetValue(Protocol.TRACKER_VERSION, out value)) { version = value.ToObject <ApiVersion>(); } if (values.TryGetValue(Protocol.TRACKER_MODE_PUSH, out value)) { if ((bool)value) { clientMode = ClientMode.Push; } else { clientMode = ClientMode.Pull; } } if (values.TryGetValue(Protocol.TRACKER_HEARTBEATINTERVAL, out value)) { HeartbeatMillis = (int)value; } if (values.TryGetValue(Protocol.TRACKER_FRAMERATE, out value)) { Framerate = value.ToObject <FrameRate>(); } if (values.TryGetValue(Protocol.TRACKER_TRACKERSTATE, out value)) { //if tracker state changed, notify listeners if ((int)value != (int)Trackerstate.GetTypeCode()) { Trackerstate = (TrackerState)(int)value; lock (((ICollection)trackerStateListeners).SyncRoot) { foreach (ITrackerStateListener listener in trackerStateListeners) { try { listener.OnTrackerStateChanged(Trackerstate); } catch (Exception e) { Debug.WriteLine("Exception while calling ITrackerStateListener.OnTrackerStateChanged() on listener " + listener + ": " + e.StackTrace); } } } } } if (values.TryGetValue(Protocol.TRACKER_CALIBRATIONRESULT, out value)) { LastCalibrationResult = value.ToObject <CalibrationResult>(); } if (values.TryGetValue(Protocol.TRACKER_ISCALIBRATING, out value)) { IsCalibrating = (bool)value; } if (values.TryGetValue(Protocol.TRACKER_ISCALIBRATED, out value)) { //if calibration state changed, notify listeners if ((bool)value != IsCalibrated) { IsCalibrated = (bool)value; lock (((ICollection)calibrationStateListeners).SyncRoot) { foreach (ICalibrationResultListener listener in calibrationStateListeners) { try { listener.OnCalibrationChanged(IsCalibrated, LastCalibrationResult); } catch (Exception e) { Debug.WriteLine("Exception while calling ICalibrationResultListener.OnCalibrationChanged() on listener " + listener + ": " + e.StackTrace); } } } } } if (values.TryGetValue(Protocol.TRACKER_SCREEN_RESOLUTION_WIDTH, out value)) { ScreenResolutionWidth = (int)value; } if (values.TryGetValue(Protocol.TRACKER_SCREEN_RESOLUTION_HEIGHT, out value)) { ScreenResolutionHeight = (int)value; } if (values.TryGetValue(Protocol.TRACKER_SCREEN_PHYSICAL_WIDTH, out value)) { ScreenPhysicalWidth = (int)value; } if (values.TryGetValue(Protocol.TRACKER_SCREEN_PHYSICAL_HEIGHT, out value)) { ScreenPhysicalHeight = (int)value; } if (values.TryGetValue(Protocol.TRACKER_SCREEN_INDEX, out value)) { //if screen index changed, notify listeners if ((int)value != ScreenIndex) { ScreenIndex = (int)value; lock (((ICollection)trackerStateListeners).SyncRoot) { foreach (ITrackerStateListener listener in trackerStateListeners) { try { listener.OnScreenStatesChanged(ScreenIndex, ScreenResolutionWidth, ScreenResolutionHeight, ScreenPhysicalWidth, ScreenPhysicalHeight); } catch (Exception e) { Debug.WriteLine("Exception while calling ITrackerStateListener.OnScreenStatesChanged() on listener " + listener + ": " + e.StackTrace); } } } } } if (values.TryGetValue(Protocol.TRACKER_FRAME, out value) && null != gazeBroadcaster) { //Add gaze update to high frequency broadcasting queue lock (((ICollection)queueGazeData).SyncRoot) { queueGazeData.Enqueue(value.ToObject <GazeData>()); } events.GetUpdateHandle().Set(); } } //Handle initialization if (initializationLock != null) { lock (initializationLock) { Monitor.Pulse(initializationLock); initializationLock = null; } } } else if (reply.Request.Equals(Protocol.TRACKER_REQUEST_SET)) { //Do nothing } break; case Protocol.CATEGORY_CALIBRATION: switch (reply.Request) { case Protocol.CALIBRATION_REQUEST_START: IsCalibrating = true; if (null != calibrationListener) { //Notify calibration listener that a new calibration process was successfully started try { calibrationListener.OnCalibrationStarted(); } catch (Exception e) { Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationStarted() on listener " + calibrationListener + ": " + e.StackTrace); } } break; case Protocol.CALIBRATION_REQUEST_POINTSTART: break; case Protocol.CALIBRATION_REQUEST_POINTEND: ++sampledCalibrationPoints; if (null != calibrationListener) { //Notify calibration listener that a new calibration point has been sampled try { calibrationListener.OnCalibrationProgress(sampledCalibrationPoints / totalCalibrationPoints); } catch (Exception e) { Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationProgress() on listener " + calibrationListener + ": " + e.StackTrace); } if (sampledCalibrationPoints == totalCalibrationPoints) { //Notify calibration listener that all calibration points have been sampled and the analysis of the calirbation results has begun try { calibrationListener.OnCalibrationProcessing(); } catch (Exception e) { Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationProcessing() on listener " + calibrationListener + ": " + e.StackTrace); } } } var cper = JsonConvert.DeserializeObject <CalibrationPointEndReply>(response); if (cper == null || cper.Values.CalibrationResult == null) { break; // not done with calibration yet } //if calibration state changed, notify listeners if (cper.Values.CalibrationResult.Result != IsCalibrated) { lock (((ICollection)calibrationStateListeners).SyncRoot) { foreach (ICalibrationResultListener listener in calibrationStateListeners) { try { listener.OnCalibrationChanged(cper.Values.CalibrationResult.Result, cper.Values.CalibrationResult); } catch (Exception e) { Debug.WriteLine("Exception while calling ICalibrationStateListener.OnCalibrationChanged() on listener " + listener + ": " + e.StackTrace); } } } } IsCalibrated = cper.Values.CalibrationResult.Result; IsCalibrating = !cper.Values.CalibrationResult.Result; LastCalibrationResult = cper.Values.CalibrationResult; if (null != calibrationListener) { //Notify calibration listener that calibration results are ready for evaluation try { calibrationListener.OnCalibrationResult(cper.Values.CalibrationResult); } catch (Exception e) { Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationResult() on listener " + calibrationListener + ": " + e.StackTrace); } } break; case Protocol.CALIBRATION_REQUEST_ABORT: IsCalibrating = false; //restore states of last calibration if any apiManager.RequestCalibrationStates(); break; case Protocol.CALIBRATION_REQUEST_CLEAR: IsCalibrated = false; IsCalibrating = false; LastCalibrationResult = null; break; } break; // end calibration switch case Protocol.CATEGORY_HEARTBEAT: //do nothing break; default: var rf = JsonConvert.DeserializeObject <ReplyFailed>(response); Debug.WriteLine("Request FAILED"); Debug.WriteLine("Category: " + rf.Category); Debug.WriteLine("Request: " + rf.Request); Debug.WriteLine("StatusCode: " + rf.StatusCode); Debug.WriteLine("StatusMessage: " + rf.Values.StatusMessage); break; } } else { var rf = JsonConvert.DeserializeObject <ReplyFailed>(response); /* * JSON Message status code is different from HttpStatusCode.OK. Check if special TET * specific statuscode before handling error */ switch (rf.StatusCode) { case Protocol.STATUSCODE_CALIBRATION_UPDATE: //The calibration state has changed, clients should update themselves apiManager.RequestCalibrationStates(); break; case Protocol.STATUSCODE_SCREEN_UPDATE: //The primary screen index has changed, clients should update themselves apiManager.RequestScreenStates(); break; case Protocol.STATUSCODE_TRACKER_UPDATE: //The connected Tracker Device has changed state, clients should update themselves apiManager.RequestTrackerState(); break; default: Debug.WriteLine("Request FAILED"); Debug.WriteLine("Category: " + rf.Category); Debug.WriteLine("Request: " + rf.Request); Debug.WriteLine("StatusCode: " + rf.StatusCode); Debug.WriteLine("StatusMessage: " + rf.Values.StatusMessage); break; } } }
/// <summary> /// Activates TET C# Client and all underlying routines using default values. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion"/>Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode"/>Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <returns>True is succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode) { return(Activate(apiVersion, mode, GazeApiManager.DEFAULT_SERVER_HOST, GazeApiManager.DEFAULT_SERVER_PORT)); }
/// <summary> /// Activates TET C# Client and all underlying routines using default values. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion"/>Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode"/>Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <returns>True is succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode) { return Activate(apiVersion, mode, GazeApiManager.DEFAULT_SERVER_HOST, GazeApiManager.DEFAULT_SERVER_PORT); }
/// <summary> /// Initializes a new instance of the <see cref="SimpleOAuth2Client"/> class. /// </summary> /// <param name="authorizeUri">The authorize URI.</param> /// <param name="accessTokenUri">The access token URI.</param> /// <param name="clientId">The client id.</param> /// <param name="clientSecret">The client secret.</param> /// <param name="scope">The scope.</param> /// <param name="redirectUri">The redirect URI.</param> /// <param name="mode"></param> public SimpleOAuth2Client(Uri authorizeUri, Uri accessTokenUri, string clientId, string clientSecret, string scope, Uri redirectUri, ClientMode mode = ClientMode.ThreeLegged) { if (authorizeUri == null) throw new ArgumentNullException("authorizeUri"); if (accessTokenUri == null) throw new ArgumentNullException("accessTokenUri"); if (clientId == null) throw new ArgumentNullException("clientId"); if (clientSecret == null) throw new ArgumentNullException("clientSecret"); if (scope == null) throw new ArgumentNullException("scope"); if (redirectUri == null) throw new ArgumentNullException("redirectUri"); AuthorizeUri = authorizeUri; AccessTokenUri = accessTokenUri; ClientId = clientId; ClientSecret = clientSecret; Scope = scope; RedirectUri = redirectUri; Mode = mode; }
public NamePacket(string name, ClientMode side) { Name = name; Side = side; }
public static IGdaxClient CreateGdaxClient(string apiKey, string apiSecret, string apiPassphrase, ClientMode mode, string dataPath = null) { switch (mode) { case ClientMode.Production: case ClientMode.Sandbox: return(new Gdax.Client(apiKey, apiSecret, apiPassphrase, mode)); case ClientMode.Simulated: return(new Gdax.SimulatedClient(dataPath)); default: throw new ArgumentOutOfRangeException(nameof(mode), mode, null); } }
/// <summary> /// Activates TET C# Client and all underlying routines. Should be called _only_ /// once when an application starts up. Calling thread will be locked during /// initialization. /// </summary> /// <param name="apiVersion">Version number of the Tracker API that this client will be compliant to</param> /// <param name="mode">Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param> /// <param name="hostname">The host name or IP address where the eye tracking server is running.</param> /// <param name="portnumber">The port number used for the eye tracking server</param> /// <returns>True if succesfully activated, false otherwise</returns> public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber) { //lock to ensure that state changing method calls are synchronous lock (Instance) { Object threadLock = Thread.CurrentThread; //lock calling thread while initializing lock (threadLock) { //only one entity can initialize at the time lock (initializationLock) { if (!IsActivated) { isInizializing = true; try { //establish connection in seperate thread apiManager = new GazeApiManager(this, this); ThreadPool.QueueUserWorkItem(new WaitCallback(HandleServerConnect), new Object[] { apiManager, mode, apiVersion, hostname, portnumber }); //We wait untill above requests have been handled by server or timeout occurs bool waitSuccess = Monitor.Wait(initializationLock, TimeSpan.FromSeconds(INIT_TIME_DELAY_SECONDS)); if (!waitSuccess) { HandleInitFailure(); Console.Write("Error initializing GazeManager, is EyeTribe Server running?"); } else { //init heartbeat heartbeatHandler = new Heartbeat(apiManager); heartbeatHandler.Start(); isActive = true; //notify connection listeners OnGazeApiConnectionStateChanged(IsActivated); } } catch (Exception e) { HandleInitFailure(); Console.Write("Error initializing GazeManager: " + e.StackTrace); } } return IsActivated; } } } }
public AsyncTcpClient(string server, int port, ClientMode mode) : this(server, port, _defaultReceiveBufferSize, _defaultTimeout, mode) { }