示例#1
0
    /* request the number of championships for each city in database for a client query */
    public void getCitiesChampionshipsNum(bool delay)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (delay)
        {
            ManualResetEvent delayEvent = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback((_) =>
            {
                sleep();
                delayEvent.Set();
            }));
            delayEvent.WaitOne();
        }

        using (var db = new TTTDataClassesDataContext())
        {
            var x = db.Championships.GroupBy(c => c.City);
            CityChampionships[] citiesChmps = new CityChampionships[x.Count()];
            int i = 0;
            foreach (var cc in x)
            {
                citiesChmps[i]      = new CityChampionships();
                citiesChmps[i].City = cc.Key;
                citiesChmps[i++].NumberOfChampionships = cc.Count();
            }
            channel.sendCitiesChampionshipsNum(citiesChmps);
        }
    }
示例#2
0
        public void Add(int x, int y)
        {
            var       result   = x + y;
            ICallBack callBack = OperationContext.Current.GetCallbackChannel <ICallBack>();

            callBack.Show($"INT:{x}+{y}={result}");
        }
示例#3
0
        // ---- команды управления пользователем ----

        /// <summary>
        /// Зарегистрироваться в системе
        /// </summary>
        /// <param name="Role">Требуемая роль в системе</param>
        /// <returns>Описатель используемый при взаимодействии в системе в дальнейшем</returns>
        public Handle Register(Role Role)
        {
            try
            {
                locker.AcquireWriterLock(300);
                try
                {
                    /*if (Role == Role.Basic)
                     * {
                     *  foreach (var user in users)
                     *  {
                     *      if (user.Role == Role.Basic)
                     *      {
                     *          return null;
                     *      }
                     *  }
                     * }*/

                    ICallBack proxy = OperationContext.Current.GetCallbackChannel <ICallBack>();
                    if (proxy != null)
                    {
                        User user = User.InstanceUser(proxy, Role);
                        users.Add(user);

                        return(user.Handle);
                    }
                }
                finally
                {
                    locker.ReleaseWriterLock();
                }
            }
            catch { }
            return(null);
        }
示例#4
0
        public void Add(double x, double y)
        {
            var       result   = x + y;
            ICallBack callBack = OperationContext.Current.GetCallbackChannel <ICallBack>();

            callBack.Show($"Double:{x}+{y}={result}");
        }
示例#5
0
    public void addPlayer(ICallBack player, int dim)
    {
        if (this.dim != dim)
        {
            player.gameError("Something went wrong...\nDifferenet dimensions of board");
            return;
        }

        if (player1 == null)
        {
            player.gameError("Something went wrong...\nPlayer1 is not found");
            return;
        }

        if (player == player1)
        {
            player.gameError("Something went wrong...\nTrying to add the same player");
            return;
        }

        if (player1 != null && singlePlayer)
        {
            player.gameError("Something went wrong...\nThe game is already occupied by single player game");
            return;
        }

        waitingForPlayer2 = false;
        player2           = player;
        game.Player2      = server.getPlayerData(player).Id;
    }
示例#6
0
    public Board(int dim, bool singlePlayer, ICallBack player, TTT server)
    {
        this.dim          = dim;
        this.singlePlayer = singlePlayer;
        this.server       = server;
        initBoard();
        moveCount = 0;
        gameEnded = false;
        player1   = player;
        if (singlePlayer)
        {
            rand = new Random();
        }

        game           = new Game();
        game.BoardSize = dim;
        game.Player1   = server.getPlayerData(player).Id;
        game.StartTime = DateTime.Now;
        game.Moves     = "";                    // simple array

        if (singlePlayer)
        {
            game.Player2 = 1;
        }

        waitingForPlayer2 = !singlePlayer;
    }
        /// <summary>
        /// Print all the integers between a lowerBound and and upperBound (inclusive).
        /// Except, filter out certain integer values, if they are divisible by any of a List of integer Keys,
        /// replace those values with a Value associated with that particular Key.
        /// If more than one happens to match, then append each Value, in the order it appears in the List.
        /// Return the results, one number/string at a time, through a generic callBack method
        /// </summary>
        /// <param name="lowerBound">Start counting at this integer</param>
        /// <param name="upperBound">Stop counting at this integer</param>
        /// <param name="callBack">Invoke the CallBack method of this class to collect each integer/String</param>
        /// <param name="patternList">An ordered List of Name/Value pairs of integers/Strings to be replaced</param>
        public static void CountUp(int lowerBound, int upperBound, ICallBack callBack,
                                   List <KeyValuePair <int, String> > patternList)
        {
            for (int i = lowerBound; i <= upperBound; i++)
            {
                String result  = "";
                bool   matched = false;

                foreach (KeyValuePair <int, String> pair in patternList)
                {
                    // We'll never be evenly divisible by zero
                    if (pair.Key == 0)
                    {
                        continue;
                    }

                    // Are we divisible by this Key?
                    if (i % pair.Key == 0)
                    {
                        // Append the Value associated with this Key
                        result += pair.Value;
                        matched = true;
                    }
                }

                // Did we match anything?  If not, return the integer
                if (!matched)
                {
                    result = String.Format("{0}", i);
                }

                // Send the result back to the caller
                callBack.CallBack(result);
            }
        }
示例#8
0
    private void computerMove(ICallBack player)
    {
        Thread.Sleep(1000);

        int row = -1, col = -1;

        do
        {
            row = rand.Next(0, dim);
            col = rand.Next(0, dim);
        } while (isPressed(row, col));

        board[row, col] = 'O';
        addGameMove(row, col);
        moveCount++;
        player.opponentPressed(row, col);

        if (checkWinning('O'))
        {
            player.gameEnded("You lose..");
            game.Winner = 1;
            endGame();
        }
        else if (isBoardFull())
        {
            player.gameEnded("It's a tie..");
            endGame();
        }
        else
        {
            player.playerTurn();
        }
    }
示例#9
0
    /* request the number of games for each player in database for a client query */
    public void getPlayersGamesNum(bool delay)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (delay)
        {
            ManualResetEvent delayEvent = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback((_) =>
            {
                sleep();
                delayEvent.Set();
            }));
            delayEvent.WaitOne();
        }

        using (var db = new TTTDataClassesDataContext())
        {
            PlayerGames[] playersGames = new PlayerGames[db.Players.Count() - 1];
            int           i            = 0;
            foreach (var p in db.Players)
            {
                if (p.Id != SERVER)
                {
                    playersGames[i]      = new PlayerGames();
                    playersGames[i].Name = p.Id + " : " + p.FirstName;
                    var x = db.Games.Where(g => g.Player1 == p.Id || g.Player2 == p.Id);
                    playersGames[i++].NumberOfGames = x.Count();
                }
            }
            channel.sendPlayersGamesNum(playersGames);
        }
    }
示例#10
0
        /// <summary>
        /// 完成计算  然后回调
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void Plus(int x, int y)
        {
            int       nResult  = x + y;
            ICallBack callBack = OperationContext.Current.GetCallbackChannel <ICallBack>();

            callBack.Show(1, 2, nResult);
        }
    //获得关卡数据
    public static void GetUserLevelInfos(MonoBehaviour behaviour, ICallBack callBack)
    {
        var userLevelInfoRelativePath = UserInfoManager._instance.GetUserInfo().userLevelInfosPath;
        var wordInfoPath = RemotePath + userLevelInfoRelativePath;

        behaviour.StartCoroutine(GetInfo(wordInfoPath, callBack));
    }
示例#12
0
    /* request all players of a specific championship from database for a client query */
    public void getChampionshipPlayers(ChampionshipData chmp, bool delay)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (delay)
        {
            ManualResetEvent delayEvent = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback((_) =>
            {
                sleep();
                delayEvent.Set();
            }));
            delayEvent.WaitOne();
        }

        using (var db = new TTTDataClassesDataContext())
        {
            var          x       = db.PlayerChampionships.Where(pc => pc.ChampionshipId == chmp.Id);
            PlayerData[] players = new PlayerData[x.Count()];
            int          i       = 0;
            foreach (var pc in x)
            {
                players[i++] = getPlayerDataById(pc.PlayerId, db);
            }
            channel.sendPlayers(players, "Q");
        }
    }
    //获取单词数据
    public static void GetWordInfo(MonoBehaviour behaviour, ICallBack callBack)
    {
        var wordInfoRelativePath = LevelDict.Instance.GetLevelInfo(LevelDict.Instance.SelectLevel).wordInfoPath;
        var wordInfoPath         = RemotePath + wordInfoRelativePath;

        behaviour.StartCoroutine(GetInfo(wordInfoPath, callBack));
    }
示例#14
0
    public void addPlayer(ICallBack player, int dim)
    {
        if (this.dim != dim)
        {
            player.gameError("Something went wrong...\nDifferenet dimensions of board");
            return;
        }

        if (player1 == null)
        {
            player.gameError("Something went wrong...\nPlayer1 is not found");
            return;
        }

        if (player == player1)
        {
            player.gameError("Something went wrong...\nTrying to add the same player");
            return;
        }

        if (player1 != null && singlePlayer)
        {
            player.gameError("Something went wrong...\nThe game is already occupied by single player game");
            return;
        }

        waitingForPlayer2 = false;
        player2 = player;
        game.Player2 = server.getPlayerData(player).Id;
    }
示例#15
0
 public void DuplexOneWay(string msg)
 {
     Interlocked.Increment(ref msgCount);
     Log.Trace("Received Message # " + msgCount + "  Message == " + msg);
     callback = OperationContext.Current.GetCallbackChannel <ICallBack>();
     callback.CallBackMethod("Received Message # " + msgCount);
 }
示例#16
0
 public void DuplexOneWay(string msg)
 {
     Interlocked.Increment(ref msgCount);
     Log.Trace("Received Message # " + msgCount + "  Message == " + msg);
     callback = OperationContext.Current.GetCallbackChannel<ICallBack>();
     callback.CallBackMethod("Received Message # " + msgCount);
 }
示例#17
0
    /* delete the specific championship from database */
    public void deleteChampionship(ChampionshipData chmp)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        using (var db = new TTTDataClassesDataContext())
        {
            using (SqlConnection con = new SqlConnection(db.Connection.ConnectionString))
            {
                try
                {
                    bool success = deleteChampionshipDependencies(chmp.Id, db, con);

                    if (!success)
                    {
                        throw new Exception();
                    }

                    string     sql = string.Format("delete from Championships where Id={0}", chmp.Id);;
                    SqlCommand cmd = new SqlCommand(sql, con);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

                    channel.updateSuccess();
                }
                catch (Exception)
                {
                    channel.updateError("Some error occured while deleting from database");
                }
            }
        }
    }
示例#18
0
        public void DownFile(string FileName)
        {
            ICallBack  callback   = OperationContext.Current.GetCallbackChannel <ICallBack>();
            FileStream fs         = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            CustomFile customFile = new CustomFile(callback, fs, FileName);

            fs.BeginRead(customFile.CurrentByte, 0, customFile.MaxLength, (AsyncCallback)DownFileCallBack, customFile);
        }
示例#19
0
        //public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> TestFunction1Completed;

        public void TestMethod3()
        {
            Thread.Sleep(6000);

            ICallBack callBack = OperationContext.Current.GetCallbackChannel <ICallBack>();

            callBack.NotifyClient("TestMethod3 wurde erfolgreich ausgeführt...");
        }
示例#20
0
        /// <summary>
        /// Инициализировать нового пользователя
        /// </summary>
        /// <param name="UserInterface">Интерфейс для взаимодействия с пользователем</param>
        /// <param name="UserRole">Роль пользователя в системе</param>
        /// <returns>Новый пользователь системы</returns>
        public static User InstanceUser(ICallBack UserInterface, Role UserRole)
        {
            User user = new User();

            user.Role      = UserRole;
            user.Interface = UserInterface;

            return(user);
        }
示例#21
0
        public void DisplayName(string name)
        {
            string result = string.Format("书籍名称:{0},时间:{1}", name, DateTime.Now.ToString());

            Console.WriteLine(result + "\r\n");
            ICallBack callback = OperationContext.Current.GetCallbackChannel <ICallBack>();

            callback.DisplayResult(name);
        }
示例#22
0
        /// <summary>
        /// 完成计算,然后去回调
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void Plus(int x, int y)
        {
            int result = x + y;

            Thread.Sleep(2000);
            ICallBack callBack = OperationContext.Current.GetCallbackChannel <ICallBack>();

            callBack.Show(x, y, result);
        }
示例#23
0
        public void SendToAll(string name, string msg)
        {
            ICallBack callback = OperationContext.Current.GetCallbackChannel <ICallBack>();

            //Task.Factory.StartNew(new Action(() =>
            //{

            //}));
            callback.Show();
        }
示例#24
0
    /* inform the server that a player left the game */
    public void playerExitGame()
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (players_boards.ContainsKey(channel))
        {
            players_boards[channel].playerExit(channel);
            players_boards.Remove(channel);
        }
    }
示例#25
0
 public static void CallBackEvents(this ICallBack callbackable, Widget widget)
 {
     if (callbackable != null)
     {
         callbackable.CallBack.Message      += (title, message) => MessageDialog.ShowMessage(widget.ParentWindow, title, message);
         callbackable.CallBack.Warning      += (title, message) => MessageDialog.ShowWarning(widget.ParentWindow, title, message);
         callbackable.CallBack.Error        += (title, message) => MessageDialog.ShowError(widget.ParentWindow, title, message);
         callbackable.CallBack.Confirmation += (title, message) => MessageDialog.Confirm(widget.ParentWindow, title, message, Command.Yes);
     }
 }
示例#26
0
    /* request all championships from database for a client query */
    public async void getAllChampionships(int playerId, string caller, bool delay)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (delay)
        {
            await Task <int> .Factory.StartNew(sleep);
        }

        channel.sendChampionships(getAllChampionships(playerId), caller);
    }
示例#27
0
    /* request all users from database */
    public async void getAllUsers(string caller, bool delay)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (delay)
        {
            await Task <int> .Factory.StartNew(sleep);
        }

        channel.sendPlayers(getAllPlayersFromDB(), caller);
    }
示例#28
0
 private Board tryFindOpponent(int dim, ICallBack player)
 {
     foreach (var b in boards)
     {
         if (b != null && !b.isGameEnded() && dim == b.getDimension() && b.isWaitingForPlayer2())
         {
             return(b);
         }
     }
     return(null);
 }
示例#29
0
 /* get player data of the requesting player */
 public PlayerData getPlayerData(ICallBack channel)
 {
     if (players.ContainsKey(channel))
     {
         return(players[channel]);
     }
     else
     {
         return(null);
     }
 }
示例#30
0
    /* request all games from database for a client query */
    public async void getAllGames(bool withPlayersNames, int playerId, string caller, bool delay)
    {
        ICallBack channel = OperationContext.Current.GetCallbackChannel <ICallBack>();

        if (delay)
        {
            await Task <int> .Factory.StartNew(sleep);
        }

        channel.sendGames(getAllGamesFromDB(withPlayersNames, playerId), caller);
    }
        /// <summary>
        /// Print all the integers between a lowerBound and and upperBound (inclusive).
        /// Except, print "Fizz" when the integer is evenly divisible by 3,
        /// print "Buzz" when the integer is evenly divisible by 5;
        /// print "FizzBUzz" when the integer is evenly divisible by both
        /// Return the results, one number/string at a time, through a generic callBack method
        /// </summary>
        /// <param name="lowerBound">Start counting at this integer</param>
        /// <param name="upperBound">Stop counting at this integer</param>
        /// <param name="callBack">Invoke the CallBack method of this class to collect each integer/String</param>
        public static void CountUp(int lowerBound, int upperBound, ICallBack callBack)
        {
            List <KeyValuePair <int, String> > patternList = new List <KeyValuePair <int, string> >()
            {
                //new KeyValuePair<int, String>(0,"Zero"),
                //new KeyValuePair<int, String>(-10,"Negative"),
                new KeyValuePair <int, String>(3, "Fizz"),
                new KeyValuePair <int, String>(5, "Buzz"),
            };

            CountUp(lowerBound, upperBound, callBack, patternList);
        }
 //获取用户数据
 public static void GetUserInfo(MonoBehaviour behaviour, ICallBack callBack)
 {
     if (GeneralUtils.IsStringEmpty(Token))
     {
         BackHandler._instance.GoToLogin();
     }
     else
     {
         var userInfoUrl = GetUserInfoPath + "?token=" + Token;
         behaviour.StartCoroutine(GetInfo(userInfoUrl, callBack));
     }
 }
示例#33
0
        public Pusher(HttpListenerContext context,ICallBack callBack)
        {
            User	= context.User;
            request	= context.Request;
            response	= context.Response;
            if(request.Url.Port != 8888 && request.Headers["X-FORWARDED-PROTO"] != Uri.UriSchemeHttps)
            {
                var builder	= new UriBuilder(request.Url) { Scheme	= Uri.UriSchemeHttps };
                var uriComponentsWithoutPort	= UriComponents.AbsoluteUri & ~UriComponents.Port;

                response.RedirectLocation	= builder.Uri.GetComponents(uriComponentsWithoutPort,UriFormat.Unescaped);
                response.StatusCode	= (int)HttpStatusCode.Moved;
            }
            else callBack.Prepare(request,response);
        }
示例#34
0
    public Board(int dim, bool singlePlayer, ICallBack player, TTT server)
    {
        this.dim = dim;
        this.singlePlayer = singlePlayer;
        this.server = server;
        initBoard();
        moveCount = 0;
        gameEnded = false;
        player1 = player;
        if (singlePlayer)
            rand = new Random();

        game = new Game();
        game.BoardSize = dim;
        game.Player1 = server.getPlayerData(player).Id;
        game.StartTime = DateTime.Now;
        game.Moves = "";                        // simple array

        if (singlePlayer)
            game.Player2 = 1;

        waitingForPlayer2 = !singlePlayer;
    }
示例#35
0
 private char getToken(ICallBack player)
 {
     if (player == player1)
         return 'X';
     else if (player == player2)
         return 'O';
     else
         return 'E';     // error
 }
示例#36
0
 public void playerExit(ICallBack player)
 {
     if (!gameEnded)
     {
         if (!singlePlayer)
         {
             ICallBack op = getOpponent(player);
             if (op != null)
                 op.gameEnded("Opponent left the game..");
         }
         endGame();
     }
 }
示例#37
0
 private Board tryFindOpponent(int dim, ICallBack player)
 {
     foreach (var b in boards)
     {
         if (b != null && !b.isGameEnded() && dim == b.getDimension() && b.isWaitingForPlayer2())
             return b;
     }
     return null;
 }
示例#38
0
 /* get player data of the requesting player */
 public PlayerData getPlayerData(ICallBack channel)
 {
     if (players.ContainsKey(channel))
         return players[channel];
     else
         return null;
 }
示例#39
0
        /// <summary>
        /// Инициализировать нового пользователя
        /// </summary>
        /// <param name="UserInterface">Интерфейс для взаимодействия с пользователем</param>
        /// <param name="UserRole">Роль пользователя в системе</param>
        /// <returns>Новый пользователь системы</returns>
        public static User InstanceUser(ICallBack UserInterface, Role UserRole)
        {
            User user = new User();

            user.Role = UserRole;
            user.Interface = UserInterface;

            return user;
        }
示例#40
0
    public void playerPressed(ICallBack player, int row, int col)
    {
        char token = getToken(player);
        if (token == 'E')
        {
            player.gameError("Something went wrong...\nPlayer is not found");
            return;
        }

        if (isPressed(row, col))
        {
            player.gameError("Something went wrong...\nCell already pressed");
            return;
        }

        board[row, col] = token;
        addGameMove(row, col);
        moveCount++;

        ICallBack opponent = getOpponent(player);   // if singleplayer it will be null

        if (!singlePlayer)
        {
            if (opponent != null)
                opponent.opponentPressed(row, col);
            else
            {
                player.gameError("Something went wrong...\nOpponent is not found");
                return;
            }
        }

        if (checkWinning(token))
        {
            player.gameEnded("You won!");
            if (!singlePlayer && opponent != null)
                opponent.gameEnded("You lose..");
            game.Winner = server.getPlayerData(player).Id;
            endGame();
        }
        else if (isBoardFull())
        {
            player.gameEnded("It's a tie..");
            if (!singlePlayer && opponent != null)
                opponent.gameEnded("It's a tie..");
            endGame();
        }
        else
        {
            if (singlePlayer)
            {
                Task t = Task.Run(() => { computerMove(player); });
            }
            else
            {
                if (opponent != null)
                    opponent.playerTurn();
            }
        }
    }
示例#41
0
    private void computerMove(ICallBack player)
    {
        Thread.Sleep(1000);

        int row = -1, col = -1;

        do
        {
            row = rand.Next(0, dim);
            col = rand.Next(0, dim);

        } while (isPressed(row, col));

        board[row, col] = 'O';
        addGameMove(row, col);
        moveCount++;
        player.opponentPressed(row, col);

        if (checkWinning('O'))
        {
            player.gameEnded("You lose..");
            game.Winner = 1;
            endGame();
        }
        else if (isBoardFull())
        {
            player.gameEnded("It's a tie..");
            endGame();
        }
        else
            player.playerTurn();
    }
示例#42
0
    private ICallBack getOpponent(ICallBack player)
    {
        if (singlePlayer)
            return null;

        if (player == player1)
            return player2;
        else if (player == player2)
            return player1;
        else
            return null;
    }