Пример #1
0
        public void InvokeWithStateCopiesStateToHubProxy()
        {
            var hubResult = new HubResult
            {
                State = new Dictionary <string, JToken>
                {
                    { "state", JToken.FromObject(1) }
                }
            };

            var connection = new Mock <IHubConnection>();

            connection.Setup(m => m.RegisterCallback(It.IsAny <Action <HubResult> >()))
            .Callback <Action <HubResult> >(callback =>
            {
                callback(hubResult);
            });

            connection.Setup(m => m.Send(It.IsAny <string>()))
            .Returns(TaskAsyncHelper.Empty);

            connection.SetupGet(x => x.JsonSerializer).Returns(new JsonSerializer());

            var hubProxy = new HubProxy(connection.Object, "foo");

            hubProxy.Invoke("Anything").Wait();

            Assert.Equal(1, hubProxy["state"]);
        }
Пример #2
0
        public void InvokeReturnsHubsResult()
        {
            var hubResult = new HubResult
            {
                Result = "Something"
            };

            var connection = new Mock <IHubConnection>();

            connection.Setup(m => m.RegisterCallback(It.IsAny <Action <HubResult> >()))
            .Callback <Action <HubResult> >(callback =>
            {
                callback(hubResult);
            });

            connection.Setup(m => m.Send(It.IsAny <string>()))
            .Returns(TaskAsyncHelper.Empty);

            connection.SetupGet(x => x.JsonSerializer).Returns(new JsonSerializer());

            var hubProxy = new HubProxy(connection.Object, "foo");

            var result = hubProxy.Invoke <object>("Anything").Result;

            Assert.Equal(result, "Something");
        }
Пример #3
0
        public void InvokeWithErrorInHubResultReturnsFaultedTask()
        {
            var hubResult = new HubResult
            {
                Error = "This in an error"
            };

            var connection = new Mock <IHubConnection>();

            connection.Setup(m => m.RegisterCallback(It.IsAny <Action <HubResult> >()))
            .Callback <Action <HubResult> >(callback =>
            {
                callback(hubResult);
            });

            connection.Setup(m => m.Send(It.IsAny <string>()))
            .Returns(TaskAsyncHelper.Empty);

            connection.SetupGet(x => x.JsonSerializer).Returns(new JsonSerializer());

            var hubProxy = new HubProxy(connection.Object, "foo");

            TestUtilities.AssertAggregateException(() => hubProxy.Invoke("Invoke").Wait(),
                                                   "This in an error");
        }
Пример #4
0
        public HubResult GetState(string gameId)
        {
            _gameService.Games.TryGetValue(gameId, out IGame game);
            if (game == null)
            {
                return(HubResult.Fail("Game not found."));
            }

            Clients.User(Context.UserIdentifier).SendAsync("upd-state", game.GameStatePacket());

            return(HubResult.Ok());
        }
Пример #5
0
        private void ProcessResult(TrackingDictionary state, object result, HubRequest request, Exception error)
        {
            var hubResult = new HubResult
            {
                State  = state.GetChanges(),
                Result = result,
                Id     = request.Id,
                Error  = error != null?error.GetBaseException().Message : null
            };

            Send(hubResult);
        }
Пример #6
0
        public void InvokeWithErrorInHubResultReturnsFaultedTask()
        {
            var result = new HubResult<object>
            {
                Error = "This in an error"
            };

            var connection = new Mock<SignalR.Client.IConnection>();
            connection.Setup(m => m.Send<HubResult<object>>(It.IsAny<string>()))
                      .Returns(TaskAsyncHelper.FromResult(result));

            var hubProxy = new HubProxy(connection.Object, "foo");

            AssertAggregateException(() => hubProxy.Invoke("Invoke").Wait(),
                                     "This in an error");
        }
Пример #7
0
        private void ClearInvocationCallbacks(string error)
        {
            var result = new HubResult();

            result.Error = error;

            lock (_callbacks)
            {
                foreach (var callback in _callbacks.Values)
                {
                    callback(result);
                }

                _callbacks.Clear();
            }
        }
Пример #8
0
        public void InvokeWithErrorInHubResultReturnsFaultedTask()
        {
            var result = new HubResult <object>
            {
                Error = "This in an error"
            };

            var connection = new Mock <SignalR.Client.IConnection>();

            connection.Setup(m => m.Send <HubResult <object> >(It.IsAny <string>()))
            .Returns(TaskAsyncHelper.FromResult(result));

            var hubProxy = new HubProxy(connection.Object, "foo");

            AssertAggregateException(() => hubProxy.Invoke("Invoke").Wait(),
                                     "This in an error");
        }
Пример #9
0
        public void InvokeReturnsHubsResult()
        {
            var hubResult = new HubResult<object>
            {
                Result = "Something"
            };

            var connection = new Mock<SignalR.Client.IConnection>();
            connection.Setup(m => m.Send<HubResult<object>>(It.IsAny<string>()))
                      .Returns(TaskAsyncHelper.FromResult(hubResult));

            var hubProxy = new HubProxy(connection.Object, "foo");

            var result = hubProxy.Invoke<object>("Anything").Result;

            Assert.Equal(result, "Something");
        }
Пример #10
0
        public void InvokeReturnsHubsResult()
        {
            var hubResult = new HubResult <object>
            {
                Result = "Something"
            };

            var connection = new Mock <SignalR.Client.IConnection>();

            connection.Setup(m => m.Send <HubResult <object> >(It.IsAny <string>()))
            .Returns(TaskAsyncHelper.FromResult(hubResult));

            var hubProxy = new HubProxy(connection.Object, "foo");

            var result = hubProxy.Invoke <object>("Anything").Result;

            Assert.Equal(result, "Something");
        }
Пример #11
0
        public async Task <HubResult> JoinGame(string gameId)
        {
            if (_activeUserService.HasGameConnections(Context.UserIdentifier))
            {
                return(HubResult.Fail("User already in game."));
            }

            _gameService.Games.TryGetValue(gameId, out IGame game);
            var user = await _userManager.FindByIdAsync(Context.UserIdentifier);

            if (game == null || user == null)
            {
                return(HubResult.Fail("Game not found."));
            }

            game.AddPlayer(user);
            return(HubResult.Ok(game.Id));
        }
Пример #12
0
        public async Task <HubResult> CreateGame(MafiaCreateGameOptions options)
        {
            if (_activeUserService.HasGameConnections(Context.UserIdentifier))
            {
                return(HubResult.Fail("User already in game."));
            }

            var user = await _userManager.FindByIdAsync(Context.UserIdentifier);

            var game = _mafiaGameBuilder
                       .CreateGame()
                       .WithName(options.Name)
                       .HasMaxPlayers(options.MaxPlayers)
                       .ContainsPlayer(user)
                       .Build();

            _gameService.AddGame(game);

            return(HubResult.Ok(game.Id));
        }
Пример #13
0
        public void InvokeWithStateCopiesStateToHubProxy()
        {
            var result = new HubResult<object>
            {
                State = new Dictionary<string, object>
                {
                    { "state", 1 }
                }
            };

            var connection = new Mock<SignalR.Client.IConnection>();
            connection.Setup(m => m.Send<HubResult<object>>(It.IsAny<string>()))
                      .Returns(TaskAsyncHelper.FromResult(result));

            var hubProxy = new HubProxy(connection.Object, "foo");

            hubProxy.Invoke("Anything").Wait();

            Assert.Equal(1, hubProxy["state"]);
        }
Пример #14
0
        public void InvokeWithStateCopiesStateToHubProxy()
        {
            var result = new HubResult <object>
            {
                State = new Dictionary <string, object>
                {
                    { "state", 1 }
                }
            };

            var connection = new Mock <SignalR.Client.IConnection>();

            connection.Setup(m => m.Send <HubResult <object> >(It.IsAny <string>()))
            .Returns(TaskAsyncHelper.FromResult(result));

            var hubProxy = new HubProxy(connection.Object, "foo");

            hubProxy.Invoke("Anything").Wait();

            Assert.Equal(1, hubProxy["state"]);
        }
Пример #15
0
        public HubResult GetGames()
        {
            var activeGames = _gameService.Games
                              .Select(d => d.Value)
                              .Where(g =>
                                     g is MafiaGame game &&
                                     game.State == MafiaGameState.Created &&
                                     game.ContainsPlayer(Context.UserIdentifier)
                                     )
                              .Select(g => (g as MafiaGame).ConnectInfo())
                              .ToList();

            var avalibleGames = _gameService.Games
                                .Select(d => d.Value)
                                .Where(g => g is MafiaGame game &&
                                       game.State == MafiaGameState.Created &&
                                       !game.ContainsPlayer(Context.UserIdentifier))
                                .Select(g => (g as MafiaGame).ConnectInfo())
                                .ToList();

            return(HubResult.Ok(new { active = activeGames, avalible = avalibleGames }));
        }
Пример #16
0
        private Task ProcessResult(TrackingDictionary state, object result, HubRequest request, Exception error)
        {
            var hubResult = new HubResult
            {
                State = state.GetChanges(),
                Result = result,
                Id = request.Id,
                Error = error != null ? error.GetBaseException().Message : null
            };

            return Send(hubResult);
        }
        protected override void OnMessageReceived(JSONNode message)
        {
            // We have to handle progress updates first in order to ensure old clients that receive
            // progress updates enter the return value branch and then no-op when they can't find
            // the callback in the map (because the message["I"[ value will not be a valid callback ID)
            if (message["P"] != null)
            {
                var result = HubResult.FromJson(message);
                Action <HubResult> callback;

                lock (_callbacks)
                {
                    if (!_callbacks.TryGetValue(result.ProgressUpdate.Id, out callback))
                    {
                        Trace(TraceLevels.Messages, "Callback with id " + result.ProgressUpdate.Id + " not found!");
                    }
                }

                callback?.Invoke(result);
            }
            else if (message["I"] != null)
            {
                var result = HubResult.FromJson(message);
                Action <HubResult> callback;

                lock (_callbacks)
                {
                    if (_callbacks.TryGetValue(result.Id, out callback))
                    {
                        _callbacks.Remove(result.Id);
                    }
                    else
                    {
                        Trace(TraceLevels.Messages, "Callback with id " + result.Id + " not found!");
                    }
                }

                if (callback != null)
                {
                    callback(result);
                }
            }
            else
            {
                var      invocation = HubInvocation.FromJson(message);
                HubProxy hubProxy;
                if (_hubs.TryGetValue(invocation.Hub, out hubProxy))
                {
                    if (invocation.State != null)
                    {
                        foreach (var state in invocation.State)
                        {
                            hubProxy[state.Key] = state.Value;
                        }
                    }

                    hubProxy.InvokeEvent(invocation.Method, invocation.Args);
                }

                base.OnMessageReceived(message);
            }
        }
Пример #18
0
        public void UploadToHub(Report report, HubSettings settings, Connection socketConnection)
        {
            var reportName = report?.Name ?? null;

            if (String.IsNullOrEmpty(reportName))
            {
                throw new Exception("The report filename is empty.");
            }

            if (String.IsNullOrEmpty(settings.Owner))
            {
                throw new Exception("No owner for shared content found.");
            }

            //Delete reports from hub before uploaded!
            if (settings.Mode == DistributeMode.DELETEALLFIRST)
            {
                DeleteReportsFromHub(report, settings, socketConnection);
            }

            foreach (var reportPath in report.Paths)
            {
                try
                {
                    var fileData    = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath));
                    var contentName = GetContentName(reportName, fileData);

                    // Copy with report name - Important for other delivery options.
                    var uploadCopyReportPath = Path.Combine(Path.GetDirectoryName(reportPath), $"{reportName}{Path.GetExtension(reportPath)}");
                    File.Copy(reportPath, uploadCopyReportPath, true);

                    if (settings.Mode == DistributeMode.OVERRIDE ||
                        settings.Mode == DistributeMode.CREATEONLY)
                    {
                        var uploadResult = new HubResult()
                        {
                            ReportName = reportName,
                        };

                        HubInfo hubInfo   = null;
                        Guid?   hubUserId = null;

                        var qrsApi = GetQrsApiConnection(socketConnection);
                        logger.Debug($"Use the following Qlik user '{settings.Owner}'...");
                        var hubUser = new DomainUser(settings.Owner, true);
                        var filter  = $"userId eq '{hubUser.UserId}' and userDirectory eq '{hubUser.UserDirectory}'";
                        logger.Debug($"Use Filter '{filter}'...");
                        var result = qrsApi.SendRequestAsync("user", HttpMethod.Get, null, filter).Result;
                        logger.Debug($"QRS Result for user: '******'");
                        if (result == null || result == "[]")
                        {
                            throw new Exception($"Qlik user {settings.Owner} was not found or session not connected (QRS).");
                        }
                        var userObject = JArray.Parse(result);
                        if (userObject.Count > 1)
                        {
                            throw new Exception($"Too many User found. {result}");
                        }
                        else if (userObject.Count == 1)
                        {
                            hubUserId = new Guid(userObject.First()["id"].ToString());
                        }
                        logger.Debug($"hubUser id is '{hubUserId}'.");

                        var sharedContent = GetSharedContentFromUser(contentName, hubUser, qrsApi);
                        if (sharedContent == null)
                        {
                            var createRequest = new HubCreateRequest()
                            {
                                Name        = contentName,
                                ReportType  = settings.SharedContentType,
                                Description = "Created by Analytics Gate",
                                Tags        = new List <Tag>()
                                {
                                    new Tag()
                                    {
                                        Name         = "SER",
                                        CreatedDate  = DateTime.Now,
                                        ModifiedDate = DateTime.Now
                                    }
                                },
                                Data = new ContentData()
                                {
                                    ContentType  = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}",
                                    ExternalPath = Path.GetFileName(uploadCopyReportPath),
                                    FileData     = fileData.DownloadData,
                                }
                            };

                            logger.Debug($"Create request '{JsonConvert.SerializeObject(createRequest)}'");
                            hubInfo = qrsApi.CreateSharedContentAsync(createRequest).Result;
                            logger.Debug($"Create response '{JsonConvert.SerializeObject(hubInfo)}'");
                        }
                        else
                        {
                            if (settings.Mode == DistributeMode.OVERRIDE)
                            {
                                var tag = sharedContent?.Tags?.FirstOrDefault(t => t.Name == "SER") ?? null;
                                if (tag != null)
                                {
                                    tag.CreatedDate  = DateTime.Now;
                                    tag.ModifiedDate = DateTime.Now;
                                }
                                var updateRequest = new HubUpdateRequest()
                                {
                                    Info = sharedContent,
                                    Data = new ContentData()
                                    {
                                        ContentType  = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}",
                                        ExternalPath = Path.GetFileName(uploadCopyReportPath),
                                        FileData     = fileData.DownloadData,
                                    }
                                };

                                logger.Debug($"Update request '{JsonConvert.SerializeObject(updateRequest)}'");
                                hubInfo = qrsApi.UpdateSharedContentAsync(updateRequest).Result;
                                logger.Debug($"Update response '{JsonConvert.SerializeObject(hubInfo)}'");
                            }
                            else
                            {
                                throw new Exception($"The shared content '{contentName}' already exist.");
                            }
                        }

                        if (hubUserId != null)
                        {
                            //change shared content owner
                            logger.Debug($"Change shared content owner '{hubUserId}' (User: '******').");
                            var newHubInfo = new HubInfo()
                            {
                                Id    = hubInfo.Id,
                                Type  = settings.SharedContentType,
                                Owner = new Owner()
                                {
                                    Id            = hubUserId.ToString(),
                                    UserId        = hubUser.UserId,
                                    UserDirectory = hubUser.UserDirectory,
                                    Name          = hubUser.UserId,
                                }
                            };

                            var changeRequest = new HubUpdateRequest()
                            {
                                Info = newHubInfo,
                            };
                            logger.Debug($"Update Owner request '{JsonConvert.SerializeObject(changeRequest)}'");
                            var ownerResult = qrsApi.UpdateSharedContentAsync(changeRequest).Result;
                            logger.Debug($"Update Owner response '{JsonConvert.SerializeObject(ownerResult)}'");
                        }

                        // Get fresh shared content infos
                        var filename = Path.GetFileName(uploadCopyReportPath);
                        filename = filename.Replace("+", " ");
                        hubInfo  = GetSharedContentFromUser(contentName, hubUser, qrsApi);
                        logger.Debug("Get shared content link.");
                        var link = hubInfo?.References?.FirstOrDefault(r => r.LogicalPath.Contains($"/{filename}"))?.ExternalPath ?? null;
                        if (link == null)
                        {
                            throw new Exception($"The download link is empty. Please check the security rules. (Name: {filename} - References: {hubInfo?.References?.Count}) - User: {hubUser}.");
                        }

                        Results.Add(new HubResult()
                        {
                            Success     = true,
                            ReportState = GetFormatedState(),
                            TaskName    = JobResult.TaskName,
                            Message     = "Upload to the hub was successful.",
                            Link        = link,
                            ReportName  = contentName,
                            FullLink    = GetFullLink(qrsApi.ConnectUri, link)
                        });
                    }
                    else
                    {
                        throw new Exception($"Unknown hub mode {settings.Mode}");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "The delivery via 'Hub' failed.");
                    JobResult.Exception = ReportException.GetException(ex);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new HubResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        TaskName    = JobResult.TaskName,
                        Message     = ex.Message
                    });
                }
                finally
                {
                    socketConnection.IsFree = true;
                }
            }
        }