示例#1
0
            public async Task ReturnsResultOfCallingExecutorIfAllPhasesSucceed()
            {
                // Arrange
                TestableEdgeApplication app = CreateEdgeApp(null);

                IFileInfo testFile = app.TestFileSystem.AddTestFile("Bar.cshtml", "Flarg");

                Type compiled = typeof(RazorApplicationTests);
                var  page     = new Mock <IRazorPage>();
                var  resp     = new RazorResponse(TestData.CreateCallParams(path: "/Bar"))
                {
                    StatusCode   = 418,
                    ReasonPhrase = "I'm a teapot"
                };

                app.MockCompilationManager
                .Setup(c => c.Compile(testFile, It.IsAny <ITrace>()))
                .Returns(Task.FromResult(CompilationResult.Successful(null, compiled, Enumerable.Empty <CompilationMessage>())));
                app.MockActivator
                .Setup(a => a.ActivatePage(compiled, It.IsAny <ITrace>()))
                .Returns(ActivationResult.Successful(page.Object));
                app.MockExecutor
                .Setup(e => e.Execute(page.Object, It.IsAny <IDictionary <string, object> >(), It.IsAny <ITrace>()))
                .Returns(Task.FromResult <object>(null));

                // Act
                await app.Invoke(TestData.CreateCallParams(path: "/Bar"));

                // Assert
                Assert.Equal(418, resp.StatusCode);
                Assert.Equal("I'm a teapot", resp.ReasonPhrase);
            }
示例#2
0
            public async Task ThrowsActivationExceptionIfActivationFails()
            {
                // Arrange
                TestableEdgeApplication app = CreateEdgeApp(null);

                IFileInfo testFile = app.TestFileSystem.AddTestFile("Bar.cshtml", "Flarg");

                Type compiled = typeof(RazorApplicationTests);

                app.MockCompilationManager
                .Setup(c => c.Compile(testFile, It.IsAny <ITrace>()))
                .Returns(Task.FromResult(CompilationResult.Successful(null, compiled, Enumerable.Empty <CompilationMessage>())));
                app.MockActivator
                .Setup(a => a.ActivatePage(compiled, It.IsAny <ITrace>()))
                .Returns(ActivationResult.Failed());

                // Act
                ActivationFailedException ex = await AssertEx.Throws <ActivationFailedException>(async() => await app.Invoke(TestData.CreateCallParams(path: "/Bar")));

                // Assert
                Assert.Equal(
                    String.Format(Resources.ActivationFailedException_DefaultMessage, compiled.AssemblyQualifiedName),
                    ex.Message);
                Assert.Equal(
                    compiled,
                    ex.AttemptedToActivate);
            }
示例#3
0
        public async Task <ActivationResult> ActivateMinerAsync(string connectionId, long minerId, MinerStatus status, IPAddress address)
        {
            await ActiveMinersLock.WaitAsync();

            try
            {
                var activation = new MinerActivation(connectionId, address, status);
                if (!ActiveMiners.TryAdd(minerId, activation))
                {
                    return(ActivationResult.FromFailed("There already is a active connection from this miner!"));
                }

                Logger.LogInformation($"Activated miner [{minerId}]");
                long userId = await UserService.GetOwnerIdFromMinerId(minerId);

                return(ActivationResult.FromSuccess(userId));
            }
            catch (Exception ex)
            {
                Logger.LogCritical(ex, "There was an exception while activating a miner!");
                return(ActivationResult.FromFailed("An unknown error occurred!"));
            }
            finally
            {
                ActiveMinersLock.Release();
            }
        }
示例#4
0
        private string SerializeAndEncryptResult(ActivationResult result, KeyPair keyPair)
        {
            string serializedResult = _serializationProvider.Serialize(result);
            string encryptedResult  = _asymmetricEncryptionProvider.EncryptPrivate(serializedResult, keyPair);

            return(encryptedResult);
        }
示例#5
0
        public ActivationResult Activate(string code)
        {
            ActivationResult activationResult = new ActivationResult();

            activationResult.IsSuccess = false;

            if (!string.IsNullOrEmpty(code))
            {
                SqlCommand cmd = null;
                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    con.Open();
                    string sql = "update [User] set IsActive=1 where vCode=@code";
                    cmd = new SqlCommand(sql, con);
                    cmd.Parameters.AddWithValue("@code", code);
                    if (cmd.ExecuteNonQuery() == 1)
                    {
                        activationResult.IsSuccess = true;
                        string Quary = "select vFirstName from [User] where vCode=@code";
                        cmd = new SqlCommand(Quary, con);
                        cmd.Parameters.AddWithValue("@code", code);
                        SqlDataReader sdr = cmd.ExecuteReader();
                        if (sdr.Read())
                        {
                            activationResult.FirstName = (string)sdr.GetValue(0);
                        }
                        sdr.Close();
                    }
                    cmd.Dispose();
                    con.Close();
                }
            }

            return(activationResult);
        }
            public void ReturnsFailedResultIfTypeIsConstructableButNotEdgePage()
            {
                // Arrange
                var activator = new DefaultPageActivator();

                // Act
                ActivationResult result = activator.ActivatePage(typeof(object), NullTrace.Instance);

                // Assert
                Assert.False(result.Success);
                Assert.Null(result.Page);
            }
            public void ReturnsFailedResultIfTypeIsEdgePageButHasNoPublicParameterlessCtor()
            {
                // Arrange
                var activator = new DefaultPageActivator();

                // Act
                ActivationResult result = activator.ActivatePage(typeof(NoParameterlessConstructorEdgePage), NullTrace.Instance);

                // Assert
                Assert.False(result.Success);
                Assert.Null(result.Page);
            }
示例#8
0
        /// <summary>
        /// Активирует пользователя.
        /// </summary>
        /// <param name="userDomainID">Код пользователя.</param>
        /// <param name="clientIdentifier">Идентификатор клиента.</param>
        /// <returns>Результат активации.</returns>
        public ActivationResult Activate(Guid userDomainID, string clientIdentifier)
        {
            var result = new ActivationResult();

            _logger.InfoFormat("Начало активации домена пользователя {0}:{1}", userDomainID, clientIdentifier);

            try
            {
                var domain = RemontinkaServer.Instance.DataStore.GetUserDomain(userDomainID);
                if (domain == null)
                {
                    _logger.ErrorFormat("Домен не найден {0}:{1}", userDomainID, clientIdentifier);
                    result.Description = "Отказано в активации";
                    return(result);
                }

                if (domain.IsActive)
                {
                    _logger.InfoFormat("Домен уже активирован {0}:{1}", userDomainID, clientIdentifier);
                    result.Description = "Успех";
                    result.Success     = true;
                    return(result);
                } //if

                RemontinkaServer.Instance.DataStore.Deploy(userDomainID);
                result.Success     = true;
                result.Description = "Успех";
                result.Login       = domain.UserLogin;
                _logger.InfoFormat("Домен успешно активирован {0}:{1}", userDomainID, clientIdentifier);
            }
            catch (Exception ex)
            {
                result.Description = "Ошибка";
                var innerException = string.Empty;

                if (ex.InnerException != null)
                {
                    innerException = ex.InnerException.Message;
                }

                _logger.ErrorFormat("Во время активации домена пользователя {0}, произошла ошибка {1}, {2} {3} {4}",
                                    userDomainID, ex.Message, innerException, ex.GetType(), ex.StackTrace);

                //Если домен активировали ранее
                var domain = RemontinkaServer.Instance.DataStore.GetUserDomain(userDomainID);
                if (domain != null && domain.IsActive)
                {
                    result.Description = "Успех";
                    result.Success     = true;
                }
            }
            return(result);
        }
            public void ReturnsSuccessfulResultIfTypeIsPubliclyConstructableEdgePage()
            {
                // Arrange
                var activator = new DefaultPageActivator();

                // Act
                ActivationResult result = activator.ActivatePage(typeof(ConstructableEdgePage), NullTrace.Instance);

                // Assert
                Assert.True(result.Success);
                Assert.IsType <ConstructableEdgePage>(result.Page);
            }
示例#10
0
        public string ActivateLicense(string token, string payload)
        {
            ActivationResult result  = new ActivationResult();
            KeyPair          keyPair = _keyPairService.GetClientKeyPair();

            Debug.WriteLine(keyPair.PrivateKey);
            Debug.WriteLine(keyPair.PublicKey);

            if (!_controlService.ValidateClientToken(token))
            {
                result.WasOperationSuccessful = false;
                result.WasRequestValid        = false;
                result.ActivationSuccessful   = false;

                return(SerializeAndEncryptResult(result, keyPair));
            }

            result.WasRequestValid = true;

            result.ServiceId = _masterService.GetMasterServiceData().ServiceId;

            string decryptedPayload = _asymmetricEncryptionProvider.DecryptPublic(payload, keyPair);
            LicenseActivationPayload activationPayload = _serializationProvider.Deserialize <LicenseActivationPayload>(decryptedPayload);

            if (!_keyService.AuthorizeLicenseForActivation(activationPayload.LicenseKey, activationPayload.ServiceLicense, activationPayload.HardwareFingerprint))
            {
                result.WasOperationSuccessful = false;
                result.ActivationSuccessful   = false;
            }
            else
            {
                Guid?activiationtoken = _keyService.ActivateLicenseKey(activationPayload.LicenseKey, activationPayload.Token,
                                                                       activationPayload.ServiceLicense, activationPayload.HardwareFingerprint);
                if (activiationtoken.HasValue)
                {
                    _activationLogService.LogActiviation(activationPayload.LicenseKey, ActivationResults.Success, GetIpAddress());

                    result.ActivationToken        = activiationtoken;
                    result.WasOperationSuccessful = true;
                    result.ActivationSuccessful   = true;
                }
                else
                {
                    _activationLogService.LogActiviation(activationPayload.LicenseKey, ActivationResults.ActivationFailure, GetIpAddress());

                    result.WasOperationSuccessful = false;
                    result.ActivationSuccessful   = false;
                }
            }

            return(SerializeAndEncryptResult(result, keyPair));
        }
示例#11
0
        public AccountCreationModel(string anActivationKey, string aName, string aPassword, string aPassword2)
        {
            myActivationKey = anActivationKey;

            using (SqlConnection con = getCon())
            {
                if (FindUser(con, anActivationKey) && LoadUser(con) && UpdateUser(con, aName, aPassword, aPassword2))
                {
                    myResult = ActivationResult.ACTIVATIONSUCCESS;
                }
                else
                {
                    myResult = ActivationResult.ACTIVATIONFAILED;
                }
            }
        }
示例#12
0
        public AccountCreationModel(string anAccountActivationKey)
        {
            myActivationKey = anAccountActivationKey;

            using (SqlConnection con = getCon())
            {
                if (anAccountActivationKey != null && FindUser(con, anAccountActivationKey) && LoadUser(con))
                {
                    myResult = ActivationResult.FOUND;
                }
                else
                {
                    myResult = ActivationResult.NOTFOUND;
                }
            }
        }
        public ActivationResult ActivateLicense(string url, string token, EncryptionInfo encryptionInfo,
                                                LicenseActivationPayload payload, ClientLicense clientLicense)
        {
            ActivationServiceClient client = ActivationServiceClientCreator(url);

            string encryptedToken    = _symmetricEncryptionProvider.Encrypt(token, encryptionInfo);
            string serializedPayload = _objectSerializationProvider.Serialize(payload);
            string encryptedData     = _asymmetricEncryptionProvider.EncryptPrivate(serializedPayload, clientLicense.ServicesKeys);


            string serviceResult = client.ActivateLicense(encryptedToken, encryptedData);
            string result        = _asymmetricEncryptionProvider.DecryptPublic(serviceResult, clientLicense.ServicesKeys);

            ActivationResult activationResult = _objectSerializationProvider.Deserialize <ActivationResult>(result);

            return(activationResult);
        }
            public void should_not_have_been_successful()
            {
                string clientToken = packingService.PackToken(service.GetClientToken());

                LicenseActivationPayload payload = new LicenseActivationPayload();

                payload.LicenseKey     = "999-999999-9999";
                payload.ServiceLicense = new ServiceLicense(servicesService.CreateTestClientLicense(service));

                string encryptedToken    = symmetricEncryptionProvider.Encrypt(clientToken, servicesService.GetClientStandardEncryptionInfo(service));
                string serializedPayload = objectSerializationProvider.Serialize(payload);
                string encryptedData     = asymmetricEncryptionProvider.EncryptPrivate(serializedPayload, servicesService.CreateTestClientLicense(service).ServicesKeys);


                string           encryptedResult = activationService.ActivateLicense(encryptedToken, encryptedData);
                string           decryptedResult = asymmetricEncryptionProvider.DecryptPublic(encryptedResult, servicesService.CreateTestClientLicense(service).ServicesKeys);
                ActivationResult result          = objectSerializationProvider.Deserialize <ActivationResult>(decryptedResult);

                Assert.IsFalse(result.WasOperationSuccessful);
            }
        private async Task <int> ExecuteCommand(ActivationResult activation)
        {
            // inject host services

            activation.Command.SetInterface(_interface);

            // execute

            var method = activation.ResolvedCommand.CommandInfo.Type.GetMethod("Execute");

            var args = new object[]
            {
                new CommandExecutionContext
                {
                    CancellationToken = _currentCancellationTokenSource.Token,
                    CommandRegistry   = _registry
                }
            };

            try
            {
                return(activation.ResolvedCommand.CommandInfo.IsExecuteAsync
                    ? await(Task <int>) method.Invoke(activation.Command, args)
                    : await Task.Factory.StartNew(() => (int)method.Invoke(activation.Command, args)));
            }
            catch (Exception ex)
            {
                _interface.WriterCollection.Error.WriteLine($"Command {activation.ResolvedCommand.CommandInfo.Type.FullName} has thrown an unhandled exception");

                while (ex != null)
                {
                    _interface.WriterCollection.Error.WriteLine($"{ex.Message} --");
                    _interface.WriterCollection.Error.WriteLine(ex.StackTrace);
                    ex = ex.InnerException;
                }

                return((int)ExecutionReturnCode.ExecutionError);
            }
        }
        public ClientLicense ActivateLicenseKey(string licenseKey, Guid?token, bool isOffline, ClientLicense scutexLicense, string hardwareFingerprint)
        {
            /* This method used to live in the LicenseKeyService class, where it should be
             *  but because of a circular reference in the WebServicesProvider and the ServicesLibrary
             *  project requiring the LicenseKeyService to valid keys it was causing and error and had
             *  to be moved here.
             */

            if (_licenseKeyService.ValidateLicenseKey(licenseKey, scutexLicense, true))
            {
                Token t = new Token();
                t.Data      = scutexLicense.ServiceToken;
                t.Timestamp = DateTime.Now;

                string packedToken = _packingService.PackToken(t);

                LicenseActivationPayload payload = new LicenseActivationPayload();
                payload.LicenseKey     = licenseKey;
                payload.ServiceLicense = new ServiceLicense(scutexLicense);
                payload.Token          = token;

                if (!String.IsNullOrEmpty(hardwareFingerprint))
                {
                    payload.HardwareFingerprint = hardwareFingerprint;
                }

                if (!isOffline)
                {
                    ActivationResult result = _licenseActiviationProvider.ActivateLicense(scutexLicense.ServiceAddress, packedToken,
                                                                                          GetClientStandardEncryptionInfo(scutexLicense),
                                                                                          payload, scutexLicense);

                    if (result != null && result.WasRequestValid && result.ActivationSuccessful)
                    {
                        scutexLicense.IsLicensed              = true;
                        scutexLicense.IsActivated             = true;
                        scutexLicense.ActivatingServiceId     = result.ServiceId;
                        scutexLicense.ActivationToken         = result.ActivationToken;
                        scutexLicense.ActivatedOn             = DateTime.Now;
                        scutexLicense.ActivationLastCheckedOn = DateTime.Now;

                        _clientLicenseService.SaveClientLicense(scutexLicense);

                        return(scutexLicense);
                    }
                }
                else
                {
                    scutexLicense.IsLicensed              = true;
                    scutexLicense.IsActivated             = false;
                    scutexLicense.ActivatingServiceId     = null;
                    scutexLicense.ActivationToken         = null;
                    scutexLicense.ActivatedOn             = DateTime.Now;
                    scutexLicense.ActivationLastCheckedOn = DateTime.Now;

                    _clientLicenseService.SaveClientLicense(scutexLicense);

                    return(scutexLicense);
                }
            }

            return(scutexLicense);
        }
示例#17
0
        public bool TestService(Service service)
        {
            string clientToken = _packingService.PackToken(service.GetClientToken());
            string mgmtToken   = _packingService.PackToken(service.GetManagementToken());

            LicenseActivationPayload payload = new LicenseActivationPayload();

            payload.ServiceLicense = new ServiceLicense(CreateTestClientLicense(service));

            LicenseGenerationOptions options = new LicenseGenerationOptions();

            options.LicenseKeyType = LicenseKeyTypes.MultiUser;

            payload.LicenseKey = _licenseKeyService.GenerateLicenseKey(null, payload.ServiceLicense, options);

            SetupTestProductResult result = _serviceStatusProvider.SetupTestProduct(service.ManagementUrl, mgmtToken, payload.LicenseKey, GetManagementStandardEncryptionInfo(service));

            if (result.WasRequestValid == false)
            {
                return(false);
            }

            if (result.WasOperationSuccessful == false)
            {
                return(false);
            }

            ActivationResult activationResult1 = _licenseActiviationProvider.ActivateLicense(service.ClientUrl, clientToken, GetClientStandardEncryptionInfo(service),
                                                                                             payload, CreateTestClientLicense(service));

            ActivationResult activationResult2 = _licenseActiviationProvider.ActivateLicense(service.ClientUrl, clientToken, GetClientStandardEncryptionInfo(service),
                                                                                             payload, CreateTestClientLicense(service));

            ActivationResult activationResult3 = _licenseActiviationProvider.ActivateLicense(service.ClientUrl, clientToken, GetClientStandardEncryptionInfo(service),
                                                                                             payload, CreateTestClientLicense(service));

            if (activationResult1.WasRequestValid == false || activationResult1.ActivationSuccessful == false)
            {
                return(false);
            }

            if (activationResult2.WasRequestValid == false || activationResult2.ActivationSuccessful == false)
            {
                return(false);
            }

            if (activationResult3.WasRequestValid == false || activationResult3.ActivationSuccessful == true)
            {
                return(false);
            }

            SetupTestProductResult cleanUpResult = _serviceStatusProvider.CleanUpTestProductData(service.ManagementUrl, mgmtToken,
                                                                                                 GetManagementStandardEncryptionInfo
                                                                                                     (service));

            if (cleanUpResult.WasOperationSuccessful == false)
            {
                return(false);
            }

            return(true);
        }
示例#18
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            var    sw    = new Stopwatch();
            var    req   = new RazorRequest(environment);
            ITrace trace = Tracer.ForRequest(req);

            using (trace.StartTrace())
            {
                trace.WriteLine("Received {0} {1}", req.Method, req.Path);

                if (!IsUnder(VirtualRoot, req.Path))
                {
                    // Not for us!
                    await NextApp(environment);

                    return;
                }

                // Step 1. Route the request to a file
                RouteResult routed = await Router.Route(req, trace);

                if (!routed.Success)
                {
                    // Also not for us!
                    await NextApp(environment);

                    return;
                }
                trace.WriteLine("Router: '{0}' ==> '{1}'::'{2}'", req.Path, routed.File.Name, routed.PathInfo);

                // Step 2. Use the compilation manager to get the file's compiled type
                sw.Start();
                CompilationResult compiled = await CompilationManager.Compile(routed.File, trace);

                sw.Stop();
                if (!compiled.Success)
                {
                    trace.WriteLine("Compiler: '{0}' FAILED", routed.File.Name);
                    throw new CompilationFailedException(compiled.Messages, compiled.GeneratedCode);
                }
                if (compiled.SatisfiedFromCache)
                {
                    trace.WriteLine("Retrieved compiled code from cache in {0}ms", sw.ElapsedMilliseconds);
                }
                else
                {
                    trace.WriteLine("Compiled '{0}' in {1}ms", routed.File.Name, sw.ElapsedMilliseconds);
                }
                sw.Reset();

                // Step 3. Construct an instance using the PageActivator
                Type             type      = compiled.GetCompiledType();
                ActivationResult activated = Activator.ActivatePage(type, trace);
                if (!activated.Success)
                {
                    trace.WriteLine("Activator: '{0}' FAILED", type.FullName);
                    throw new ActivationFailedException(type);
                }
                trace.WriteLine("Activator: '{0}' SUCCESS", type.FullName);

                // Step 4. Execute the activated instance!
                await Executor.Execute(activated.Page, environment, trace);
            }
        }
示例#19
0
        private ActivationResult Activate(SceneArgs args, NavigationOption option = NavigationOption.None)
        {
            var result = new ActivationResult();

            if (this._currentScene != null)
            {
                var currentUnityScene = SceneManager.GetSceneByName(this._currentScene.SceneArgs.SceneName);
                if (!currentUnityScene.isLoaded)
                {
                    this._logger.LogException(new NavigationFailureException("無効なシーンが設定されています"));
                    return(null);
                }

                result.DisactivatedScene = this._currentScene;
            }

            // シーンマネージャの方から次のSceneを取得
            var nextUnityScene = SceneManager.GetSceneByName(args.SceneName);

            if (!nextUnityScene.isLoaded)
            {
                this._logger.LogException(new NavigationFailureException("シーンの読み込みに失敗しました"));
                return(null);
            }
            if (nextUnityScene.rootCount != 1)
            {
                this._logger.LogException(new NavigationFailureException("シーンのRootObjectが複数あります"));
                return(null);
            }

            // SceneからINavigatableSceneを取得
            var rootObjects = nextUnityScene.GetRootGameObjects();

            if (rootObjects.Length == 0)
            {
                this._logger.LogException(new NavigationFailureException("RootObjectが存在しません"));
            }
            if (rootObjects.Length > 1)
            {
                this._logger.LogException(new NavigationFailureException("RootObjectが複数あります"));
            }

            var containsCanvases = rootObjects[0].GetComponentsInChildren <Canvas>();

            if (containsCanvases.Length == 0)
            {
                this._logger.LogException(new NavigationFailureException("Canvasが見つかりませんでした"));
                return(null);
            }

            var sceneBases = rootObjects[0].GetComponents <SceneBase>();

            if (sceneBases.Length == 0)
            {
                this._logger.LogException(new NavigationFailureException("SceneBaseコンポーネントがRootObjectに存在しません"));
                return(null);
            }
            if (sceneBases.Length > 1)
            {
                this._logger.LogException(new NavigationFailureException("SceneBaseコンポーネントが複数あります"));
                return(null);
            }

            // 進む場合、新しいシーンは非表示にしておく
            if (!option.HasFlag(NavigationOption.Pop))
            {
                rootObjects[0].SetActive(false);
            }

            // 次のシーンに諸々引数を渡す
            var nextScene = sceneBases[0] as INavigatableScene;

            nextScene.SetRootCanvas(containsCanvases[0]);
            nextScene.SceneArgs = args;
            nextScene.SetNavigator(this);
            nextScene.SetLogger(this._logger);
            if (this._currentScene != null)
            {
                nextScene.SetParentSceneArgs(this._currentScene.SceneArgs);
            }

            // 進む場合、ソートを整える
            if (!option.HasFlag(NavigationOption.Pop))
            {
                if (this._currentScene != null)
                {
                    nextScene.RootCanvas.sortingOrder = this._canvasOrderArranger.GetOrder(this._currentScene.RootCanvas.sortingOrder, option);
                }
                else
                {
                    nextScene.RootCanvas.sortingOrder = this._canvasOrderArranger.InitialOrder;
                }
            }

            // 次のシーンにnextSceneを設定
            this._currentScene = result.ActivatedScene = nextScene;

            // TransitionModeの調整
            if (option.HasFlag(NavigationOption.Override))
            {
                result.TransitionMode |= TransitionMode.KeepCurrent;
            }
            if (option.HasFlag(NavigationOption.Pop))
            {
                result.TransitionMode |= TransitionMode.Back;
            }

            return(result);
        }