protected override BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData) { RequestSerializer data = (RequestSerializer)requestData; ResponseSerializer resp = (ResponseSerializer)InitializeResponseSerializer(); resp.Status = "OK"; Lobby lobby = (Lobby)conn.Session.Get("joined-lobby"); string username = (string)conn.Session.Get("username"); var signal = new ChatMessageSerializer() { Signal = ChatMessageSerializer.SIGNAL_CHAT_MESSAGE, Username = username, Message = username + ": " + data.Message }; Console.WriteLine("New message > {0}", username + ": " + data.Message); var result = new StandardCommunicateSerializer() { CommunicateType = StandardCommunicateSerializer.TYPE_LOBBY_SIGNAL, Data = signal.GetApiObject() }; lobby.Broadcast(result.GetApiObject()); return(resp); }
/// <summary> /// Wywołuje wykonanie akcji /// </summary> /// <param name="requestData">Dane wejściowe</param> /// <returns>Odpowiedź od akcji</returns> public JObject Invoke(ClientConnection conn, JObject requestData) { BaseSerializer requestSerializer = (BaseSerializer)Activator.CreateInstance(RequestSerializerType); requestSerializer.SetData(requestData); requestSerializer.Validate(); // Wywołanie wydarzenia var argsInvk = new ActionInvokeEventArgs() { RequestData = requestSerializer }; InvokedThis?.Invoke(this, argsInvk); Invoked?.Invoke(this, argsInvk); // Główna metoda wykonująca akcję BaseSerializer responseSerializer = PerformAction(conn, requestSerializer); // Wywołanie wydarzenia var argsFnshd = new ActionFinishEventArgs() { RequestData = requestSerializer, ResponseData = responseSerializer }; FinishedThis?.Invoke(this, argsFnshd); Finished?.Invoke(this, argsFnshd); // Zwrócenie odpowiedzi return(responseSerializer.GetApiObject()); }
/// <summary> /// Выполняет конвертацию из XML в аналогиченый JSON - элемент /// </summary> /// <param name="xml"></param> /// <returns></returns> public JsonItem ConvertToJsonItem(XElement xml) { if (xml.Attribute("__isarray") != null) { if (xml.Attribute("__isarray").Value == "true") { xml.SetAttributeValue(JsonItem.JsonTypeAttributeName, "array"); } } if (null == xml.Attribute(JsonItem.JsonTypeAttributeName)) { var json = BaseSerializer.Serialize("root", xml); var result = Parser.Parse(json); foreach (var n in result.CollectAllValues()) { n.Type = JsonTokenType.Auto; } return(result); } if (IsValue(xml)) { return(new JsonValue(xml)); } else if (IsArray(xml)) { return(ConvertToJsonArray(xml)); } else if (IsObject(xml)) { return(ConvertToJsonObject(xml)); } return(null); }
public BaseDispatcher(BaseSerializer serializer, IHandlerFactory factory, OperationRuntimeModel model, ILoggerFactory logger, DescriptionRuntimeModel descriptionRuntimeModel) { _serializer = serializer; _factory = factory; Model = model; _descriptionRuntimeModel = descriptionRuntimeModel; Logger = logger.CreateLogger(GetType().FullName); }
protected AbstractClient(IFactory <TConnection, Session> sessionFactory, IFactory <Session, IClientOperationExecutor> executorFactory, BaseDispatcher <TRequest, TResponse> dispatcher, BaseSerializer serializer, ILoggerFactory loggerFactory) { Serializer = serializer; _sessionFactory = sessionFactory; _executorFactory = executorFactory; _dispatcher = dispatcher; _dispatcher.ExecutionSide = Side.Client; Logger = loggerFactory.CreateLogger(GetType().FullName); Session = NotConnectedSession.Default; }
public OO2RDFOptions(Uri baseUrl, BaseSerializer serializer) { if (baseUrl == null || serializer == null) { throw new OO2RDFException("All parameters are required."); } _baseUrl = baseUrl; _serializer = serializer; }
/// <summary> /// Connect to the broker. /// </summary> public virtual Task Connect() { _serializer = (BaseSerializer)Activator.CreateInstance( Serializers.Types[_config.CommunicationFormatUsed] ); ConnectionState = ConnectionState.Connecting; _logger.Info("Connecting"); return(Task.CompletedTask); }
bool LoadParam(string fName) { SerialPortParams tmp = null; if (BaseSerializer <SerialPortParams> .LoadFromFile(fName, out tmp)) { m_spParams = tmp; return(true); } return(false); }
// TODO: For now, we're stogily assuming `val[whitespace][plus or minus][whitespace][value]` etc. // TODO: Even though we're allowing multiple column names and values, this is still pretty naive, // as we're not handling parentheses or order of operations at all. public static byte[] ConstructValue(Column colOutput, string strClause, byte[] abytRowOfValues, TableContext table) { string strOrigClause = strClause; strClause = "+ " + strClause; string[] astrTokens = strClause.Split(); if (0 != astrTokens.Length % 2) { throw new Exception("Illegal update clause (value-operator count mismatch): " + strOrigClause); } Queue <CompositeColumnValueModifier> qModifiers = new Queue <CompositeColumnValueModifier>(); for (int i = 0; i < astrTokens.Length; i = i + 2) { qModifiers.Enqueue( new CompositeColumnValueModifier( astrTokens[i + 1].IsNumeric() ? astrTokens[i + 1] : string.Empty, astrTokens[i + 1].IsNumeric() ? null : table.getColumnByName(astrTokens[i + 1]), !astrTokens[i].Equals("-") ) ); } // I realize I could've done this in the loop where I construct // the UpdateModifiers, but this feels a little cleaner. byte[] abytResult = new byte[colOutput.intColLength]; BaseSerializer outputSerializer = Router.routeMe(colOutput); foreach (CompositeColumnValueModifier modifier in qModifiers) { if (modifier.isValueNotColumn) { abytResult = outputSerializer.addRawToStringRepresentation(abytResult, modifier.strValue, !modifier.isAdditionModifierNotSubtraction); } else { if (colOutput.intColLength < modifier.column.intColLength || !ColsAreCompatible(colOutput, modifier.column)) { throw new Exception("Value aggregation attempted to aggregate values that were potentially too large or with columns of incompatible types."); } byte[] abytValToAdd = new byte[modifier.column.intColLength]; Array.Copy(abytRowOfValues, modifier.column.intColStart, abytValToAdd, 0, modifier.column.intColLength); abytResult = outputSerializer.addRawToRaw(abytResult, abytValToAdd, !modifier.isAdditionModifierNotSubtraction); } } return(abytResult); }
protected override BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData) { // requestData ma typ taki, jak zdefiniujemy w konstruktorze, // więc możemy zrobić proste rzutowanie RequestSerializer data = (RequestSerializer)requestData; // Od razu inicjalizujemy też serializator do odpowiedzi // Poniższa linia robi to samo co "var resp = new ResponseSerializer();" RequestSerializer resp = (RequestSerializer)InitializeResponseSerializer(); Console.WriteLine("Hello " + data.Name + "!"); resp.Name = "System"; return(resp); }
protected override BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData) { RequestSerializer data = (RequestSerializer)requestData; ResponseSerializer resp = (ResponseSerializer)InitializeResponseSerializer(); resp.Status = "OK"; Lobby lobby = (Lobby)conn.Session.Get("joined-lobby"); Match game = lobby.Game; if (lobby.LobbyState != LobbyState.IDLE) { data.AddError(null, "INVALID_LOBBY_STATE", "Nie można usiąść w tym momencie gry"); data.ThrowException(); } try { var player = new Player((PlayerTag)data.PlaceTag, (string)conn.Session.Get("username")); game.AddPlayer(player); conn.Session.Set("player", player); Console.WriteLine("Player sat at " + data.PlaceTag + ": " + conn.Session.Get("username")); var broadcastData = new LobbySignalUserSatSerializer() { Signal = LobbySignalUserSatSerializer.SIGNAL_USER_SAT, PlaceTag = data.PlaceTag, Username = player.Name }; var broadcastWrapper = new StandardCommunicateSerializer() { CommunicateType = StandardCommunicateSerializer.TYPE_LOBBY_SIGNAL, Data = broadcastData.GetApiObject() }; lobby.Broadcast(broadcastWrapper.GetApiObject()); } catch (SeatTakenException) { data.AddError("PlaceTag", "SEAT_TAKEN", "Miejsce jest już zajęte"); data.ThrowException(); } catch (DuplicatedPlayerNameException) { data.AddError(null, "ALREADY_SEATED", "Użytkownik zajął już miejsce"); data.ThrowException(); } catch (WrongGameStateException) { data.AddError(null, "WRONG_GAME_STATE", "Nieprawidłowy stan gry dla tej operacji"); data.ThrowException(); } return(resp); }
public static void Test(BaseSerializer serializer, Action<MemoryStream> logger, object value,Type type) { SerializationServices.AssemblyLoader = assemblyLoader; SerializationServices.InstanceFactory = factory; object other; using (var mem = new MemoryStream()) { serializer.Serialize(mem,value); mem.Position = 0; logger(mem); mem.Position = 0; other = serializer.Deserialize(mem, type); } Assert.AreEqual(value,other); }
protected override BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData) { RequestSerializer data = (RequestSerializer)requestData; ResponseSerializer resp = (ResponseSerializer)InitializeResponseSerializer(); resp.Status = "OK"; Lobby lobby = (Lobby)conn.Session.Get("joined-lobby"); Match game = lobby.Game; Player player = new Player((PlayerTag)data.PlaceTag, (string)conn.Session.Get("username")); if (player != null) { try { game.RemovePlayer(player); conn.Session.Remove("player"); lobby.SetLobbyState(LobbyState.IDLE); var username = conn.Session.Get <string>("username"); var signal = new LobbySignalUserSittedOutSerializer() { Signal = LobbySignalUserSittedOutSerializer.SIGNAL_USER_SITTED_OUT, Message = "User " + username + " joined the lobby", Username = username, PlaceTag = (int)player.Tag }; var result = new StandardCommunicateSerializer() { CommunicateType = StandardCommunicateSerializer.TYPE_LOBBY_SIGNAL, Data = signal.GetApiObject() }; lobby.Broadcast(result.GetApiObject()); Console.WriteLine("Player left at " + data.PlaceTag + ": " + conn.Session.Get("username")); } catch (WrongPlayerException) { data.AddError("PlaceTag", "NOT_SEATEN_HERE", "Gracz nie siedzi na tym miejscu"); data.ThrowException(); } } return(resp); }
private static Comparison _CreateComparison(string strClause, TableContext table) { string strOperator = "="; if (strClause.ContainsOutsideOfQuotes("<")) { strOperator = "<"; } else if (strClause.ContainsOutsideOfQuotes(">")) { strOperator = ">"; } else if (strClause.ContainsOutsideOfQuotes("LIKE", '\'', '`')) { strOperator = "LIKE"; } else if (strClause.ContainsOutsideOfQuotes("like", '\'', '`')) { // kludge until I get case sensitivity into ContainsOutsideOfQuotes. // Too bad, lIkE. strOperator = "like"; } else if (!strClause.ContainsOutsideOfQuotes("=")) { throw new Exception("Illegal comparison type in SelectCommand: " + strClause); } string[] astrComparisonParts = strClause.SplitSeeingSingleQuotesAndBackticks(strOperator, false).Take(2).ToArray(); Column colToConstrain = table.getColumnByName(astrComparisonParts[0].Trim()); if (null == colToConstrain) { throw new ColumnNotFoundException("Column not found in SELECT statement: " + astrComparisonParts[0]); } BaseSerializer serializer = Router.routeMe(colToConstrain); byte[] abytComparisonVal = serializer.toByteArray(astrComparisonParts[1].Trim()); return(new Comparison(strOperator, colToConstrain, abytComparisonVal)); }
public static void Test(BaseSerializer serializer, Action <MemoryStream> logger, object value, Type type) { //TODO: Ask Pedro /*SerializationServices.AssemblyLoader = assemblyLoader; * SerializationServices.InstanceFactory = factory;*/ object other; using (var mem = new MemoryStream()) { serializer.Serialize(mem, value); mem.Position = 0; logger(mem); mem.Position = 0; other = serializer.Deserialize(mem, type); } Assert.AreEqual(value, other); }
public Client(IFactory <NetPeer, Session> sessionFactory, IFactory <Session, IClientOperationExecutor> executorFactory, BaseDispatcher <TRequest, TResponse> dispatcher, BaseSerializer serializer, ILoggerFactory loggerFactory) : base(sessionFactory, executorFactory, dispatcher, serializer, loggerFactory) { Manager = new NetManager(this); }
public void RunSerialize <TSymbols, TObject>(BaseSerializer <TSymbols> serializer, BaseTest <TObject> test) { object result = null; var dataRow = results.Rows.Cast <DataRow>().First(dataRow => Equals(dataRow[TestName], test.TestName) && Equals(dataRow[MethodName], SerValue)); Dispatcher.InvokeAsync(() => { dataRow[serializer.Name] = RuningValue; }); try { TObject obj = default; TSymbols symbols = default; double ns = default; var isTimeout = !Task.Run(() => { obj = test.GetObject(); symbols = serializer.Serialize(obj); var stopwatch = Stopwatch.StartNew(); serializer.Serialize(obj); ns = stopwatch.ElapsedNanoseconds(); }).Wait(MillisecondsTimeout); if (isTimeout) { throw new TimeoutException(); } long count = 0; double total = 0; double min = double.MaxValue; double max = double.MinValue; for (int i = 0; i < 10; i++) { Run(1); Run((int)(10 / GetAvg())); Run((int)(100 / GetAvg())); Run((int)(1000 / GetAvg())); Run((int)(10000 / GetAvg())); Run((int)(100000 / GetAvg())); Run((int)(1000000 / GetAvg())); Run((int)(10000000 / GetAvg())); Run((int)(100000000 / GetAvg())); Run((int)(500000000 / GetAvg())); } double GetAvg() { return(total / count); } void Run(int times) { if (!(times > 0)) { return; } TSymbols tSym = default; var stopwatch = Stopwatch.StartNew(); for (int i = 0; i < times; i++) { tSym = serializer.Serialize(obj); } var ns = stopwatch.ElapsedNanoseconds(); total += ns; count += times; min = Math.Min(min, ns / times); max = Math.Max(min, ns / times); var tObj = serializer.Deserialize <TObject>(tSym); if (!test.Equals(tObj, obj)) { throw new IncorrectException(); } } result = new Result(GetAvg()); } catch (Exception e) { result = new ExceptionResult(e); } finally { Dispatcher.InvokeAsync(() => { dataRow[serializer.Name] = result; }); } }
public DefaultClientOperationExecutorFactory(OperationRuntimeModel model, BaseSerializer serializer, ILoggerFactory loggerFactory) { _model = model; _serializer = serializer; _loggerFactory = loggerFactory; }
public Serializer(BaseSerializer serializerType) { _serializerType = serializerType; }
protected override BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData) { RequestSerializer data = (RequestSerializer)requestData; ResponseSerializer resp = (ResponseSerializer)InitializeResponseSerializer(); resp.Status = "OK"; resp.Color = data.Color; resp.Height = data.Height; resp.X = data.X; resp.XX = data.XX; Lobby lobby = (Lobby)conn.Session.Get("joined-lobby"); Match game = lobby.Game; if (lobby.LobbyState != LobbyState.IN_GAME) { data.AddError(null, "INVALID_LOBBY_STATE", "Nie można licytować w tym stanie lobby"); data.ThrowException(); } string username = (string)conn.Session.Get("username"); int playerIndex = game.PlayerList.FindIndex(x => { return(username == x.Name); }); // gdy nie ma takiego gracza przy stole => wywal wyjątek if (playerIndex == -1) { data.AddError("PlayerUsername", "INVALID_PLAYER", "Nie ma takiego gracza"); data.ThrowException(); } var player = game.PlayerList[playerIndex]; var contract = new Contract((ContractHeight)data.Height, (ContractColor)data.Color, player.Tag, data.X, data.XX); if (!game.CheckAddBid(contract)) { data.AddError(null, "INVALID_CONTRACT", "Nie można zalicytować kontraktu"); data.ThrowException(); } game.AddBid(contract); Console.WriteLine(username + "> Bid: " + contract.ToString()); // Broadcast do pozostałych graczy var broadcastData = new LobbySignalNewBidSerializer() { Signal = LobbySignalNewBidSerializer.SIGNAL_NEW_BID, Username = username, PlaceTag = (int)player.Tag, Color = data.Color, Height = data.Height, X = data.X, XX = data.XX }; var broadcastWrapper = new StandardCommunicateSerializer() { CommunicateType = StandardCommunicateSerializer.TYPE_LOBBY_SIGNAL, Data = broadcastData.GetApiObject() }; lobby.Broadcast(broadcastWrapper.GetApiObject()); // Broadcast o przepasowaniu całej licytacji, nowe rozdanie if (game.CurrentBidding.IsEnd() && game.CurrentBidding.HighestContract.ContractColor == ContractColor.NONE) { game.GameState = GameState.BIDDING; game.StartBidding(); var bData = new LobbySignalGameStartedNextBiddingSerializer() { Signal = LobbySignalGameStartedNextBiddingSerializer.SIGNAL_GAME_STARTED_NEXT_BIDDING, PointsNSAboveLine = game.PointsNS[1], PointsNSBelowLine = game.PointsNS[0], PointsWEAboveLine = game.PointsWE[1], PointsWEBelowLine = game.PointsWE[0], RoundsNS = game.RoundsNS, RoundsWE = game.RoundsWE }; var bWrapper = new StandardCommunicateSerializer() { CommunicateType = StandardCommunicateSerializer.TYPE_LOBBY_SIGNAL, Data = bData.GetApiObject() }; lobby.Broadcast(bWrapper.GetApiObject()); } return(resp); }
public HostOperationExecutor(OperationRuntimeModel model, BaseSerializer serializer, SessionCollection sessions, ILoggerFactory loggerFactory) : base(model, serializer, loggerFactory) { _sessions = sessions; }
void SaveParam() { BaseSerializer <SerialPortParams> .SaveToFile(m_paramFileFullName, m_spParams); }
/// <summary> /// Właściwa metoda wykonująca akcję. Otrzymuje na wejściu zwalidowane dane po walidacji /// </summary> /// <param name="requestData">Dane wejściowe wpisane do serializatora. Serializator przekazywany na wejściu jest typu "requestSerializerType", definiowanego w konstruktorze</param> /// <returns>Odpowiedź w postaci serializatora</returns> protected abstract BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData);
protected override BaseSerializer PerformAction(ClientConnection conn, BaseSerializer requestData) { RequestSerializer data = (RequestSerializer)requestData; ResponseSerializer resp = (ResponseSerializer)InitializeResponseSerializer(); resp.Status = "OK"; Lobby lobby = (Lobby)conn.Session.Get("joined-lobby"); Match game = lobby.Game; string username = (string)conn.Session.Get("username"); resp.MatchInfo = new MatchSerializer(); resp.MatchInfo.EWPointsHistory = new string[game.History.WEHistory.Count]; resp.MatchInfo.NSPointsHistory = new string[game.History.NSHistory.Count]; for (int i = 0; i < game.History.WEHistory.Count; i++) { resp.MatchInfo.EWPointsHistory[i] = game.History.WEHistory[i]; } for (int i = 0; i < game.History.NSHistory.Count; i++) { resp.MatchInfo.NSPointsHistory[i] = game.History.NSHistory[i]; } resp.MatchInfo.CurrentBidding = new BiddingSerializer(); resp.MatchInfo.CurrentBidding.ContractList = new ContractSerializer[game.CurrentBidding.ContractList.Count]; for (int i = 0; i < game.CurrentBidding.ContractList.Count; i++) { var tmp = new ContractSerializer(); tmp.ContractColor = (int)game.CurrentBidding.ContractList[i].ContractColor; tmp.ContractHeight = (int)game.CurrentBidding.ContractList[i].ContractHeight; tmp.PlayerTag = (int)game.CurrentBidding.ContractList[i].DeclaredBy; tmp.XEnabled = game.CurrentBidding.ContractList[i].XEnabled; tmp.XXEnabled = game.CurrentBidding.ContractList[i].XXEnabled; resp.MatchInfo.CurrentBidding.ContractList[i] = tmp; } resp.MatchInfo.CurrentBidding.BiddingEnded = game.CurrentBidding.End; resp.MatchInfo.CurrentBidding.CurrentPlayerTag = (int)game.CurrentBidding.CurrentPlayer; resp.MatchInfo.CurrentBidding.Dealer = (int)game.CurrentBidding.Dealer; var tmpHighestBidContract = new ContractSerializer(); tmpHighestBidContract.ContractColor = (int)game.CurrentBidding.HighestContract.ContractColor; tmpHighestBidContract.ContractHeight = (int)game.CurrentBidding.HighestContract.ContractHeight; tmpHighestBidContract.PlayerTag = (int)game.CurrentBidding.HighestContract.DeclaredBy; tmpHighestBidContract.XEnabled = game.CurrentBidding.HighestContract.XEnabled; tmpHighestBidContract.XXEnabled = game.CurrentBidding.HighestContract.XXEnabled; resp.MatchInfo.CurrentBidding.HighestContract = tmpHighestBidContract; //resp.MatchInfo.CurrentBidding.PassCounter = game.CurrentBidding.HighestContract resp.MatchInfo.PointsNS = new int[game.PointsNS.Length]; resp.MatchInfo.PointsEW = new int[game.PointsWE.Length]; for (int i = 0; i < game.PointsNS.Length; i++) { resp.MatchInfo.PointsNS[i] = game.PointsNS[i]; } for (int i = 0; i < game.PointsWE.Length; i++) { resp.MatchInfo.PointsEW[i] = game.PointsWE[i]; } resp.MatchInfo.RoundsNS = game.RoundsNS; resp.MatchInfo.RoundsEW = game.RoundsWE; resp.MatchInfo.Dealer = (int)game.Dealer; resp.MatchInfo.GameState = (int)game.GameState; resp.MatchInfo.PlayerList = new PlayerSerializer[4]; resp.MatchInfo.GrandpaCards = new CardSerializer[13]; PlayerSerializer tmpPlayerSerializer; for (int i = 0; i < 4; i++) { if (game.PlayerList[i] != null) { tmpPlayerSerializer = new PlayerSerializer(); tmpPlayerSerializer.PlayerTag = (int)game.PlayerList[i].Tag; tmpPlayerSerializer.Username = game.PlayerList[i].Name; resp.MatchInfo.PlayerList[i] = tmpPlayerSerializer; switch (game.PlayerList[i].Tag) { case PlayerTag.N: resp.MatchInfo.NPlayerHandSize = game.PlayerList[i].Hand.Length; break; case PlayerTag.E: resp.MatchInfo.EPlayerHandSize = game.PlayerList[i].Hand.Length; break; case PlayerTag.S: resp.MatchInfo.SPlayerHandSize = game.PlayerList[i].Hand.Length; break; case PlayerTag.W: resp.MatchInfo.WPlayerHandSize = game.PlayerList[i].Hand.Length; break; } bool IsGrand = IsPlayerGrand(game.PlayerList[i].Tag, game); if (game.PlayerList[i].Name == username) // przypadek gdy to są moje karty { resp.MatchInfo.PlayerCards = new CardSerializer[game.PlayerList[i].Hand.Length]; for (int c = 0; c < game.PlayerList[i].Hand.Length; c++) { resp.MatchInfo.PlayerCards[c] = new CardSerializer(); resp.MatchInfo.PlayerCards[c].Color = (int)game.PlayerList[i].Hand[c].Color; resp.MatchInfo.PlayerCards[c].Figure = (int)game.PlayerList[i].Hand[c].Figure; resp.MatchInfo.PlayerCards[c].State = (int)game.PlayerList[i].Hand[c].CurrentState; } resp.MatchInfo.GrandpaCards = null; } else if (IsGrand) // przypadek gdy to nie są moje karty { resp.MatchInfo.PlayerCards = null; bool GrandCardsVisible = AreGrandCardsVisible(game); if (GrandCardsVisible) { resp.MatchInfo.GrandpaCards = new CardSerializer[game.PlayerList[i].Hand.Length]; for (int c = 0; c < game.PlayerList[i].Hand.Length; c++) { resp.MatchInfo.GrandpaCards[c] = new CardSerializer(); resp.MatchInfo.GrandpaCards[c].Color = (int)game.PlayerList[i].Hand[c].Color; resp.MatchInfo.GrandpaCards[c].Figure = (int)game.PlayerList[i].Hand[c].Figure; resp.MatchInfo.GrandpaCards[c].State = (int)game.PlayerList[i].Hand[c].CurrentState; } } else { resp.MatchInfo.GrandpaCards = null; } } } else { resp.MatchInfo.PlayerList[i] = null; } } resp.MatchInfo.GameInfo = new GameInfoSerializer(); resp.MatchInfo.GameInfo.ContractColor = (int)game.CurrentGame.ContractColor; resp.MatchInfo.GameInfo.CurrentPlayer = (int)game.CurrentGame.CurrentPlayer; resp.MatchInfo.GameInfo.CurrentTrick = new TrickSerializer(); resp.MatchInfo.GameInfo.CurrentTrick.CardList = new CardSerializer[4]; for (int i = 0; i < 4; i++) { resp.MatchInfo.GameInfo.CurrentTrick.CardList[i] = null; } for (int i = 0; i < game.CurrentGame.currentTrick.CardList.Count; i++) { resp.MatchInfo.GameInfo.CurrentTrick.CardList[i] = new CardSerializer(); resp.MatchInfo.GameInfo.CurrentTrick.CardList[i].Color = (int)game.CurrentGame.currentTrick.CardList[i].Color; resp.MatchInfo.GameInfo.CurrentTrick.CardList[i].Figure = (int)game.CurrentGame.currentTrick.CardList[i].Figure; resp.MatchInfo.GameInfo.CurrentTrick.CardList[i].State = (int)game.CurrentGame.currentTrick.CardList[i].CurrentState; } resp.MatchInfo.GameInfo.CurrentTrick.Winner = (int)game.CurrentGame.currentTrick.Winner; resp.MatchInfo.GameInfo.Declarer = (int)game.CurrentGame.Declarer; return(resp); }
protected SessionRequestHandler(BaseSerializer serializer) { _serializer = serializer; }
public TestDispatcher(BaseSerializer serializer, IHandlerFactory factory, OperationRuntimeModel model, ILoggerFactory logger, DescriptionRuntimeModel descriptionRuntimeModel) : base(serializer, factory, model, logger, descriptionRuntimeModel) { }
public Factory(OperationRuntimeModel model, BaseSerializer serializer, ILoggerFactory logger) { _model = model; _serializer = serializer; _logger = logger; }
public TcpNetOperationClient(IFactory <Socket, Session> sessionFactory, IFactory <Session, IClientOperationExecutor> executorFactory, BaseDispatcher <TRequest, TResponse> dispatcher, ILoggerFactory logger, BaseSerializer serializer) : base(sessionFactory, executorFactory, dispatcher, serializer, logger) { Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Client.LingerState.Enabled = false; Client.Blocking = false; }
private static bool SaveStateForProperty(ISerializedObject obj, InspectedProperty property, BaseSerializer serializer, ISerializationOperator serializationOperator, out string serializedValue, ref bool success) { object currentValue = property.Read(obj); try { if (currentValue == null) { serializedValue = null; } else { serializedValue = serializer.Serialize(property.MemberInfo, currentValue, serializationOperator); } return(true); } catch (Exception e) { success = false; serializedValue = null; Debug.LogError("Exception caught when serializing property <" + property.Name + "> in <" + obj + "> with value " + currentValue + "\n" + e); return(false); } }
private static bool Upsert <T, TId>(IMongoCollection <T> collection, T entity, BaseSerializer <T, TId> idProvider) { if (idProvider.FillId(collection, entity)) { collection.InsertOne(entity); return(true); } var res = collection.ReplaceOne( Builders <T> .Filter.Eq("_id", idProvider.GetId(entity)), entity, new UpdateOptions { IsUpsert = true }); return(res.ModifiedCount <= 1); }
private List <Comparison> _createWhereConditions(string strWhere) { List <Comparison> lstReturn = new List <Comparison>(); if (!string.IsNullOrWhiteSpace(strWhere)) { strWhere = strWhere.Substring(6); //string[] astrClauses = Regex.Split (strWhere, @"AND"); string[] astrClauses = strWhere.Split(new string[] { "AND" }, StringSplitOptions.None); for (int i = 0; i < astrClauses.Length; i++) { Comparison comparison = null; string strClause = astrClauses[i].Trim(); if (MainClass.bDebug) { Console.WriteLine("Where clause #" + i + " " + strClause); } // TODO: Use real RegExes so we're not keying on non-actionable signs. // TODO: Do the selecting in the binary, but sort with DataTable. string patternHasEquals = "="; Match equalsMatch = Regex.Match(strClause, patternHasEquals); if (equalsMatch.Success) { string[] astrEqualsParts = Regex.Split(strClause, patternHasEquals); if (MainClass.bDebug) { Console.WriteLine("Equals clause: " + astrEqualsParts[0] + " :: " + astrEqualsParts[1]); } // TODO: Trim in regexp processing? // TODO: Factor out split on token by doing all three in one regexp before hitting the if tree. // Would remove colToConstrain, null check, and serializer construction from each. Column colToConstrain = _table.getColumnByName(astrEqualsParts[0].Trim()); if (null == colToConstrain) { throw new Exception("Column not found in DELETE statement (0): " + astrEqualsParts[0]); } BaseSerializer serializer = Router.routeMe(colToConstrain); byte[] abytComparisonVal = serializer.toByteArray(astrEqualsParts[1].Trim()); comparison = new Comparison(COMPARISON_TYPE.EQUALS, colToConstrain, abytComparisonVal); } else { string patternHasLt = "<"; Match ltMatch = Regex.Match(strClause, patternHasLt); if (ltMatch.Success) { string[] astrLtParts = Regex.Split(strClause, patternHasLt); if (MainClass.bDebug) { Console.WriteLine("Less than clause: " + astrLtParts[0] + " :: " + astrLtParts[1]); } // TODO: Trim in regexp processing? Column colToConstrain = _table.getColumnByName(astrLtParts[0].Trim()); if (null == colToConstrain) { throw new Exception("Column not found in DELETE statement (1): " + astrLtParts[0]); } BaseSerializer serializer = Router.routeMe(colToConstrain); byte[] abytComparisonVal = serializer.toByteArray(astrLtParts[1].Trim()); comparison = new Comparison(COMPARISON_TYPE.LESS_THAN, colToConstrain, abytComparisonVal); } else { string patternHasGt = ">"; Match gtMatch = Regex.Match(strClause, patternHasGt); if (gtMatch.Success) { string[] astrGtParts = Regex.Split(strClause, patternHasGt); if (MainClass.bDebug) { Console.WriteLine("Greater than clause: " + astrGtParts[0] + " :: " + astrGtParts[1]); } // TODO: Trim in regexp processing? Column colToConstrain = _table.getColumnByName(astrGtParts[0].Trim()); if (null == colToConstrain) { throw new Exception("Column not found in DELETE statement (3): " + astrGtParts[0]); } BaseSerializer serializer = Router.routeMe(colToConstrain); byte[] abytComparisonVal = serializer.toByteArray(astrGtParts[1].Trim()); comparison = new Comparison(COMPARISON_TYPE.GREATER_THAN, colToConstrain, abytComparisonVal); } } } if (null != comparison) { lstReturn.Add(comparison); } } } return(lstReturn); }