public void Run(TextBox tb, IChecker checker, string header, IEnumerable messages)
        {
            Console.WriteLine("Running script {0}", _script);
            try
            {
                var ps = PowerShell.Create();
                ps.Runspace.SessionStateProxy.SetVariable("textbox", tb);
                ps.Runspace.SessionStateProxy.SetVariable("checker", checker);
                ps.Runspace.SessionStateProxy.SetVariable("header", header);
                ps.Runspace.SessionStateProxy.SetVariable("message", messages);
                ps.AddScript(_script);
                ps.Invoke();

                Console.WriteLine(".. done");
                _logger.Info("notified");

                if (ps.Streams.Error.Count > 0)
                {
                    _logger.Error("Count of errors: {0}", ps.Streams.Error.Count);
                    foreach (var e in ps.Streams.Error)
                    {
                        _logger.ErrorException("Exception when running PowerShell notifier", e.Exception);
                        _logger.Error(e.ErrorDetails);
                    }
                }
            }
            catch(Exception e)
            {
                _logger.ErrorException("Error when running notifier", e);
            }
        }
        public SimpleCheckController(string identifier, IChecker checker, ICollection<INotifyResultFilter> notifyResultFilters, INotifier notifier)
        {
            this.identifier = identifier;
            this.checker = checker;
            this.notifyResultFilters = notifyResultFilters;
            this.notifier = notifier;

            passedFilters = new List<INotifyResultFilter>();
        }
 private static MessageBlock GenerateMessageWhenSameLenghtButDiffContent(Stream expected, IChecker<Stream, ICheck<Stream>> checker, Stream value)
 {
     var message =
         checker.BuildMessage(
                 "The {0} doesn't have the same content as the expected one (despite the fact that they have the same Length: " +
                 value.Length + ").")
             .On(value)
             .And.Expected(expected);
     return message;
 }
        public override void SetParameter(string parameter)
        {
            var customCheckerFromCache = this.compiledCustomCheckersCache[parameter] as IChecker;
            if (customCheckerFromCache != null)
            {
                this.customChecker = customCheckerFromCache;
                return;
            }

            var codeProvider = new CSharpCodeProvider();
            var compilerParameters = new CompilerParameters { GenerateInMemory = true, };
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("OJS.Workers.Common.dll");
            var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, parameter);
            if (compilerResults.Errors.HasErrors)
            {
                var errorsStringBuilder = new StringBuilder();
                foreach (CompilerError error in compilerResults.Errors)
                {
                    errorsStringBuilder.AppendLine(error.ToString());
                }

                // TODO: Introduce class CompilerException and throw exception of this type
                throw new Exception(
                    string.Format(
                        "Could not compile checker!{0}Errors:{0}{1}",
                        Environment.NewLine,
                        errorsStringBuilder));
            }

            var assembly = compilerResults.CompiledAssembly;

            var types = assembly.GetTypes().Where(x => typeof(IChecker).IsAssignableFrom(x)).ToList();
            if (types.Count > 1)
            {
                throw new Exception("More than one implementation of OJS.Workers.Common.IChecker was found!");
            }

            var type = types.FirstOrDefault();
            if (type == null)
            {
                throw new Exception("Implementation of OJS.Workers.Common.IChecker not found!");
            }

            var instance = Activator.CreateInstance(type) as IChecker;
            if (instance == null)
            {
                throw new Exception($"Cannot create an instance of type {type.FullName}!");
            }

            this.compiledCustomCheckersCache.Set(parameter, instance, new CacheItemPolicy { SlidingExpiration = CacheDaysSlidingExpiration });
            this.customChecker = instance;
        }
 private static MessageBlock GenerateMessageWhenFullyDistinct(Stream expected, IChecker<Stream, ICheck<Stream>> checker, Stream value)
 {
     var message =
         checker.BuildMessage(
                 "The {0} doesn't have the same content as the expected one. They don't even have the same Length!")
             .On(value)
             .Comparison(string.Format("(Length: {0})", value.Length))
             .And.Expected(expected)
             .Comparison(string.Format("(Length: {0})", expected.Length));
     return message;
 }
		public Controller(ClientSetting clientSetting, IStatsCheckerFactory statsCheckerFactory, IOutputChannelFactory outputChannelFactory, IStatsTemplate template)
		{
			this.clientSetting = clientSetting;
			// If enabled then start immedially
			statsChecker = statsCheckerFactory.CreateStatsCheckerInstance(clientSetting);
			statsOutputChannels = clientSetting.Outputs.Select(output => outputChannelFactory.CreateOutputChannelInstance(output, output, template)).ToArray();

			timer = new Timer
			{
				Enabled = clientSetting.Enabled,
				Interval = clientSetting.Ping.Interval
			};

			timer.Elapsed += (sender, e) => Ping(sender, e, clientSetting.Ping);
		}
    private static void TestChecker(IChecker checker, string expectedOutput, string userOutput)
    {
        var input = "";
        var result = checker.Check(input, userOutput, expectedOutput, false);

        Console.WriteLine("Correct: " + result.IsCorrect);
        if (!result.IsCorrect)
        {
            Console.WriteLine(result.CheckerDetails.Comment);
            Console.WriteLine("User output:");
            Console.WriteLine(result.CheckerDetails.UserOutputFragment);
            Console.WriteLine("Expected output:");
            Console.WriteLine(result.CheckerDetails.ExpectedOutputFragment);
        }
    }
        protected TestResult ExecuteAndCheckTest(TestContext test, ProcessExecutionResult processExecutionResult, IChecker checker, string receivedOutput)
        {
            var testResult = new TestResult
            {
                Id = test.Id,
                TimeUsed = (int)processExecutionResult.TimeWorked.TotalMilliseconds,
                MemoryUsed = (int)processExecutionResult.MemoryUsed,
            };

            if (processExecutionResult.Type == ProcessExecutionResultType.RunTimeError)
            {
                testResult.ResultType = TestRunResultType.RunTimeError;
                testResult.ExecutionComment = processExecutionResult.ErrorOutput.MaxLength(2048); // Trimming long error texts
            }
            else if (processExecutionResult.Type == ProcessExecutionResultType.TimeLimit)
            {
                testResult.ResultType = TestRunResultType.TimeLimit;
            }
            else if (processExecutionResult.Type == ProcessExecutionResultType.MemoryLimit)
            {
                testResult.ResultType = TestRunResultType.MemoryLimit;
            }
            else if (processExecutionResult.Type == ProcessExecutionResultType.Success)
            {
                var checkerResult = checker.Check(test.Input, receivedOutput, test.Output, test.IsTrialTest);
                if (checkerResult.IsCorrect)
                {
                    testResult.ResultType = TestRunResultType.CorrectAnswer;
                }
                else
                {
                    testResult.ResultType = TestRunResultType.WrongAnswer;
                }

                // TODO: Do something with checkerResult.ResultType
                testResult.CheckerComment = checkerResult.CheckerDetails;
            }
            else
            {
                throw new ArgumentOutOfRangeException("processExecutionResult", "Invalid ProcessExecutionResultType value.");
            }

            return testResult;
        }
        protected override List<TestResult> ProcessTests(ExecutionContext executionContext, IExecutor executor, IChecker checker, string codeSavePath)
        {
            var testResults = new List<TestResult>();

            var arguments = new List<string>();
            arguments.Add(this.mochaModulePath);
            arguments.Add(codeSavePath);
            arguments.AddRange(executionContext.AdditionalCompilerArguments.Split(' '));

            foreach (var test in executionContext.Tests)
            {
                var processExecutionResult = executor.Execute(this.NodeJsExecutablePath, test.Input, executionContext.TimeLimit, executionContext.MemoryLimit, arguments);
                var mochaResult = JsonExecutionResult.Parse(processExecutionResult.ReceivedOutput);
                var testResult = this.ExecuteAndCheckTest(test, processExecutionResult, checker, mochaResult.Passed ? "yes" : string.Format("Unexpected error: {0}", mochaResult.Error));
                testResults.Add(testResult);
            }

            return testResults;
        }
Beispiel #10
0
        } // функция валидации хода

        private IChecker[][] ExecuteOperationToKill(IChecker[][] newBoardState, IChecker killer, IChecker victim, Coord coord)
        {
            if (killer.CheckPossibilityToKill(coord, gameField))
            {
                newBoardState[killer.CurrentCoord.Row][killer.CurrentCoord.Column] = null;
                killer.CurrentCoord = coord;
                newBoardState[killer.CurrentCoord.Row][killer.CurrentCoord.Column] = killer;
                newBoardState[victim.CurrentCoord.Row][victim.CurrentCoord.Column] = null;
                CheckGettingKing(killer);
            }

            return(newBoardState);
        } //виртуальное исполнение команды на убийство
Beispiel #11
0
        private void CheckKingKilling(TurnNode currentNode, Lib.PlayersSide whoseTurn, IChecker checker, int level)
        {
            int i = checker.CurrentCoord.Row;
            int j = checker.CurrentCoord.Column;

            while ((i <= 8) && (j <= 8))
            {
                if (checker.CheckPossibilityToKill(new Coord(i, j), gameField))
                {
                    currentNode.AddChild(KillingRecurcion(currentNode, whoseTurn, checker, new Coord(i, j), level));
                }
                i++;
                j++;
            }

            i = checker.CurrentCoord.Row;
            j = checker.CurrentCoord.Column;
            while ((i <= 8) && (j >= 1))
            {
                if (checker.CheckPossibilityToKill(new Coord(i, j), gameField))
                {
                    currentNode.AddChild(KillingRecurcion(currentNode, whoseTurn, checker, new Coord(i, j), level));
                }
                i++;
                j--;
            }

            i = checker.CurrentCoord.Row;
            j = checker.CurrentCoord.Column;
            while ((i >= 1) && (j <= 8))
            {
                if (checker.CheckPossibilityToKill(new Coord(i, j), gameField))
                {
                    currentNode.AddChild(KillingRecurcion(currentNode, whoseTurn, checker, new Coord(i, j), level));
                }
                i--;
                j++;
            }

            i = checker.CurrentCoord.Row;
            j = checker.CurrentCoord.Column;
            while ((i >= 1) && (j >= 1))
            {
                if (checker.CheckPossibilityToKill(new Coord(i, j), gameField))
                {
                    currentNode.AddChild(KillingRecurcion(currentNode, whoseTurn, checker, new Coord(i, j), level));
                }
                i--;
                j--;
            }
        }
Beispiel #12
0
        private TurnNode KillingRecurcion(TurnNode currentNode, Lib.PlayersSide whoseTurn, IChecker checker, Coord destination, int level)
        {
            int killingValue = (whoseTurn == Lib.PlayersSide.BLACK) ? 100 : 0;

            IChecker[][] state   = CreateStateCopy(currentNode.state);
            TurnNode     newNode = new TurnNode(state, killingValue, level);//чем больше уровень рекурсии, тем меньше

            if (checker.CurrentCoord.Row == 4 && checker.CurrentCoord.Column == 3 && level == 0)
            {
            }

            bool a = (side == Lib.PlayersSide.BLACK && checker is BlackChecker) || (side == Lib.PlayersSide.WHITE && checker is WhiteChecker);

            if (level == 0 && a)
            {
                KillingCommand command = new KillingCommand(game, checker, checker.GetVictim(destination, gameField), destination);
                newNode.turnCommand = command; //присваеваем команду на первом уровне рекурсии
                TurnNodes.Add(newNode);
            }
            state = ExecuteOperationToKill(state, state[checker.CurrentCoord.Row][checker.CurrentCoord.Column], checker.GetVictim(destination, gameField), destination);
            MakeTurnNodes(newNode, AnotherPlayer(whoseTurn), level + 1);
            return(newNode);
        }
Beispiel #13
0
 /*public User ChekReal(string userName)
  * {
  *  foreach (var user in UsersList.UsersEntityNew.UsersNew)
  *  {
  *      if (user.UserName == userName)
  *      {
  *          return user;
  *      }
  *  }
  *  return null;
  * }*/
 private string CheckValue(IChecker <User> cheker, User user, string oldValue, string newValue, string field)
 {
     //MessageBox.Show("Вход в проверки");
     return(!cheker.CheckField(user, oldValue, newValue, out string message) ? throw new Exception($"{field}: {message}") : newValue);
 }
        /// <summary>
        /// Checks that an instance is in the inheritance hierarchy of a specified type.
        /// </summary>
        /// <param name="checker">The instance to be checked.</param>
        /// <param name="expectedBaseType">The Type which is expected to be a base Type of the instance.</param>
        /// <exception cref="FluentCheckException">The instance is not in the inheritance hierarchy of the specified type.</exception>
        public static void InheritsFrom(IChecker<object, ICheck<object>> checker, Type expectedBaseType)
        {
            var instanceType = checker.Value.GetTypeWithoutThrowingException();
            if (expectedBaseType.IsAssignableFrom(instanceType))
            {
                return;
            }

            var message = checker.BuildMessage("The {0} does not have the expected inheritance.")
                             .For("expression type")
                             .On(instanceType)
                             .Label("Indeed, the {0} {1}")
                             .And.Expected(expectedBaseType)
                             .Label("is not a derived type of");
            
            throw new FluentCheckException(message.ToString());
        }
        private static string IsEmptyImpl(IChecker<string, ICheck<string>> checker, bool canBeNull, bool negated)
        {
            var checkedValue = checker.Value;
            
            // special case if checkedvalue is null
            if (checkedValue == null)
            {
                if (canBeNull != negated)
                {
                    return null;
                }

                return negated ? checker.BuildShortMessage("The {0} is null whereas it must have content.").For("string").ToString()
                    : checker.BuildShortMessage("The {0} is null instead of being empty.").For("string").ToString();
            }

            if (string.IsNullOrEmpty(checkedValue) != negated)
            {
                // success
                return null;
            }

            if (negated)
            {
                return
                    checker.BuildShortMessage("The {0} is empty, whereas it must not.")
                    .For("string")
                                 .ToString();
            }

            return
                checker.BuildMessage("The {0} is not empty or null.")
                .For("string")
                             .On(checkedValue)
                             .ToString();
        }
        private static string AssessEquals(IChecker<string, ICheck<string>> checker, object expected, bool negated, bool ignoreCase = false)
        {
            if (string.Equals(checker.Value, (string)expected, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture) != negated)
            {
                return null;
            }

            string messageText;
            if (negated)
            {
                messageText = checker.BuildShortMessage("The {0} is equal to the {1} whereas it must not.")
                                    .For("string")
                                    .Expected(expected)
                                    .Comparison("different from")
                                    .ToString();
            }
            else
            {
                // we try to refine the difference
                var expectedString = expected as string;
                var message = "The {0} is different from {1}.";
                var isCrlfAndLfDifference = false;
                var isTabAndWhiteSpaceDifference = false;
                var firstDiffPos = 0;

                // TODO: refactor to reduce method lines
                var value = checker.Value;
                if (expectedString != null && value != null)
                {
                    var firstDiff = 0;
                    var blockStart = 0;
                    var blockLen = 0;

                    var minLength = Math.Min(value.Length, expectedString.Length);

                    for (; firstDiff < minLength; firstDiff++)
                    {
                        if (value[firstDiff] != expectedString[firstDiff])
                        {
                            firstDiffPos = firstDiff;
                            isCrlfAndLfDifference = IsACRLFDifference(firstDiff, expectedString, value);
                            isTabAndWhiteSpaceDifference = IsATabAndWhiteSpaceDifference(firstDiff, expectedString, value);
                        
                            blockStart = Math.Max(0, firstDiff - 10);
                            blockLen = Math.Min(minLength - blockStart, 20);
                            break;
                        }
                    }

                    if (expectedString.Length == value.Length)
                    {
                        // same length
                        if (string.Compare(value, expectedString, StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            message = "The {0} is different from the {1} but only in case.";
                        }
                        else
                        {
                            message = "The {0} is different from the {1} but has same length.";
                        }   

                        var prefix = blockStart == 0 ? string.Empty : "...";
                        var suffix = (blockStart + blockLen) == minLength ? string.Empty : "...";
                        message += string.Format(
                                                    " At {0}, expected '{3}{1}{4}' was '{3}{2}{4}'",
                                                    firstDiff,
                                                    expectedString.Substring(blockStart, blockLen),
                                                    value.Substring(blockStart, blockLen),
                                                    prefix,
                                                    suffix);
                    }
                    else
                    {
                        if (expectedString.Length > value.Length)
                        {
                            if (expectedString.StartsWith(value, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture))
                            {
                                message = "The {0} is different from {1}, it is missing the end.";
                            }
                        }
                        else
                        {
                            if (value.StartsWith(expectedString, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture))
                            {
                                message = "The {0} is different from {1}, it contains extra text at the end.";
                            }
                        }
                    }
                }

                if (isCrlfAndLfDifference)
                {
                    value = HighlightFirstCrlfOrLfIfAny(value, firstDiffPos);
                    expectedString = HighlightFirstCrlfOrLfIfAny(expectedString, firstDiffPos);
                }

                if (isTabAndWhiteSpaceDifference)
                {
                    value = HighlightTabsIfAny(value);
                    expectedString = HighlightTabsIfAny(expectedString);    
                }

                messageText = checker.BuildMessage(message).For("string").On(value).And.Expected(expectedString).ToString();
            }

            return messageText;
        }
 public ThatTruyenHub(IChecker checker)
 {
     _checker = checker;
 }
Beispiel #18
0
        public void AddChecker(IChecker checker)
        {
            checker.AddChecker(SwitchChecker);

            this.SwitchChecker = checker;
        }
Beispiel #19
0
 protected FeatureSwitchProvider()
 {
     FeatureSwitches    = new Dictionary <string, Feature>();
     this.SwitchChecker = new StateChecker();
 }
Beispiel #20
0
 public Alarm(ISensor sensor, IChecker checker)
 {
     _sensor = sensor;
     _checker = checker;
 }
        protected virtual List <TestResult> ProcessTests(ExecutionContext executionContext, IExecutor executor, IChecker checker, string codeSavePath)
        {
            var testResults = new List <TestResult>();

            foreach (var test in executionContext.Tests)
            {
                var processExecutionResult = executor.Execute(this.NodeJsExecutablePath, test.Input, executionContext.TimeLimit, executionContext.MemoryLimit, new[] { codeSavePath });
                var testResult             = this.ExecuteAndCheckTest(test, processExecutionResult, checker, processExecutionResult.ReceivedOutput);
                testResults.Add(testResult);
            }

            return(testResults);
        }
Beispiel #22
0
 public void SetPassword(IChecker <User> check, User user, string oldPassword, string newPassword)
 {
     user.Password = CheckValue(check, user, oldPassword, newPassword, $"{user.Name}, Password");
 }
        /// <summary>
        /// Check if two collections of <see typeparamref="T" /> are equal.
        /// </summary>
        /// <remarks>
        /// The parameters are first checked for null, an exception is thrown if only one is null.
        /// Second, the cardinalities of the collections are checked if the <see cref="IEnumerable{T}" /> is
        /// also <see cref="ICollection{T}" /> which means that it supports <see cref="ICollection{T}.Count" />
        /// If these checks are passed, each item is compared in turn.
        /// </remarks>
        /// <param name="checker"></param>
        /// <param name="expected"></param>
        /// <param name="candidate"></param>
        /// <param name="objectName"></param>
        protected void Check(IChecker checker, IEnumerable expected, IEnumerable candidate, string objectName)
        {
            // Do we have two actual lists
            if (CheckNullNotNull(expected, candidate, objectName))
            {
                return;
            }

            CheckCardinality(expected, candidate, objectName);
            if (this.CompareTarget == CompareTarget.Count)
            {
                // We're done
                return;
            }

            // Ok, step both iterator togeter, will work as these are now confirmed to have the same cardinality
            var i = 0;
            var enumExpected = expected.GetEnumerator();
            var enumCandidate = candidate.GetEnumerator();
            var target = CompareTarget.Entity;
            Type type = null;

            enumExpected.Reset();
            enumCandidate.Reset();
            while (enumExpected.MoveNext())
            {
                if (type == null)
                {
                    type = enumExpected.Current.GetType();
                    if (Targeter == null)
                    {
                        throw new NotSupportedException("No ITypeCompareTargeter assigned to PropertyCheck");
                    }
                    target = Targeter.DetermineCompareTarget(type);
                }
                enumCandidate.MoveNext();
                this.Check(target, checker, enumExpected.Current, enumCandidate.Current, objectName + "[" + i++ + "]");
            }
        }
Beispiel #24
0
        private OutputParameter CheckInput(Parameter parameter, VerifyerParameter verifyerParameter)
        {
            if (verifyerParameter.Direction  == RatchetingDirections.TowardsZero)
            {
                _checker = new TowardsZeroChecker();
            }
            else
            {
                _checker = new TowardsHundredChecker();
            }
            _logProxy.LogThis(MessageImportance.Low, string.Format("Checking {0}", parameter.ParameterName));
            var par = new OutputParameter(parameter.ParameterName, "", false);

            if (Checker.CurrentValueIsWorseThanTargetValue(parameter.CurrentValue, verifyerParameter.TargetValue))
            {

                par.IsOk = false;
                par.VeriferResult = string.Format("Fail: {0} -> Current value is worse than target",
                                                  parameter.ParameterName);
                return par;
            }
            if (Checker.CurrentValueIsEqualToTargetValue(parameter.CurrentValue, verifyerParameter.TargetValue))
            {

                par.IsOk = true;
                par.VeriferResult = string.Format(
                    "Warning: {0} -> Current and Target equal - you are close to fail",
                    parameter.ParameterName);
                return par;
            }
            if (Checker.CurrentValueIsBetterThanTargetValue(parameter.CurrentValue, verifyerParameter.TargetValue) &
                !Checker.CurrentValueIsBetterThanTargetValueAndWarning(parameter.CurrentValue,
                                                                       verifyerParameter.TargetValue,
                                                                       verifyerParameter.WarningValue))
            {

                par.IsOk = true;
                par.VeriferResult = string.Format(
                    "Warning: {0} -> Current better than target but within warning - you are close to fail",
                    parameter.ParameterName);
                return par;
            }
            if (Checker.CurrentValueIsBetterThanTargetValue(parameter.CurrentValue, verifyerParameter.TargetValue) && verifyerParameter.RatchetValue > 0)
            {
                par.IsOk = true;
                par.VeriferResult = string.Format("Success: {0} -> Current is better than Target and can be ratcheted to {1}",
                                                  parameter.ParameterName,
                                                  Checker.NewRatchetValue(verifyerParameter.TargetValue,
                                                                          verifyerParameter.RatchetValue));
                return par;
            }

            if (Checker.CurrentValueIsBetterThanTargetValue(parameter.CurrentValue, verifyerParameter.TargetValue))
            {
                par.IsOk = true;
                par.VeriferResult = string.Format("Success: {0} -> Current is better than Target", parameter.ParameterName);
                return par;
            }

            par.IsOk = false;
            par.VeriferResult = "Error in verification: somehow i didn't  foresee this";
            return par;
        }
Beispiel #25
0
 public IChecker GetVictim(Coord newCoord, IChecker checker)
 {
     return(checker.GetVictim(newCoord, this));
 }
        private static string EndsWithImpl(IChecker<string, ICheck<string>> checker, string ends, bool negated)
        {
            var checkedValue = checker.Value;

            // special case if checkedvalue is null
            if (checkedValue == null)
            {
                return negated ? null : checker.BuildShortMessage("The {0} is null.").For("string").Expected(ends).Comparison("ends with").ToString();
            }

            if (checkedValue.EndsWith(ends) != negated)
            {
                // success
                return null;
            }

            if (negated)
            {
                return
                    checker.BuildMessage("The {0} ends with {1}, whereas it must not.")
                    .For("string").Expected(ends)
                                 .Comparison("does not end with")
                                 .ToString();
            }

            return
                checker.BuildMessage("The {0}'s end is different from the {1}.")
                .For("string")
                             .Expected(ends)
                             .Comparison("ends with")
                             .ToString();
        }
        public void SamrEnumerateDomainsInSamServer_SUCCESS()
        {
            HRESULT  hResult;
            IChecker PtfAssert = TestClassBase.BaseTestSite.Assert;

            Site.Log.Add(LogEntryKind.TestStep,
                         string.Format("SamrBind, Server:{0}, Domain:{1}, User:{2}, Password{3}.",
                                       _samrProtocolAdapter.pdcNetBIOSName,
                                       _samrProtocolAdapter.primaryDomainFqdn,
                                       _samrProtocolAdapter.DomainAdministratorName,
                                       _samrProtocolAdapter.DomainUserPassword));
            _samrProtocolAdapter.SamrBind(
                _samrProtocolAdapter.pdcNetBIOSName,
                _samrProtocolAdapter.primaryDomainFqdn,
                _samrProtocolAdapter.DomainAdministratorName,
                _samrProtocolAdapter.DomainUserPassword,
                false,
                true);
            Site.Log.Add(LogEntryKind.TestStep,
                         string.Format("SamrConnect5, Server:{0}, Desired Access: SAM_SERVER_ENUMERATE_DOMAINS.", _samrProtocolAdapter.PDCNetbiosName));
            hResult = (HRESULT)_samrProtocolAdapter.SamrConnect5(
                _samrProtocolAdapter.PDCNetbiosName,
                (uint)SERVER_ACCESS_MASK.SAM_SERVER_ENUMERATE_DOMAINS,
                out _serverHandle);
            PtfAssert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrConnect5 must return STATUS_SUCCESS.");
            uint?enumerationContext = 0;
            uint countReturned;
            _SAMPR_ENUMERATION_BUFFER?enumerationBuffer;

            Site.Log.Add(LogEntryKind.TestStep, "SamrEnumerateDomainsInSamServer, PreferedMaximumLength: 1024.");
            hResult = (HRESULT)SAMRProtocolAdapter.RpcAdapter.SamrEnumerateDomainsInSamServer(
                _serverHandle,
                ref enumerationContext,
                out enumerationBuffer,
                1024,
                out countReturned);
            PtfAssert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrEnumerateDomainsInSamServer must return STATUS_SUCCESS.");
            PtfAssert.AreNotEqual <uint>(0, countReturned, "The CountReturned is not zero.");
            PtfAssert.IsNotNull(enumerationBuffer, "EnumerationBuffer is not null.");
            PtfAssert.AreEqual <uint>(countReturned, enumerationBuffer.Value.EntriesRead, "Verify the EntriesRead property.");

            bool builtInDomainFound = false;
            bool accountDomainFound = false;

            foreach (var entry in enumerationBuffer.Value.Buffer)
            {
                string name = DtypUtility.ToString(entry.Name);
                if (string.Compare(name, "BUILTIN", true) == 0)
                {
                    builtInDomainFound = true;
                }
                if (string.Compare(name, _samrProtocolAdapter.primaryDomainNetBIOSName, true) == 0)
                {
                    accountDomainFound = true;
                }
                PtfAssert.AreEqual <uint>(0, entry.RelativeId, "[MS-SAMR]3.1.5.2.1 Buffer.Buffer.RelativeId is 0.");
            }
            PtfAssert.IsTrue(builtInDomainFound,
                             "[MS-SAMR]3.1.5.2.1 The server MUST enable a client to obtain a listing, without duplicates, " +
                             "of the following two values: the name attribute of the account domain object and the name" +
                             " attribute of the built-in domain object.");
            PtfAssert.IsTrue(accountDomainFound,
                             "[MS-SAMR]3.1.5.2.1 The server MUST enable a client to obtain a listing, without duplicates, " +
                             "of the following two values: the name attribute of the account domain object and the name" +
                             " attribute of the built-in domain object.");
        }
        public void AddChecker(IChecker checker)
        {
            checker.AddChecker(SwitchChecker);

            this.SwitchChecker = checker;
        }
Beispiel #29
0
        /// <summary>
        /// Check if two <see cref="IDictionary"/> are equal.
        /// </summary>
        /// <param name="checker"></param>
        /// <param name="expected"></param>
        /// <param name="candidate"></param>
        /// <param name="objectName"></param>
        protected void Check(IChecker checker, IDictionary expected, IDictionary candidate, string objectName)
        {
            // Do we have two dictionaries
            if (CheckNullNotNull(expected, candidate, objectName))
            {
                return;
            }

            var ex = new List <PropertyCheckException>();
            var sb = new StringBuilder();
            PropertyCheckException p;

            sb.AppendLine(objectName + " differences...");
            var keys = new List <object>();

            foreach (var key in expected.Keys)
            {
                // Track the processed keys
                keys.Add(key);

                // Does it exist
                if (!candidate.Contains(key))
                {
                    p = new PropertyCheckException(key.ToString(), expected[key], "null");
                    sb.AppendLine(p.Message);
                    ex.Add(p);
                }
                else
                {
                    try
                    {
                        Check(expected[key], candidate[key], key.ToString());
                    }
                    catch (PropertyCheckException pex)
                    {
                        sb.AppendLine(pex.Message);
                        ex.Add(pex);
                    }
                }
            }

            // Now do the reverse, excluding keys we've already processed
            foreach (var key in candidate.Keys)
            {
                if (keys.Contains(key))
                {
                    // Tracked it the first time around
                    continue;
                }
                p = new PropertyCheckException(key.ToString(), "null", candidate[key]);
                sb.AppendLine(p.Message);
                ex.Add(p);
            }

            if (ex.Count != 0)
            {
                p = new PropertyCheckException(objectName, sb.ToString());
                foreach (var pex in ex)
                {
                    p.Exceptions.Add(pex);
                }

                throw p;
            }
        }
 public MainForm(IChecker checker)
 {
     InitializeComponent();
     _checker = checker;
 }
        private static string AssessEquals(IChecker <string, ICheck <string> > checker, object expected, bool negated, bool ignoreCase = false)
        {
            if (string.Equals(checker.Value, (string)expected, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture) != negated)
            {
                return(null);
            }

            string messageText;

            if (negated)
            {
                messageText = checker.BuildShortMessage("The {0} is equal to the {1} whereas it must not.")
                              .Expected(expected)
                              .Comparison("different from")
                              .ToString();
            }
            else
            {
                // we try to refine the difference
                var expectedString               = expected as string;
                var message                      = "The {0} is different from {1}.";
                var isCrlfAndLfDifference        = false;
                var isTabAndWhiteSpaceDifference = false;
                var firstDiffPos                 = 0;

                // TODO: refactor to reduce method lines
                var value = checker.Value;
                if (expectedString != null && value != null)
                {
                    var firstDiff  = 0;
                    var blockStart = 0;
                    var blockLen   = 0;

                    var minLength = Math.Min(value.Length, expectedString.Length);

                    for (; firstDiff < minLength; firstDiff++)
                    {
                        if (value[firstDiff] != expectedString[firstDiff])
                        {
                            firstDiffPos                 = firstDiff;
                            isCrlfAndLfDifference        = IsACRLFDifference(firstDiff, expectedString, value);
                            isTabAndWhiteSpaceDifference = IsATabAndWhiteSpaceDifference(firstDiff, expectedString, value);

                            blockStart = Math.Max(0, firstDiff - 10);
                            blockLen   = Math.Min(minLength - blockStart, 20);
                            break;
                        }
                    }

                    if (expectedString.Length == value.Length)
                    {
                        // same length
                        if (string.Compare(value, expectedString, StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            message = "The {0} is different from the {1} but only in case.";
                        }
                        else
                        {
                            message = "The {0} is different from the {1} but has same length.";
                        }

                        var prefix = blockStart == 0 ? string.Empty : "...";
                        var suffix = (blockStart + blockLen) == minLength ? string.Empty : "...";
                        message += string.Format(
                            " At {0}, expected '{3}{1}{4}' was '{3}{2}{4}'",
                            firstDiff,
                            expectedString.Substring(blockStart, blockLen),
                            value.Substring(blockStart, blockLen),
                            prefix,
                            suffix);
                    }
                    else
                    {
                        if (expectedString.Length > value.Length)
                        {
                            if (expectedString.StartsWith(value, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture))
                            {
                                message = "The {0} is different from {1}, it is missing the end.";
                            }
                        }
                        else
                        {
                            if (value.StartsWith(expectedString, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture))
                            {
                                message = "The {0} is different from {1}, it contains extra text at the end.";
                            }
                        }
                    }
                }

                if (isCrlfAndLfDifference)
                {
                    value          = HighlightFirstCrlfOrLfIfAny(value, firstDiffPos);
                    expectedString = HighlightFirstCrlfOrLfIfAny(expectedString, firstDiffPos);
                }

                if (isTabAndWhiteSpaceDifference)
                {
                    value          = HighlightTabsIfAny(value);
                    expectedString = HighlightTabsIfAny(expectedString);
                }

                messageText = checker.BuildMessage(message).On(value).And.Expected(expectedString).ToString();
            }

            return(messageText);
        }
Beispiel #32
0
 public CheckerController(ILogger <CheckerController> logger, IChecker checker, ICheckerInitializer checkerInitializer)
 {
     this.logger             = logger;
     this.checker            = checker;
     this.checkerInitializer = checkerInitializer;
 }
 public ValuesController(IChecker checker, IUserRepository userRepository)
 {
     _checker        = checker;
     _userRepository = userRepository;
 }
Beispiel #34
0
        private TurnNode MovingRecurcion(TurnNode currentNode, Lib.PlayersSide whoseTurn, IChecker checker, Coord destination, int level)
        {
            IChecker[][] state = CreateStateCopy(currentNode.state);
            state = ExecuteOperationToMove(state, state[checker.CurrentCoord.Row][checker.CurrentCoord.Column], destination);
            TurnNode newNode = new TurnNode(state, EstimatingFunction(state), level);

            bool a = (side == Lib.PlayersSide.BLACK && checker is BlackChecker) || (side == Lib.PlayersSide.WHITE && checker is WhiteChecker);

            if (level == 0 && a)
            {
                MovingCommand command = new MovingCommand(game, checker, destination);
                newNode.turnCommand = command; //присваеваем команду на первом уровне рекурсии
                TurnNodes.Add(newNode);
            }
            MakeTurnNodes(newNode, AnotherPlayer(whoseTurn), level + 1);
            return(newNode);
        }
Beispiel #35
0
 public MovingCommand(IGame game, IChecker mover, Coord destination)
 {
     resiver          = game;
     this.mover       = mover;
     this.destination = destination;
 }
Beispiel #36
0
 public void FinishStep(Coord coord, IChecker mover, IChecker victim)//просто для реализации интерфейса
 {
 }
        protected virtual List <TestResult> ProcessTests(ExecutionContext executionContext, IExecutor executor, IChecker checker, string codeSavePath)
        {
            var testResults = new List <TestResult>();

            var arguments = new[] { LatestEcmaScriptFeaturesEnabledFlag, codeSavePath };

            foreach (var test in executionContext.Tests)
            {
                var processExecutionResult = this.ExecuteNodeJsProcess(executionContext, executor, test.Input, arguments);

                var testResult = this.ExecuteAndCheckTest(test, processExecutionResult, checker, processExecutionResult.ReceivedOutput);
                testResults.Add(testResult);
            }

            return(testResults);
        }
        protected void Check(CompareTarget target, IChecker checker, object expected, object candidate, string objectName)
        {
            switch (target)
            {
                case CompareTarget.Id:
                    CheckId(expected, candidate, objectName + ".Id");
                    break;

                case CompareTarget.Entity:
                    checker.Check(expected, candidate, objectName);
                    break;

                case CompareTarget.Count:
                case CompareTarget.Collection:
                    this.Check(checker, expected as IEnumerable, candidate as IEnumerable, objectName);
                    break;

                default:
                    if (CheckNullNotNull(expected, candidate, objectName))
                    {
                        return;
                    }

                    if (!expected.Equals(candidate))
                    {
                        throw new PropertyCheckException(objectName, expected, candidate);
                    }
                    break;
            }
        }
Beispiel #39
0
 public IEnumerable <AttackMove> GetMovesForLocation(IGame game, IChecker checker, TileCoordinate startLocation, IPlayer currentPlayer, IPlayer enemyPlayer, List <TileCoordinate> doneMoves)
 => GetMovesForLocation(game, checker, startLocation, currentPlayer, enemyPlayer, this.First(t => t.Checker == checker).Coordinate, doneMoves);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="checker"></param>
        /// <param name="expectedEntity"></param>
        /// <param name="candidateEntity"></param>
        /// <param name="objectName"></param>
        public void Check(IChecker checker, object expectedEntity, object candidateEntity, string objectName)
        {
            // Have to do the null check here, else "System.Reflection.TargetException: Non-static method requires a target."
            // could be thrown by RuntimePropertyInfo.GetValue().
            if (CheckNullNotNull(expectedEntity, candidateEntity, objectName))
            {
                return;
            }

            var expectedValue = this.ExtractValue(expectedEntity, objectName + ".Expected");
            var candidateValue = this.ExtractValue(candidateEntity, objectName + ".Expected");

            this.Check(this.CompareTarget, checker, expectedValue, candidateValue, objectName + "." + this.Info.Name);
        }
Beispiel #41
0
 public ITile GetOccupiedTileByChecker(IChecker checker) => this.FirstOrDefault(t => t.Checker == checker);
        private static void ValidateConfig(IChecker assume)
        {
            if (EncLevel == EncryptionLevel.ENCRYPTION_LEVEL_NONE)
            {
                assume.IsTrue(
                    EncMethod == EncryptionMethods.ENCRYPTION_METHOD_NONE,
                    "When Encryption Level is set to None, the Encryption Method must also set to None."
                    );
            }

            if (EncLevel == EncryptionLevel.ENCRYPTION_LEVEL_FIPS)
            {
                assume.IsTrue(
                    EncMethod == EncryptionMethods.ENCRYPTION_METHOD_FIPS,
                    "When Encryption Level is set to FIPS, the Encryption Method must be set to FIPS."
                    );
            }

            if (TransportProtocol == EncryptedProtocol.Rdp)
            {
                assume.IsTrue(
                    EncLevel != EncryptionLevel.ENCRYPTION_LEVEL_NONE,
                    "When use standard RDP security, the encryption level must be greater than 'None'."
                    );
            }
            else
            {
                assume.IsTrue(
                    EncLevel == EncryptionLevel.ENCRYPTION_LEVEL_NONE,
                    "When use enhanced security protocols (TLS or CredSSP), the encryption level must be set to 'None'."
                    );
            }
        }
Beispiel #43
0
 public void addTransition(IState <T> origin, IState <T> target, IChecker <T> .check checker)
 {
     addTransition(new Transition <T>(origin, target, checker));
 }
        private static string ContainsImpl(IChecker<string, ICheck<string>> checker, IEnumerable<string> values, bool negated, bool notContains)
        {
            var checkedValue = checker.Value;

            // special case if checkedvalue is null
            if (checkedValue == null)
            {
                return (negated || notContains) ? null : checker.BuildShortMessage("The {0} is null.").For("string").Expected(values).Label("The {0} substring(s):").ToString();
            }

            var items = values.Where(item => checkedValue.Contains(item) == notContains).ToList();

            if (negated == (items.Count > 0))
            {
                return null;
            }

            if (!notContains && negated)
            {
                items = values.ToList();
            }

            if (negated != notContains)
            {
                return
                    checker.BuildMessage(
                        "The {0} contains unauthorized value(s): " + items.ToEnumeratedString())
                                 .For("string")
                                 .Expected(values)
                                 .Label("The unauthorized substring(s):")
                                 .ToString();
            }

            return
                checker.BuildMessage(
                    "The {0} does not contains the expected value(s): " + items.ToEnumeratedString())
                             .For("string")
                             .Expected(values)
                             .Label("The {0} substring(s):")
                             .ToString();
        }
Beispiel #45
0
 public void CheckList(IChecker checker, IEnumerable expected, IEnumerable candidate, string objectName)
 {
     Check(checker, expected, candidate, objectName);
 }
        private static string MatchesImpl(IChecker<string, ICheck<string>> checker, string regExp, bool negated)
        {
            var checkedValue = checker.Value;

            // special case if checkedvalue is null
            if (checkedValue == null)
            {
                return negated ? null : checker.BuildShortMessage("The {0} is null.").For("string").Expected(regExp).Comparison("matches").ToString();
            }

            var exp = new Regex(regExp);
            if (exp.IsMatch(checkedValue) != negated)
            {
                // success
                return null;
            }

            if (negated)
            {
                return
                    checker.BuildMessage("The {0} matches {1}, whereas it must not.")
                    .For("string")
                                 .Expected(regExp)
                                 .Comparison("does not match")
                                 .ToString();
            }

            return
                checker.BuildMessage("The {0} does not match the {1}.")
                .For("string")
                             .Expected(regExp)
                             .Comparison("matches")
                             .ToString();
        }
Beispiel #47
0
        /// <summary>
        /// Register a <see cref="IChecker{T}" /> for <see typeparamref="T" />
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="checker"></param>
        public CheckerFactory Register <T>(IChecker <T> checker)
        {
            Register(typeof(T), (IChecker)checker);

            return(this);
        }
 protected FeatureSwitchProvider()
 {
     FeatureSwitches = new Dictionary<string, Feature>();
     this.SwitchChecker = new StateChecker();
 }
 public void AddChecker(IChecker checker)
 {
     checkerImpl = checker;
 }
Beispiel #50
0
        /// <summary>
        /// Apply a <see cref="CompareTarget"/> to a checker for some entities.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="checker"></param>
        /// <param name="expected"></param>
        /// <param name="candidate"></param>
        /// <param name="objectName"></param>
        protected void Check(CompareTarget target, IChecker checker, object expected, object candidate, string objectName)
        {
            switch (target)
            {
                case CompareTarget.Ignore:
                    break;

                case CompareTarget.Id:
                    CheckId(expected, candidate, objectName + ".Id");
                    break;

                case CompareTarget.Entity:
                    checker.Check(expected, candidate, objectName);
                    break;

                case CompareTarget.Count:
                case CompareTarget.Collection:
                    Check(checker, expected as IEnumerable, candidate as IEnumerable, objectName);
                    break;

                case CompareTarget.Value:
                    Check(expected, candidate, objectName);
                    break;

                default:
                    throw new NotSupportedException("Cannot perform comparison: " + target);
            }
        }
 public BasicCheckController(string identifier, IChecker checker, ICollection <INotifyResultFilter> notifyResultFilters, INotifier notifier)
     : base(identifier, checker, notifyResultFilters, notifier)
 {
 }
        protected virtual List<TestResult> ProcessTests(ExecutionContext executionContext, IExecutor executor, IChecker checker, string codeSavePath)
        {
            var testResults = new List<TestResult>();

            foreach (var test in executionContext.Tests)
            {
                var processExecutionResult = executor.Execute(this.NodeJsExecutablePath, test.Input, executionContext.TimeLimit, executionContext.MemoryLimit, new[] { codeSavePath });
                var testResult = this.ExecuteAndCheckTest(test, processExecutionResult, checker, processExecutionResult.ReceivedOutput);
                testResults.Add(testResult);
            }

            return testResults;
        }
        private ExecutionResult RunUnitTests(
            ExecutionContext executionContext,
            IExecutor executor,
            IChecker checker,
            ExecutionResult result,
            string csProjFilePath)
        {
            var compileDirectory = Path.GetDirectoryName(csProjFilePath);
            var fileName         = Path.GetFileName(csProjFilePath);

            if (!string.IsNullOrEmpty(fileName))
            {
                fileName = fileName.Replace(ProjectFileExtenstion, DllFileExtension);
            }

            var targetDll = $"{compileDirectory}\\{CompiledResultFolder}{fileName}";
            var arguments = new List <string> {
                targetDll
            };

            arguments.AddRange(executionContext.AdditionalCompilerArguments.Split(' '));

            var testedCodePath      = $"{compileDirectory}\\{TestedCode}";
            var originalTestsPassed = -1;
            var count = 0;

            foreach (var test in executionContext.Tests)
            {
                File.WriteAllText(testedCodePath, test.Input);

                var project    = new Project(csProjFilePath);
                var didCompile = project.Build();
                project.ProjectCollection.UnloadAllProjects();

                if (!didCompile)
                {
                    result.IsCompiledSuccessfully = false;
                    return(result);
                }

                var processExecutionResult = executor.Execute(
                    this.NUnitConsoleRunnerPath,
                    string.Empty,
                    executionContext.TimeLimit,
                    executionContext.MemoryLimit,
                    arguments);

                var totalTests  = 0;
                var passedTests = 0;

                this.ExtractTestResult(processExecutionResult.ReceivedOutput, out passedTests, out totalTests);
                var message = "Test Passed!";

                if (totalTests == 0)
                {
                    message = "No tests found";
                }
                else if (passedTests == originalTestsPassed)
                {
                    message = "No functionality covering this test!";
                }

                if (count == 0)
                {
                    originalTestsPassed = passedTests;
                    if (totalTests != passedTests)
                    {
                        message = "Not all tests passed on the correct solution.";
                    }
                }

                var testResult = this.ExecuteAndCheckTest(test, processExecutionResult, checker, message);

                File.Delete(testedCodePath);
                result.TestResults.Add(testResult);
                count++;
            }

            return(result);
        }
        public void SamrQuerySecurityObject_Server_DACL()
        {
            HRESULT  hResult;
            IChecker PtfAssert = TestClassBase.BaseTestSite.Assert;

            Site.Log.Add(LogEntryKind.TestStep,
                         string.Format("SamrBind, Server:{0}, Domain:{1}, User:{2}, Password{3}.",
                                       _samrProtocolAdapter.pdcNetBIOSName,
                                       _samrProtocolAdapter.primaryDomainFqdn,
                                       _samrProtocolAdapter.DomainAdministratorName,
                                       _samrProtocolAdapter.DomainUserPassword));
            _samrProtocolAdapter.SamrBind(
                _samrProtocolAdapter.pdcNetBIOSName,
                _samrProtocolAdapter.primaryDomainFqdn,
                _samrProtocolAdapter.DomainAdministratorName,
                _samrProtocolAdapter.DomainUserPassword,
                false,
                true);
            Site.Log.Add(LogEntryKind.TestStep,
                         string.Format("SamrConnect5, Server:{0}, Desired Access: READ_CONTROL.", _samrProtocolAdapter.PDCNetbiosName));
            hResult = (HRESULT)_samrProtocolAdapter.SamrConnect5(
                _samrProtocolAdapter.PDCNetbiosName,
                (uint)COMMON_ACCESS_MASK.READ_CONTROL,
                out _serverHandle);
            PtfAssert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrConnect5 must return STATUS_SUCCESS.");

            Site.Log.Add(LogEntryKind.TestStep,
                         "SamrQuerySecurityObject, SecurityInformation: DACL_SECURITY_INFORMATION.");
            _SAMPR_SR_SECURITY_DESCRIPTOR?securityDescriptor;

            hResult = (HRESULT)SAMRProtocolAdapter.RpcAdapter.SamrQuerySecurityObject(
                _serverHandle,
                SamrQuerySecurityObject_SecurityInformation_Values.DACL_SECURITY_INFORMATION,
                out securityDescriptor);
            PtfAssert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrQuerySecurityObject must return STATUS_SUCCESS.");
            PtfAssert.IsNotNull(securityDescriptor, "The SecurityDescriptor returned by SamrQuerySecurityObject is not null.");
            _SECURITY_DESCRIPTOR sd = DtypUtility.DecodeSecurityDescriptor(securityDescriptor.Value.SecurityDescriptor);

            PtfAssert.IsNotNull(sd.Dacl,
                                "[MS-SAMR] 3.1.5.12.2 If this bit(DACL_SECURITY_INFORMATION) is set, the client requests that the DACL be returned.");
            PtfAssert.IsNull(sd.OwnerSid,
                             "[MS-SAMR] 3.1.5.12.2 The field(OwnerSid) of the security descriptor is not returned and is set to zero.");
            PtfAssert.IsNull(sd.GroupSid,
                             "[MS-SAMR] 3.1.5.12.2 The field(GroupSid) of the security descriptor is not returned and is set to zero.");
            PtfAssert.IsNull(sd.Sacl,
                             "[MS-SAMR] 3.1.5.12.2 The field(SACL) of the security descriptor is not returned and is set to zero.");

            Site.Log.Add(LogEntryKind.TestStep,
                         "Verifies that the DACL returned from the server contains the following ACEs: WorldSid(SAM_SERVER_EXECUTE | SAM_SERVER_READ), AdministratorSid(SAM_SERVER_ALL_ACCESS");
            bool worldSidFound = false;
            uint worldSidMask  = 0;
            bool adminSidFound = false;
            uint adminSidMask  = 0;

            foreach (var o in sd.Dacl.Value.Aces)
            {
                if (!(o is Microsoft.Protocols.TestTools.StackSdk.Dtyp._ACCESS_ALLOWED_ACE))
                {
                    continue;
                }
                Microsoft.Protocols.TestTools.StackSdk.Dtyp._ACCESS_ALLOWED_ACE ace = (Microsoft.Protocols.TestTools.StackSdk.Dtyp._ACCESS_ALLOWED_ACE)o;
                switch (DtypUtility.ToSddlString(ace.Sid))
                {
                case AdministratorSid:
                    adminSidFound = true;
                    adminSidMask  = ace.Mask;
                    break;

                case WorldSid:
                    worldSidFound = true;
                    worldSidMask  = ace.Mask;
                    break;
                }
            }
            PtfAssert.IsTrue(worldSidFound,
                             "[MS-SAMR] 3.1.5.12.2 If ObjectHandle.Object refers to the server object, the DACL MUST contain the following ACE. WorldSid");
            PtfAssert.AreEqual(SERVER_ACCESS_MASK.SAM_SERVER_EXECUTE | SERVER_ACCESS_MASK.SAM_SERVER_READ, (SERVER_ACCESS_MASK)worldSidMask,
                               "The access mask of WorldSid is SAM_SERVER_EXECUTE|SAM_SERVER_READ.");
            PtfAssert.IsTrue(adminSidFound,
                             "[MS-SAMR] 3.1.5.12.2 If ObjectHandle.Object refers to the server object, the DACL MUST contain the following ACE. AdministratorSid");
            PtfAssert.AreEqual(SERVER_ACCESS_MASK.SAM_SERVER_ALL_ACCESS, (SERVER_ACCESS_MASK)adminSidMask,
                               "The access mask of AdministratorSid is SAM_SERVER_ALL_ACCESS.");
        }
Beispiel #55
0
 public void 檢查是否是電話號碼_是()
 {
     IChecker checker = null;
 }
        public override void SetParameter(string parameter)
        {
            var customCheckerFromCache = this.compiledCustomCheckersCache[parameter] as IChecker;

            if (customCheckerFromCache != null)
            {
                this.customChecker = customCheckerFromCache;
                return;
            }

            var codeProvider       = new CSharpCodeProvider();
            var compilerParameters = new CompilerParameters {
                GenerateInMemory = true,
            };

            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "OJS.Workers.Common.dll");
            var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, parameter);

            if (compilerResults.Errors.HasErrors)
            {
                var errorsStringBuilder = new StringBuilder();
                foreach (CompilerError error in compilerResults.Errors)
                {
                    errorsStringBuilder.AppendLine(error.ToString());
                }

                // TODO: Introduce class CompilerException and throw exception of this type
                throw new Exception(
                          string.Format(
                              "Could not compile checker!{0}Errors:{0}{1}",
                              Environment.NewLine,
                              errorsStringBuilder));
            }

            var assembly = compilerResults.CompiledAssembly;

            var types = assembly.GetTypes().Where(x => typeof(IChecker).IsAssignableFrom(x)).ToList();

            if (types.Count > 1)
            {
                throw new Exception("More than one implementation of OJS.Workers.Common.IChecker was found!");
            }

            var type = types.FirstOrDefault();

            if (type == null)
            {
                throw new Exception("Implementation of OJS.Workers.Common.IChecker not found!");
            }

            var instance = Activator.CreateInstance(type) as IChecker;

            if (instance == null)
            {
                throw new Exception($"Cannot create an instance of type {type.FullName}!");
            }

            this.compiledCustomCheckersCache.Set(parameter, instance, new CacheItemPolicy {
                SlidingExpiration = CacheDaysSlidingExpiration
            });
            this.customChecker = instance;
        }
        protected override List <TestResult> ProcessTests(
            ExecutionContext executionContext,
            IExecutor executor,
            IChecker checker,
            string codeSavePath)
        {
            var testResults = new List <TestResult>();

            var arguments = new List <string>();

            arguments.Add(this.MochaModulePath);
            arguments.Add(codeSavePath);
            arguments.AddRange(executionContext.AdditionalCompilerArguments.Split(' '));

            var testCount = 0;
            var processExecutionResult    = this.ExecuteNodeJsProcess(executionContext, executor, string.Empty, arguments);
            var mochaResult               = JsonExecutionResult.Parse(processExecutionResult.ReceivedOutput);
            var numberOfUserTests         = mochaResult.UsersTestCount;
            var correctSolutionTestPasses = mochaResult.InitialPassingTests;

            // an offset for tracking the current subset of tests (by convention we always have 2 Zero tests)
            var testOffset = numberOfUserTests * 2;

            foreach (var test in executionContext.Tests)
            {
                var        message    = "Test Passed!";
                TestResult testResult = null;
                if (testCount == 0)
                {
                    var minTestCount = int.Parse(
                        Regex.Match(
                            test.Input,
                            "<minTestCount>(\\d+)</minTestCount>").Groups[1].Value);
                    if (numberOfUserTests < minTestCount)
                    {
                        message = $"Insufficient amount of tests, you have to have atleast {minTestCount} tests!";
                    }

                    testResult = this.ExecuteAndCheckTest(
                        test,
                        processExecutionResult,
                        checker,
                        message);
                }
                else if (testCount == 1)
                {
                    if (numberOfUserTests == 0)
                    {
                        message = "The submitted code was either incorrect or contained no tests!";
                    }
                    else if (correctSolutionTestPasses != numberOfUserTests)
                    {
                        message = "Error: Some tests failed while running the correct solution!";
                    }

                    testResult = this.ExecuteAndCheckTest(
                        test,
                        processExecutionResult,
                        checker,
                        message);
                }
                else
                {
                    var numberOfPasses = mochaResult.TestErrors.Skip(testOffset).Take(numberOfUserTests).Count(x => x == null);
                    if (numberOfPasses >= correctSolutionTestPasses)
                    {
                        message = "No unit test covering this functionality!";
                    }

                    testResult = this.ExecuteAndCheckTest(
                        test,
                        processExecutionResult,
                        checker,
                        message);
                    testOffset += numberOfUserTests;
                }

                testCount++;
                testResults.Add(testResult);
            }

            return(testResults);
        }
 public BasicCheckController(string identifier, IChecker checker, ICollection<INotifyResultFilter> notifyResultFilters, INotifier notifier)
     : base(identifier, checker, notifyResultFilters, notifier)
 {
 }
 private static void GivenAProviderWithAChecker()
 {
     provider = new InMemorySwitchProvider(features);
     checker = Substitute.For<IChecker>();
     provider.AddChecker(checker);
 }