public Subscriber(string nickname)
 {
     this.nickname = nickname;
     this.callback = OperationContext.
                     Current.
                     GetCallbackChannel <IServiceCallback>();
 }
Пример #2
0
        public async Task Send(Message message)
        {
            IServiceCallback callback =
                OperationContext.Current.GetCallbackChannel <IServiceCallback>();
            IChannel channel = (IChannel)callback;

            WcfClientContext context;

            if (!callbacks.TryGetValue(channel, out context))
            {
                context            = new WcfClientContext(callback);
                callbacks[channel] = context;

                context.Closed += delegate
                {
                    callbacks.TryRemove(channel, out context);
                };

                ClientForm clientForm = new ClientForm(context);
                clientForm.Show();
            }

            byte[] body = new byte[] { };
            if (!message.IsEmpty)
            {
                body = message.GetBody <byte[]>();
            }

            WebSocketMessageProperty property =
                (WebSocketMessageProperty)message.Properties[webSocketMessageProperty];

            await context.Receive(body, body.Length, property == null?
                                  WebSocketMessageType.Binary : property.MessageType, true)
            .ConfigureAwait(true);
        }
Пример #3
0
        /// <summary>
        /// Register
        /// The client sends a request to register themselves
        /// with a username and password. If they are already registered
        /// the CustomValidation tries to validate their credentials
        /// </summary>
        /// <param name="username">(string) user name</param>
        /// <param name="password">(string) password</param>
        /// <returns>(boolean) if successful, false otherwise</returns>
        public bool Register(string username, string password)
        {
            // Registration Success Flag
            bool registered = false;

            // Obtain callback for the client
            IServiceCallback callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();

            // First Verify User Does Not Already Exist in Registration
            if (!(RegisteredUsers.Any(x => x.UserName == username)))
            {
                // User is Not Registered, Register User

                // Create new user
                User user = new User(username, password, callback);

                /// Add to Registered Users
                RegisteredUsers.Add(user);

                // Set Return Value
                registered = true;

                Console.WriteLine($"User {username} registered...");
            }
            else
            {
                DuplicateUserFault fault = new DuplicateUserFault()
                {
                    Reason = "User '" + username + "' already registered."
                };
                throw new FaultException <DuplicateUserFault>(fault, fault.Reason);
            }

            return(registered);
        } // end of Register method
        public void pickUp(int gameId)
        {
            Game g = listOfGames.ElementAt(gameId - 1);

            g.PickedUp = true;
            g.Players[g.HitsIndex].CardsInHand += g.NrOfCardsOnTable;
            g.NrOfCardsOnTable = 0;
            setNextMoveAndHitId(gameId);

            for (int i = 0; i < g.Count; i++)
            {
                Subscriber       s  = getSubscriberById(g.Players[i].Id);
                IServiceCallback cb = s.callback;
                cb.OnPickUp(gameId, g.Players[g.HitsIndex].Id);
            }
            if (!isGameOver(gameId))
            {
                for (int i = 0; i < g.Count; i++)
                {
                    Subscriber       s  = getSubscriberById(g.Players[i].Id);
                    IServiceCallback cb = s.callback;
                    cb.OnRoundOver(gameId, g.Players[g.MovesIndex].Id, g.Players[g.HitsIndex].Id);
                }
            }
            else
            {
                for (int i = 0; i < g.Count; i++)
                {
                    Subscriber       s  = getSubscriberById(g.Players[i].Id);
                    IServiceCallback cb = s.callback;
                    cb.OnGameOver(gameId, g.Players[g.HitsIndex].Id);
                }
            }
        }
Пример #5
0
 /// <summary>
 /// Sets initial properties
 /// </summary>
 /// <param name="callbackInstance"></param>
 /// <param name="connectionFailed"></param>
 public static void SetClient(IServiceCallback callbackInstance, Action connectionFailed)
 {
     lazy = new Lazy <ServiceClient>
                (() => new ServiceClient(new InstanceContext(callbackInstance)));
     proxyLazy = new Lazy <Proxy>(() => new Proxy());
     connectionFailedAction = connectionFailed;
 }
        public void dealRound(int gameId)
        {
            Game       g  = listOfGames.ElementAt(gameId - 1);
            Subscriber sb = GetMe();

            Trace.WriteLine("SEVICE: dealRound called by " + sb.nickname);
            if (sb.Id == g.Players[0].Id)
            {
                for (int i = 0; i < g.Count; i++)
                {
                    List <ServiceCard> cards = new List <ServiceCard>();
                    int         index        = (g.Count - g.MovesIndex - i) % g.Count;
                    ServiceUser u            = g.Players[index];
                    while (u.CardsInHand < 6 && g.TopCardIndex >= 0)
                    {
                        cards.Add(g.Deck[g.TopCardIndex]);
                        g.TopCardIndex -= 1;
                        u.CardsInHand  += 1;
                    }
                    Subscriber       s  = getSubscriberById(u.Id);
                    IServiceCallback cb = s.callback;
                    Trace.WriteLine("SEVICE: calling onDeal after dealRound ");
                    Trace.WriteLine("SEVICE: calling to " + s.nickname + " with id " + g.Players[index].Id);
                    Trace.WriteLine("SEVICE: sending " + cards.Count + " cards");
                    cb.OnDeal(cards.ToArray(), g.Deck[0], g.Players[index].Id, gameId);
                }
            }
        }
        public void dealCards(int gameid)
        {
            Subscriber me = GetMe();

            Trace.WriteLine("SERVICE: Dealing card !!!");
            Game g         = listOfGames.ElementAt(gameid - 1);
            int  deckIndex = g.Deck.Length - 1;

            for (int i = 0; i < g.Count; i++)
            {
                ServiceCard[] cards = new ServiceCard[6];
                for (int j = 0; j < 6; j++)
                {
                    cards[j]  = g.Deck[deckIndex];
                    deckIndex = deckIndex - 1;
                }
                ServiceUser p = g.Players[i];
                p.CardsInHand = 6;
                Subscriber       s  = getSubscriberById(p.Id);
                IServiceCallback cb = s.callback;
                Trace.WriteLine("SERVICE: Calling callback ");
                Trace.WriteLine("SERVICE: Calling player " + s.nickname);
                Trace.WriteLine("SERVICE: Subscribers " + subscrbers.Count);
                cb.OnDeal(cards, g.Deck[0], g.Players[i].Id, g.Id);
                Trace.WriteLine("SERVICE: Calling back done!");
            }
            g.TopCardIndex = deckIndex;
            Trace.WriteLine("SERVICE: deal done!");
        }
Пример #8
0
 public WorkflowInstanceManager(IServiceCallback progressCallback, Func <Exception, string> errorFormatter)
 {
     _progressTrackingParticipant = new ProgressTrackingParticipant(errorFormatter, OnWorkflowInstanceRemoved)
     {
         ProgressObserver = progressCallback
     };
 }
Пример #9
0
        private Object thisLock = new Object(); // https://docs.microsoft.com/fr-fr/dotnet/csharp/language-reference/keywords/lock-statement

        public void StartSession(Client client)
        {
            Console.WriteLine("{0} try to start a session", client.Name);

            this._callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();
            this._client   = client;

            lock (thisLock)
            {
                this._clients.Add(client);

                ConnectionEvent    += ConnectionHandler;
                DisconnectionEvent += DisconnectionHandler;
                MessageEvent       += MessageHandler;

                // All clients are informed of a new client's connection
                var args = new ConnectionEventArgs()
                {
                    Client = this._client
                };
                ConnectionEvent(this, args);

                OperationContext.Current.Channel.Closing += new EventHandler(Channel_Closing);
            }

            Console.WriteLine("{0} is connected", this._client.Name);
        }
        public void notifyHitMade(int gameId, ServiceCard movedCard)
        {
            Trace.WriteLine("SERVICE: notify hit made");

            Game g = listOfGames.ElementAt(gameId - 1);

            g.Players[g.HitsIndex].CardsInHand -= 1;
            g.NrOfCardsOnTable += 1;
            Trace.WriteLine("SERVICE: cards on table " + g.NrOfCardsOnTable);
            if (g.Players[g.HitsIndex].CardsInHand == 0 && g.TopCardIndex <= 0)
            {
                g.Players[g.HitsIndex].Finished = true;
                if (isGameOver(gameId))
                {
                    for (int i = 0; i < g.Count; i++)
                    {
                        int looser = getNextActivePlayerIndex(g, g.HitsIndex);

                        Subscriber       s  = getSubscriberById(g.Players[i].Id);
                        IServiceCallback cb = s.callback;
                        cb.OnGameOver(gameId, g.Players[looser].Id);
                    }

                    return;
                }
                else
                {
                    for (int i = 0; i < g.Count; i++)
                    {
                        Subscriber       s  = getSubscriberById(g.Players[i].Id);
                        IServiceCallback cb = s.callback;
                        cb.OnPlayerFinished(gameId, g.Players[g.HitsIndex].Id);
                    }
                }
            }
            if (g.NrOfCardsOnTable == 12)
            {
                setNextMoveAndHitId(gameId);
                for (int i = 0; i < g.Count; i++)
                {
                    Subscriber       s  = getSubscriberById(g.Players[i].Id);
                    IServiceCallback cb = s.callback;
                    Trace.WriteLine("SERVICE: calling round over");
                    Trace.WriteLine("SERVICE: hit index" + g.HitsIndex + " moveIndex " + g.MovesIndex);
                    cb.OnHitMade(movedCard, gameId, g.Players[g.HitsIndex].Id);
                    cb.OnRoundOver(gameId, g.Players[g.MovesIndex].Id, g.Players[g.HitsIndex].Id);
                }
            }
            else
            {
                for (int i = 0; i < g.Count; i++)
                {
                    Subscriber       s  = getSubscriberById(g.Players[i].Id);
                    IServiceCallback cb = s.callback;
                    cb.OnHitMade(movedCard, gameId, g.Players[g.HitsIndex].Id);
                }
            }
        }
Пример #11
0
 public void Connect(User user)
 {
     callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();
     if (callback != null)
     {
         clients.Add(user.UserId, callback);
         users.Add(user);
         clients?.ToList().ForEach(client => client.Value.UserConnected(users));
         Debug.WriteLine($"{user.Name} just connected");
     }
 }
Пример #12
0
        private TimerEx GetTimer(long timeLeft, IServiceCallback callback)
        {
            TimerEx timerEx = new TimerEx();

            timerEx.Interval = 1000;
            timerEx.Elapsed += TimerExOnElapsed;
            timerEx.Id       = Guid.NewGuid().ToString();
            timerEx.TimeLeft = timeLeft;
            timerEx.Callback = callback;

            return(timerEx);
        }
Пример #13
0
        public void NewClientConnects()
        {
            string id = Guid.NewGuid().ToString();

            IServiceCallback callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();
            bool             isAdding = _callbackClientList.TryAdd(id, callback);

            if (isAdding)
            {
                callback.SetUserId(id);
            }
        }
Пример #14
0
        public void Login(int id, string userName)
        {
            // throw new NotImplementedException();
            OperationContext context  = OperationContext.Current;
            IServiceCallback callback = context.GetCallbackChannel <IServiceCallback>();
            MyUser           newUser  = new MyUser(userName, callback);

            User tmp = null;
            //数据库实例
            MyDbEntities myDbEntities = new MyDbEntities();
            //选中这一条数据
            var q = from p in myDbEntities.User
                    where p.Name == userName
                    select p;

            tmp            = q.FirstOrDefault();
            newUser.Acount = tmp.Acount;
            newUser.Avart  = tmp.Avart;
            newUser.Grade  = tmp.Grade;
            newUser.Name   = tmp.Name;
            newUser.Room   = tmp.Room;
            newUser.Score  = tmp.Score;
            newUser.Sign   = tmp.Sign;
            newUser.id     = id;

            CC.Users.Add(newUser);
            List <Userdata> userdatas = new List <Userdata>();

            foreach (var item in CC.Users)
            {
                if (item.id == id)
                {
                    Userdata t = new Userdata();
                    t.Acount = item.Acount;
                    t.Avart  = item.Avart;
                    t.Grade  = item.Grade;
                    t.Name   = item.Name;
                    t.Room   = item.Room;
                    t.Score  = item.Score;
                    t.Sign   = item.Sign;
                    userdatas.Add(t);
                }
            }
            foreach (var item in CC.Users)
            {
                if (item.id == id)
                {
                    item.callback.ShowLogin(userName);
                    item.callback.ShowInfo(userdatas);
                }
            }
        }
Пример #15
0
        public void Login(string userName)
        {
            // throw new NotImplementedException();
            OperationContext context  = OperationContext.Current;
            IServiceCallback callback = context.GetCallbackChannel <IServiceCallback>();
            MyUser           newUser  = new MyUser(userName, callback);

            CC.Users.Add(newUser);
            foreach (var user in CC.Users)
            {
                user.callback.ShowLogin(userName);
            }
        }
Пример #16
0
        public void RegisterForGame(string playerName)
        {
            Guid guid = Guid.NewGuid();

            players.Add(guid, new Player(playerName, 1000));
            IServiceCallback callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();

            callbacksHandler.Add(guid, callback);
            callbacksHandler.SendMessageToPlayer(guid, $"Registered for next Game: {guid} {playerName}");
            if (players.Count >= 2)
            {
                Play();
            }
        }
Пример #17
0
        public void OpenSession()
        {
            Console.WriteLine("> Session opened at {0}", DateTime.Now);
            Callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();

            SendData();

            ClientCount++;


            //Timer = new Timer(1000);
            //Timer.Elapsed += OnTimerElapsed;
            //Timer.Enabled = true;
        }
        /// <summary>
        /// Sends card to the game. Severely unreasonable approach
        /// </summary>
        /// <param name="cardMoved">card moved</param>
        /// <param name="playerId">playet that made the move</param>
        /// <param name="gameId">game in view</param>
        public void notifyMove(ServiceCard cardMoved, long playerId, int gameId)
        {
            Game        g      = listOfGames.ElementAt(gameId - 1);
            ServiceUser player = getUserById(gameId, playerId);

            player.CardsInHand -= 1;
            g.NrOfCardsOnTable += 1;

            if (player.CardsInHand == 0 && g.TopCardIndex <= 0)
            {
                player.Finished = true;

                if (isGameOver(gameId))
                {
                    for (int i = 0; i < g.Count; i++)
                    {
                        ServiceUser      p  = g.Players[i];
                        Subscriber       s  = getSubscriberById(p.Id);
                        IServiceCallback cb = s.callback;

                        cb.OnGameOver(gameId, g.Players[g.HitsIndex].Id);
                        Trace.WriteLine("SERVICE: Calling back to notify Game Over!");
                    }

                    return;
                }
                else
                {
                    for (int i = 0; i < g.Count; i++)
                    {
                        ServiceUser      p  = g.Players[i];
                        Subscriber       s  = getSubscriberById(p.Id);
                        IServiceCallback cb = s.callback;

                        cb.OnPlayerFinished(gameId, playerId);
                        Trace.WriteLine("SERVICE: Calling back to notify player finished!");
                    }
                }
            }
            for (int i = 0; i < g.Count; i++)
            {
                ServiceUser      p  = g.Players[i];
                Subscriber       s  = getSubscriberById(p.Id);
                IServiceCallback cb = s.callback;

                cb.OnNotifyMove(cardMoved, gameId, playerId, g.Players[g.HitsIndex].Id);//seepärast peakski teenusele lisaks olema back endis veel üks klass
                Trace.WriteLine("SERVICE: Calling back to notify move done!");
            }
        }
Пример #19
0
        public void Connect(Machine mac)
        {
            try
            {
                IServiceCallback EventDataChanged = OperationContext.Current.GetCallbackChannel <IServiceCallback>();
                eventLoggingMessage?.Invoke(string.Format("Added Callback Channel: {0}, IP Address: {1}.", mac.MachineName, mac.IPAddress));
                EventChannelCount?.Invoke(1, true);
                RUN_APPLICATION = true;

                ThreadPool.QueueUserWorkItem((WaitCallback) delegate
                {
                    while (RUN_APPLICATION)
                    {
                        try
                        {
                            if (EventDataChanged != null)
                            {
                                // Query the channel state. For example:-

                                var state = (EventDataChanged as IChannel).State;
                                if (state == CommunicationState.Closed || state == CommunicationState.Faulted)
                                {
                                    // Channel has closed, or has faulted...
                                    EventDataChanged = null;
                                    EventChannelCount?.Invoke(1, false);
                                }
                                else
                                {
                                    EventDataChanged?.DataTags(TagCollection.Tags);
                                }
                            }
                            Thread.Sleep(100);
                        }
                        catch (Exception ex)
                        {
                            RUN_APPLICATION = false;

                            eventLoggingMessage?.Invoke(string.Format("Removed Callback Channel: {0}, IP Address: {1}| Message Exception: {2}.", mac.MachineName, mac.IPAddress, ex.Message));

                            EventscadaException?.Invoke(this.GetType().Name, ex.Message);
                        }
                    }
                });
            }
            catch (System.Exception ex)
            {
                EventscadaException?.Invoke(this.GetType().Name, ex.Message);
            }
        }
        public void turnPage(int gameId)
        {
            // TURN PAGE ON EVERY PLAYER IN GAME
            Game g = listOfGames.ElementAt(gameId - 1);

            for (int i = 0; i < g.Count; i++)
            {
                ServiceUser      p  = g.Players[i];
                Subscriber       s  = getSubscriberById(p.Id);
                IServiceCallback cb = s.callback;

                cb.OnGameStart(gameId);
                Trace.WriteLine("SERVICE: Calling back to turn page done!");
            }
        }
Пример #21
0
 public void ClientDisconnected()
 {
     try
     {
         IServiceCallback callback = Callback;
         if (callback != null)
         {
             _clientsCallback.Remove(callback);
         }
     }
     catch (Exception)
     {
         // ignored
     }
 }
Пример #22
0
 public void NewClientConnected()
 {
     try
     {
         IServiceCallback callback = Callback;
         if (callback != null)
         {
             _clientsCallback.Add(callback);
         }
     }
     catch (Exception)
     {
         // ignored
     }
 }
Пример #23
0
        private void TeardownChannel()
        {
            if (_serviceCallbackChannel == null)
            {
                return;
            }
            try
            {
                _serviceCallbackChannel.Close();
            }
            catch {}

            _serviceCallbackChannel = null;
            _serviceCallbackProxy   = null;
        }
        /** Get the subscriber entry for method caller */
        public Subscriber GetMe()
        {
            IServiceCallback cb = OperationContext.
                                  Current.
                                  GetCallbackChannel <IServiceCallback>();

            //return subscrbers.Single(item => item.callback == cb);
            foreach (Subscriber s in subscrbers)
            {
                if (s.callback.Equals(cb))
                {
                    return(s);
                }
            }
            return(null);
        }
Пример #25
0
        public WcfClientContext(IServiceCallback callback)
        {
            this.callback = callback;

            IChannel channel = (IChannel)callback;

            channel.Faulted += delegate
            {
            };
            channel.Closed += delegate
            {
                Closed?.Invoke();
                Message = null;
                Closed  = null;
            };
        }
Пример #26
0
            public Task Initialize(IList <string> references, IList <string> imports, NuGetConfiguration nuGetConfiguration, string workingDirectory)
            {
                var scriptOptions = _scriptOptions
                                    .WithReferences(references)
                                    .WithImports(imports);

                if (nuGetConfiguration != null)
                {
                    var resolver = new NuGetScriptMetadataResolver(nuGetConfiguration, workingDirectory);
                    scriptOptions = scriptOptions.WithMetadataResolver(resolver);
                }
                _scriptOptions = scriptOptions;

                _callbackChannel = OperationContext.Current.GetCallbackChannel <IServiceCallback>();

                return(Task.CompletedTask);
            }
Пример #27
0
        public void GetListOfTests()
        {
            IServiceCallback callback = Callback;

            if (callback != null)
            {
                try
                {
                    Dictionary <string, string> tests = SendTestsListToClients();
                    Callback.SetTestList(tests);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Пример #28
0
 public bool Subscribe()
 {
     if (HasPermission(Permission.Subscribe))
     {
         //Prvo, pokupimo objekat koji se odnosi na klijenta koji poziva ovu funkciju
         ServiceCallback = OperationContext.Current.GetCallbackChannel <IServiceCallback>();
         //Zatim, kreiramo delegat na funkciju CallbackInvoker, koji poziva funkciju koja svim subscribovanim korisnicima ispisuje podatke o promeni
         DBEventHandler = new DBChangeEventHandler(CallbackInvoker);
         //...i dodajemo je u DBChangeEvent, sto je skup svih delegata koje smo kreirali, i koji ih poziva svaki put kada se desi promena; vidi pozive DBChangeEvent
         DBChangeEvent += DBEventHandler;
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #29
0
        } // end of method

        #endregion IHelloAuthenticate Implementation

        #region Methods

        /// <summary>
        /// SendMessageToUsers
        /// Sends a message to all logged in users
        /// </summary>
        /// <param name="message">(string) message to user</param>
        private void SendMessageToUsers(string message)
        {
            // Sens message for each logged in user
            foreach (User user in LoggedInUsers)
            {
                try
                {
                    IServiceCallback callback = user.Callback;
                    callback.SendClientMessage(message);
                }

                // Catches an issue with a user disconnect and logs off that user
                catch (Exception)
                {
                    // Remove the disconnected client
                    LogOff(user.UserName);
                }
            } // end of foreach
        }     // end of method
Пример #30
0
            public Task Initialize(IList <string> references, IList <string> imports, NuGetConfiguration nuGetConfiguration, string workingDirectory)
            {
                _parseOptions = new CSharpParseOptions().WithPreprocessorSymbols("__DEMO__", "__DEMO_EXPERIMENTAL__");

                var scriptOptions = _scriptOptions
                                    .WithReferences(references)
                                    .WithImports(imports);

                if (nuGetConfiguration != null)
                {
                    var resolver = new NuGetScriptMetadataResolver(nuGetConfiguration, workingDirectory);
                    scriptOptions = scriptOptions.WithMetadataResolver(resolver);
                }
                _scriptOptions = scriptOptions;

                _callbackChannel = OperationContext.Current.GetCallbackChannel <IServiceCallback>();

                return(Task.CompletedTask);
            }
 // Create new client instace.
 public ServiceInterfaceClient(
             IServiceCallback callback)
 {
     this.callback = callback;
 }
 public Subscriber(string nickname)
 {
     this.nickname = nickname;
     this.callback = OperationContext.
                         Current.
                             GetCallbackChannel<IServiceCallback>();
 }