/// <summary> /// This method unwraps the encrypted data if necessary. /// </summary> /// <param name="key">The key of the data, must be validated by the caller.</param> /// <param name="data">The adapter wrapped data or the original data, must be validated by the caller.</param> /// <returns>The decrypted data, if it was encrypted, or the original data otherwise. May return null upon exception handling.</returns> /// <remarks>The data is typecast to IContextElement for decryption and deserialization, failure to cast returns the original data. /// Serialization or decryption failures are not recoverable, so the exception is swallowed and null is returned.</remarks> private object UnprotectData(string key, object data) { // key cannot be null, empty or whitespaces, verified in calling context, no need for arg validation // value cannot be null, verified in calling context, no need for arg validation ISerializationAdapter element = data as ISerializationAdapter; if (element == null) { // cannot infer context element, then this is direct data return(data); } try { // Convert the key to upper case since entropy generation depends on the key casing, and workflow context keys are case insensitive return(element.GetData(adapter => adapter.GetData(this.Encryptor, key.ToUpperInvariant()))); } catch (SerializationException) { // nothing to log, nothing to do (checked with Muhammad) } catch (CryptographicException) { // nothing to log, nothing to do (checked with Muhammad) } catch (SecurityException) { // nothing to log, nothing to do (checked with Muhammad) } // unable to extract actual data, caller will be responsible for determining appropriate reaction return(null); }
public static IDataStore CreateProviderFromString(string connectionString, AutoCreateOption autoCreateOption, out IDisposable[] objectsToDisposeOnDisconnect) { objectsToDisposeOnDisconnect = null; ConnectionStringParser Parser = new ConnectionStringParser(connectionString); var Url = Parser.GetPartByName(UrlPart); var Controller = Parser.GetPartByName(ControllerPart); var Token = Parser.GetPartByName(TokenPart); var DataStoreId = Parser.GetPartByName(DataStoreIdPart); var Serialization = Parser.GetPartByName(SerializationPart); Dictionary <string, string> Headers = new Dictionary <string, string>(); Headers.Add("Authorization", "Bearer " + Token); Headers.Add(DataStoreIdPart, DataStoreId); Uri uri = new Uri(new Uri(Url), Controller); string url = uri.ToString(); ISerializationAdapter Adapter = null; if (Serialization == "NewtonsoftSerializationAdapter") { Adapter = new NewtonsoftSerializationAdapter(); } if (Serialization == "ProtobufSerializationAdapter") { Adapter = new ProtobufSerializationAdapter(); } //TODO remove this line when we got an answer from https://github.com/MelbourneDeveloper/RestClient.Net/issues/75 Adapter = new NewtonsoftSerializationAdapter(); ApiFunction restClientNetFunctionClient = new ApiFunction(url, Adapter, Headers); return(new XpoWebApiProvider(restClientNetFunctionClient, new CompressXmlObjectSerializationService(), autoCreateOption)); //return new AsyncDataStoreWrapper(new XpoWebApiProvider(restClientNetFunctionClient, new SimpleObjectSerializationService(), autoCreateOption)); }
/// <summary> /// Get the type of a value from container by specific key /// </summary> /// <param name="key">Key string value</param> /// <returns> /// The type of the value, or null if the key is not found. /// </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="key"/> is null or whitespace.</exception> public Type GetValueType(string key) { // Checking parameters if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException("key", "Key cannot be empty"); } object storedValue; if (this.items.TryGetValue(key, out storedValue)) { ISerializationAdapter adapter = storedValue as ISerializationAdapter; if (adapter == null) { return(storedValue.GetType()); } else { return(adapter.DataType); } } return(null); }
public NetworkCommandServerToLoginTokenTranslator(IUserRegistrationService userRegistrationDataLayer, ISerializationAdapter serializationAdapter) { if (userRegistrationDataLayer == null) { throw new ArgumentNullException(nameof(userRegistrationDataLayer)); } UserRegistration = userRegistrationDataLayer; SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public NetworkCommandToInitialGameState(IWorldGameStateDataInputLayer gameStateDataLayer, ISerializationAdapter serializationAdapter) { if (gameStateDataLayer == null) { throw new ArgumentNullException(nameof(gameStateDataLayer)); } GameStatesDataLayer = gameStateDataLayer; SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public UpdateNetworkGameState(INetworkCommandConnectionToGameStateTranslator networkCommandToUpdateGameState, ISerializationAdapter serializationAdapter) { if (networkCommandToUpdateGameState == null) { throw new ArgumentNullException(nameof(networkCommandToUpdateGameState)); } CurrentNetworkCommandToUpdateGameState = networkCommandToUpdateGameState; SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
/// <summary> /// Clones the client With a change /// </summary> public static Client With(this Client client, ISerializationAdapter serializationAdapter) => client != null ? new Client( serializationAdapter, client.BaseUrl, client.DefaultRequestHeaders, client.logger is ILogger <Client> logger ? logger : null, client.createHttpClient, client.sendHttpRequestMessage, client.getHttpRequestMessage, client.ThrowExceptionOnFailure, client.Name) : throw new ArgumentNullException(nameof(client));
private CentralDelegationService( string peername, string ip, int port, string username, string password, ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); DelegationService = new UserDataDelegationService(serializationAdapter); DelegationService.TryLogin(peername, ip, port, username, password); }
public LoginState(UserData playerData, string ip, int port, ISerializationAdapter serializationAdapter) { if (string.IsNullOrEmpty(ip)) { throw new ArgumentException("message", nameof(ip)); } PlayerData = playerData ?? throw new ArgumentNullException(nameof(playerData)); ServerIp = ip; ServerPort = port; SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public ServerGameStateService( IUserLoginService loginService, IUserDataRoleService roleService, TWorld gameStateDataLayer, ISerializationAdapter serializationAdapter) { LoginService = loginService ?? throw new ArgumentNullException(nameof(loginService)); RoleService = roleService ?? throw new ArgumentNullException(nameof(roleService)); WorldGameStateDataLayer = gameStateDataLayer ?? throw new ArgumentNullException(nameof(gameStateDataLayer)); SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); LoadDefaultGameStates(); }
public NetOutgoingMessageBusService(TNetPeer peer, ISerializationAdapter serializationAdapter) { if (peer == null) { throw new ArgumentNullException(nameof(peer)); } Peer = peer; if (serializationAdapter == null) { throw new ArgumentNullException(nameof(serializationAdapter)); } SerializationAdapter = serializationAdapter; }
public NetworkCommandToUserDataWithLoginToken( IUserLoginService loginService, IUserDataRoleService roleService, ISerializationAdapter serializationAdapter) { if (loginService == null) { throw new ArgumentNullException(nameof(loginService)); } LoginService = loginService; if (roleService == null) { throw new ArgumentNullException(nameof(roleService)); } RoleService = roleService; SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public async Task <HttpResponseMessage> SendHttpRequestMessage <TRequestBody>( HttpClient httpClient, IGetHttpRequestMessage httpRequestMessageFunc, IRequest <TRequestBody> request, ILogger logger, ISerializationAdapter serializationAdapter) { if (httpClient == null) { throw new ArgumentNullException(nameof(httpClient)); } if (httpRequestMessageFunc == null) { throw new ArgumentNullException(nameof(httpRequestMessageFunc)); } if (request == default) { throw new ArgumentNullException(nameof(request)); } logger ??= NullLogger.Instance; try { var httpRequestMessage = httpRequestMessageFunc.GetHttpRequestMessage(request, logger, serializationAdapter); logger.LogTrace(Messages.InfoAttemptingToSend, request); var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, request.CancellationToken).ConfigureAwait(false); logger.LogInformation(Messages.InfoSendReturnedNoException); return(httpResponseMessage); } catch (OperationCanceledException oce) { logger.LogError(oce, Messages.ErrorMessageOperationCancelled, request); throw; } catch (Exception ex) { logger.LogError(ex, Messages.ErrorOnSend, request); throw; } }
private void Initialize() { Client = new NetClient( new NetPeerConfiguration(ClientConfiguration.ServerPeerName) { AcceptIncomingConnections = true, EnableUPnP = true, AutoFlushSendQueue = true }); Client.Start(); Client.Connect(ClientConfiguration.ServerIp, ClientConfiguration.ServerPort); var serializerType = GetSerializer(ClientConfiguration.SerializationAdapterType); //var serializerType = ClientConfiguration.SerializationAdapterType.LoadType(true, false)?.FirstOrDefault(); SerializationAdapter = Activator.CreateInstance(serializerType) as ISerializationAdapter; Input = new NetIncomingMessageBusService <NetClient>(Client); Output = new NetOutgoingMessageBusService <NetClient>(Client, SerializationAdapter); NetworkCommandDataConverterService = new NetworkCommandDataConverterService(SerializationAdapter); NetIncomingMessageNetworkCommand = new NetIncomingMessageNetworkCommandConnectionTranslator(new NetworkCommandTranslator(SerializationAdapter)); }
public FetchDataState(INetIncomingMessageBusService incomingMessageBusService, ISerializationAdapter serializationAdapter) { IncomingMessageBusService = incomingMessageBusService ?? throw new ArgumentNullException(nameof(incomingMessageBusService)); SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public CLIServerConnector(ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public NetworkCommandDataConverterService(ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); var lol = typeof(PlayerMetadataBag).Name; }
public ClientWorldGame(ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public StandardRestClientFactory(ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter; }
public PlayerSpaceshipUpdateGameStateFactory(ISerializationAdapter serializationAdapter, ImageToRectangleTransformationService imageToRectangleTransformationService) { SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); ImageToRectangleTransformationService = imageToRectangleTransformationService ?? throw new ArgumentNullException(nameof(imageToRectangleTransformationService)); }
public static IMessageBusBuilder AddSerializationAdapter(this IMessageBusBuilder builder, ISerializationAdapter serializationAdapter) { RemoteConfiguration.Adapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); return(builder); }
public RestClient(ISerializationAdapter serializationAdapter, Uri baseUri) { _HttpClient.BaseAddress = baseUri; _HttpClient.Timeout = new TimeSpan(0, 3, 0); SerializationAdapter = serializationAdapter; }
/// <summary> /// Initializes a new instance of the ApiFunction class with default settings. /// </summary> /// <param name="url">Api Url</param> /// <param name="serializationAdapter">An implementation of ISerializationAdapter</param> /// <param name="headers">Additional headers for the api request</param> public ApiFunction(string url, ISerializationAdapter serializationAdapter, IDictionary <string, string> headers) : this(new Client(serializationAdapter), url, headers) { }
/// <summary> /// Serializes an object of type T to a client message /// </summary> /// <typeparam name="T"></typeparam> /// <param name="stuff"></param> /// <returns></returns> public static NetOutgoingMessage ToClientOutgoingMessage <T>(this T stuff, NetClient client, ISerializationAdapter serializationAdapter) { return(client.CreateMessage(serializationAdapter.SerializeObject(stuff))); }
public HttpRequestMessage GetHttpRequestMessage <T>(IRequest <T> request, ILogger logger, ISerializationAdapter serializationAdapter) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (serializationAdapter == null) { throw new ArgumentNullException(nameof(serializationAdapter)); } logger ??= NullLogger.Instance; try { logger.LogTrace("Converting Request to HttpRequestMethod... Event: {event} Request: {request}", TraceEvent.Information, request); var httpMethod = string.IsNullOrEmpty(request.CustomHttpRequestMethod) ? request.HttpRequestMethod switch { HttpRequestMethod.Get => HttpMethod.Get, HttpRequestMethod.Post => HttpMethod.Post, HttpRequestMethod.Put => HttpMethod.Put, HttpRequestMethod.Delete => HttpMethod.Delete, HttpRequestMethod.Patch => new HttpMethod("PATCH"), HttpRequestMethod.Custom => throw new InvalidOperationException("CustomHttpRequestMethod must be specified for Custom Http Requests"), _ => throw new InvalidOperationException("That's not valid") } : new HttpMethod(request.CustomHttpRequestMethod); var httpRequestMessage = new HttpRequestMessage { Method = httpMethod, RequestUri = request.Uri }; ByteArrayContent?httpContent = null; if (request.BodyData != null) { var bodyDataData = serializationAdapter.Serialize(request.BodyData, request.Headers); httpContent = new ByteArrayContent(bodyDataData); httpRequestMessage.Content = httpContent; logger.LogTrace("Request content was set. Length: {requestBodyLength}", bodyDataData.Length); } else { logger.LogTrace("No request content set up on HttpRequestMessage"); } if (request.Headers != null) { foreach (var headerName in request.Headers.Names) { if (HeadersExtensions.ContentHeaderNames.Contains(headerName, StringComparer.OrdinalIgnoreCase)) //string.Compare(headerName, HeadersExtensions.ContentTypeHeaderName, StringComparison.OrdinalIgnoreCase) == 0) { //Note: not sure why this is necessary... //The HttpClient class seems to differentiate between content headers and request message headers, but this distinction doesn't exist in the real world... //TODO: Other Content headers httpContent?.Headers.Add(headerName, request.Headers[headerName]); } else { httpRequestMessage.Headers.Add(headerName, request.Headers[headerName]); } } logger.LogTrace("Headers added to request"); } logger.LogTrace("Successfully converted IRequest to HttpRequestMessage"); return(httpRequestMessage); }
public WorldGame ( GameServerConfiguration configuration ) { Configuration = configuration; var leSerializationType = configuration.SerializationAdapterType.LoadType(true, false)[0]; SerializationAdapter = Activator.CreateInstance(leSerializationType) as ISerializationAdapter; GameSectorLayerServices = new Dictionary <string, IStateMachine <string, IGameSectorLayerService> >(); SectorStateMachine = new InMemoryStorageGameSectorLayerServiceFactory(); AuthenticationService = new ExampleLoginAndRegistrationService(); CreateServer( Configuration.ServerPeerName, Configuration.ServerIp, Configuration.ServerPort); //translator var serverTranslator = new NetworkCommandTranslator(SerializationAdapter); var serverMessageTranslator = new NetIncomingMessageNetworkCommandConnectionTranslator(serverTranslator); var cliPassthrough = new CLIPassthroughMechanic(AuthenticationService, Configuration.RunOperation); var writer = new GameSectorLayerWriterMechanic { RedisHost = Configuration.RedisHost, RedisPort = Configuration.RedisPort }; var rediCliPassthrough = new RedisCLIPassthroughMechanic(AuthenticationService) { RedisHost = Configuration.RedisHost, RedisPort = Configuration.RedisPort }; SectorsOwnerMechanics = new List <ISingleUpdeatableMechanic <IGameSectorsOwner, IGameSectorsOwner> > { //routeTrespassingMarker, //playerShifter, cliPassthrough, rediCliPassthrough, writer }; //create default starting sector //AddSectorStateMachine(Configuration.StartingSector); BuildSector( Configuration.StartingSector, Configuration.StartingSector, Configuration.StartingSector, Configuration.StartingSector, Configuration.StartingSector); var inGameSectorStateMachine = GameSectorLayerServices[Configuration.StartingSector]; inGameSectorStateMachine.SharedContext = new GameSectorLayerService { Tag = Configuration.StartingSector }; //inGameSectorStateMachine.SharedContext.CurrentStatus = GameSectorStatus.Running; inGameSectorStateMachine .GetService .Get(Configuration.BuildOperation) .Handle(inGameSectorStateMachine); //var sectorList = new List<string>(); //for (int sectorIndex = 0; sectorIndex < 1; sectorIndex++) //{ // var sectorId = Guid.NewGuid().ToString(); // var sectorDown = Configuration.StartingSector; // var sectorUp = Configuration.StartingSector; // var sectorLeft = Configuration.StartingSector; // var sectorRight = Configuration.StartingSector; // if (sectorIndex - 4 > 0) // sectorDown = sectorList[sectorIndex - 4]; // if (sectorIndex - 3 > 0) // sectorUp = sectorList[sectorIndex - 3]; // if (sectorIndex - 2 > 0) // sectorLeft = sectorList[sectorIndex - 2]; // if (sectorIndex - 1 > 0) // sectorRight = sectorList[sectorIndex - 1]; // sectorList.Add(sectorId); // BuildSector(sectorId, sectorUp, sectorLeft, sectorRight, sectorDown); //} //datalayer to gather data out of the game world var serverStateDataLayer = new ServerGameStateService <WorldGame>( AuthenticationService, AuthenticationService, this, SerializationAdapter); //hard coded logger here GameStateContext = new ServerNetworkGameStateContext <WorldGame>( ServerInput, ServerOutput, serverMessageTranslator, serverStateDataLayer, GetLogger()); GameStateContext.Initialize(); //Language script file LanguageScriptFileEvaluator languageScriptFileEvaluator = new LanguageScriptFileEvaluator(Configuration.StartupScript, Configuration.StartupFunction, Configuration.RunOperation); foreach (var sector in GameSectorLayerServices.Values) { languageScriptFileEvaluator.Evaluate(sector); } Console.WriteLine("runner starting..." + Configuration.StartupFunction); CreateGameTimeIfNotExists(null); Console.WriteLine(CurrentGameTime); foreach (var sector in GameSectorLayerServices.Values) { sector.SharedContext.CurrentGameTime = CurrentGameTime; sector.Run(Configuration.StartupFunction); } }
public NetworkCommandTranslator(ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter; }
public SendGameStateUpdateDataState(ISerializationAdapter serializationAdapter) { SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public NetworkCommandToUserDataGameState(IUserLoginService loginService, ISerializationAdapter serializationAdapter) { LoginService = loginService ?? throw new ArgumentNullException(nameof(loginService)); SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }
public UserDataDelegationService(ISerializationAdapter serializationAdapter) { Messages = new ConcurrentBag <string>(); SerializationAdapter = serializationAdapter ?? throw new ArgumentNullException(nameof(serializationAdapter)); }