Esempio n. 1
0
        /// <summary>
        /// Implementation to execute when set action.
        /// </summary>
        /// <param name="input">stream input</param>
        /// <param name="context">Input context</param>
        /// <returns>
        /// <para>
        /// A <see cref="SetResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b>
        /// property will be <b>true</b> and the <b>Value</b> property will contain the value; Otherwise, the the <b>Success</b> property
        /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in.
        /// </para>
        /// <para>
        /// The type of the return value is <see cref="SetResultData"/>, which contains the operation result
        /// </para>
        /// </returns>
        protected override SetResult SetImpl(Stream input, IInput context)
        {
            if (string.IsNullOrEmpty(SheetName))
            {
                return(SetResult.CreateErroResult(
                           "Sheet name can not be null or empty",
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            if (string.IsNullOrEmpty(NewName))
            {
                return(SetResult.CreateErroResult(
                           $"New sheet name '{NewName}' can not be null or empty",
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            return(SetImpl(context, input, SheetName, NewName));
        }
Esempio n. 2
0
        internal async void InitialisePlay(string mixId)
        {
            if (App.Settings.PlayToken == null || App.Settings.PlayToken == string.Empty)
            {
                //TODO: Lock down user token
                SetResult result = await App.Engine.PlayToken(App.Settings.UserToken);

                if (result.errors == null || result.errors == string.Empty)
                {
                    App.Settings.PlayToken = result.play_token;
                }
            }

            //TODO: Lock down user token
            PlayResult playResult = await App.Engine.Play(App.Settings.UserToken, App.Settings.PlayToken, mixId);

            if (playResult.errors == null || playResult.errors == string.Empty)
            {
                MediaElement playMedia = this.FindName("playMedia") as MediaElement;
                if (playMedia != null)
                {
                    playMedia.Source = new Uri(playResult.set.track.url);
                    playMedia.Play();
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Implementation to execute when set action.
        /// </summary>
        /// <param name="input">stream input</param>
        /// <param name="context">Input context</param>
        /// <returns>
        /// <para>
        /// A <see cref="SetResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b>
        /// property will be <b>true</b> and the <b>Value</b> property will contain the value; Otherwise, the the <b>Success</b> property
        /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in.
        /// </para>
        /// <para>
        /// The type of the return value is <see cref="SetResultData"/>, which contains the operation result
        /// </para>
        /// </returns>
        protected override SetResult SetImpl(Stream input, IInput context)
        {
            if (string.IsNullOrEmpty(SheetName))
            {
                return(SetResult.CreateErroResult(
                           "Sheet name can not be null or empty",
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            if (Columns == null)
            {
                return(SetResult.CreateSuccessResult(new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            return(SetImpl(context, input, SheetName, Columns));
        }
        public async Task Calculate_WhenThreeGames_ExpectResultReturned()
        {
            var fixture = new Fixture();

            var tennisGame = fixture.Create <TennisGame>();

            var result01 = new SetResult(fixture.Create <TennisSet>(),
                                         new TennisGame(new List <char>
            {
                'a', 'b', 'a'
            }));

            var result02 = new SetResult(fixture.Create <TennisSet>(),
                                         new TennisGame(new List <char>
            {
                'd', 'd', 'e'
            }));

            var result03 = new SetResult(fixture.Create <TennisSet>(),
                                         new TennisGame(new List <char>()));

            _mockSetCalculator.Calculate(Arg.Any <TennisGame>())
            .Returns(result01, result02, result03);

            var tennisMatch = await _sut.Calculate(tennisGame);

            var expectedResult = new List <TennisSet> {
                result01.Set, result02.Set, result03.Set
            };

            tennisMatch.Sets.Should().BeEquivalentTo(expectedResult);
        }
Esempio n. 5
0
        private static SetResult SetImpl(IInput context, Stream input, XlsxDocumentMetadataSettings settings)
        {
            var outputStream = new MemoryStream();

            try
            {
                using (var excel = new ExcelPackage(input))
                {
                    excel.Workbook.Properties.SetDocumentMetadata(settings);
                    excel.SaveAs(outputStream);

                    return(SetResult.CreateSuccessResult(new SetResultData
                    {
                        Context = context,
                        InputStream = input,
                        OutputStream = outputStream
                    }));
                }
            }
            catch (Exception ex)
            {
                return(SetResult.FromException(
                           ex,
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Esempio n. 6
0
        public void Should_be_possible_to_evaluate_a_Set_in_the_ObjectType()
        {
            OvalDocumentLoader ovalDocument = new OvalDocumentLoader();

            sc.oval_system_characteristics systemCharacteristics = ovalDocument.GetFakeOvalSystemCharacteristics("system_characteristics_with_sets.xml");
            oval_definitions        definitions = ovalDocument.GetFakeOvalDefinitions("definitionsWithSet.xml");
            IEnumerable <StateType> states      = definitions.states;

            set registryObjectSet = SetFactory.GetSetFromDefinitionsOfRegistryObject("definitionsWithSet.xml", "oval:org.mitre.oval:obj:6000");

            SetEvaluator setEvaluator = new SetEvaluator(systemCharacteristics, states, null);
            SetResult    result       = setEvaluator.Evaluate(registryObjectSet);

            Assert.IsNotNull(result, "the items expected is null");
            Assert.AreEqual(3, result.Result.Count(), "the quantity of items is not expected");
            Assert.AreEqual(FlagEnumeration.complete, result.ObjectFlag, "the object flag is not expected");

            string element = result.Result.Where <string>(item => item == "1").SingleOrDefault();

            Assert.IsNotNull(element, "the element expected is not exits");
            element = result.Result.Where <string>(item => item == "2").SingleOrDefault();
            Assert.IsNotNull(element, "the element expected is not exits");
            element = result.Result.Where <string>(item => item == "3").SingleOrDefault();
            Assert.IsNotNull(element, "the element expected is not exits");
        }
        public async Task Calculate_WhenThreeGames_ExpectCalculatorCalledThreeTimes()
        {
            var fixture = new Fixture();

            var tennisGame = fixture.Create <TennisGame>();

            var result01 = new SetResult(fixture.Create <TennisSet>(),
                                         new TennisGame(new List <char>
            {
                'a', 'b', 'a'
            }));

            var result02 = new SetResult(fixture.Create <TennisSet>(),
                                         new TennisGame(new List <char>
            {
                'd', 'd', 'e'
            }));

            var result03 = new SetResult(fixture.Create <TennisSet>(),
                                         new TennisGame(new List <char>()));

            _mockSetCalculator.Calculate(Arg.Any <TennisGame>())
            .Returns(result01, result02, result03);

            await _sut.Calculate(tennisGame);

            await _mockSetCalculator
            .Received(3)
            .Calculate(Arg.Any <TennisGame>());
        }
Esempio n. 8
0
        public async Task <IActionResult> GetRank50()
        {
            var ds = memoryCache.Get <SetResult <SortedItem> >(Top50Key);

            if (ds != null)
            {
                return(Ok(ds));
            }
            var res = await comicRankService.RangeAsync(0, 50);

            var size = await comicRankService.SizeAsync();

            var items = res.Select(x => new SortedItem
            {
                Address = x.Element.ToString(),
                Scope   = x.Score
            }).ToArray();

            ds = new SetResult <SortedItem>
            {
                Skip  = 0,
                Take  = 50,
                Total = size,
                Datas = items,
            };
            memoryCache.Set(Top50Key, ds, new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromSeconds(2)
            });
            return(Ok(ds));
        }
Esempio n. 9
0
        public IActionResult Index(int id, double set)
        {
            if (!_context.AnimateList.Any(anime => anime.Id == id))
            {
                return(null);
            }
            var item = _context.SetDetail.FirstOrDefault(anime => anime.Id == id && anime.SetName == set);

            if (item == null)
            {
                return(null);
            }
            item.ClickCount++;
            _context.Entry(item).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            _context.SaveChanges();
            var title = LanguageHelper.GetLanguegeName(Request.Headers["Accept-Language"], _context.AnimateList.FirstOrDefault(amine => amine.Id == id));

            ViewBag.Title    = $"{title} - {set}";
            ViewBag.IsMobile = Request.IsMobileBrowser();
            var model = new SetResult {
                HighQuality = item.HighQuality, LowQuality = item.LowQuality, MediumQuality = item.MediumQuality, OriginalQuality = item.OriginalQuality ?? item.FilePath
            };

            return(View(model));
        }
Esempio n. 10
0
 private void WriteSet(SetResult result, string name)
 {
     Console.WriteLine();
     Console.WriteLine(" ----- SET WINNER ----");
     Console.WriteLine($" ----- {name} ----");
     Console.WriteLine();
 }
Esempio n. 11
0
        public JsonResult Create([FromBody] SetResult setResult)
        {
            var context = new WorkoutTrackerContext();

            setResult.UserId = this.UserId;
            context.SetResults.Add(setResult);
            context.SaveChanges();
            return(Json(setResult));
        }
Esempio n. 12
0
        public JsonResult Update([FromBody] SetResult setResult)
        {
            var context = new WorkoutTrackerContext();

            setResult.UserId = this.UserId;
            context.Entry(context.SetResults.Find(setResult.Id)).CurrentValues.SetValues(setResult);
            context.SaveChanges();
            return(Json(setResult));
        }
    public static void Init(SetResult action, string[] options)
    {
        if(SearchableWindow.windowInstance != null)
            SearchableWindow.windowInstance.Close();

        windowInstance = EditorWindow.GetWindow <SearchableWindow>(true, "Search Window", true);
        windowInstance.action = action;
        windowInstance.options = options;
    }
Esempio n. 14
0
    public static void Init(SetResult action, string[] options)
    {
        if (SearchableWindow.windowInstance != null)
        {
            SearchableWindow.windowInstance.Close();
        }

        windowInstance         = EditorWindow.GetWindow <SearchableWindow>(true, "Search Window", true);
        windowInstance.action  = action;
        windowInstance.options = options;
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="ArticleMasterSetResponse"/> class.
        /// </summary>
        /// <param name="message">The message to use for initialization.</param>
        public ArticleMasterSetResponse(MosaicMessage message)
        {
            var response = (Interfaces.Messages.Stock.ArticleMasterSetResponse)message;

            this.Id = response.ID;
            this.Source = response.Source;
            this.Destination = response.Destination;

            this.SetResult = new SetResult() 
            {
                Value = response.SetResult ? "Accepted" : "Rejected",
                Text = string.IsNullOrEmpty(response.SetResultText) ? null : TextConverter.EscapeInvalidXmlChars(response.SetResultText)
            };
        }
Esempio n. 16
0
        /// <summary>
        /// Implementation to execute when set action.
        /// </summary>
        /// <param name="input">stream input</param>
        /// <param name="context">Input context</param>
        /// <returns>
        /// <para>
        /// A <see cref="SetResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b>
        /// property will be <b>true</b> and the <b>Value</b> property will contain the value; Otherwise, the the <b>Success</b> property
        /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in.
        /// </para>
        /// <para>
        /// The type of the return value is <see cref="SetResultData"/>, which contains the operation result
        /// </para>
        /// </returns>
        protected override SetResult SetImpl(Stream input, IInput context)
        {
            if (Settings == null)
            {
                return(SetResult.CreateSuccessResult(new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }

            return(SetImpl(context, input, Settings));
        }
        public void Achieved_Minimum_Set_Result(int player1Score, int player2Score, bool expectedResult)
        {
            //arrange
            var set = new SetResult(null, null)
            {
                Player1Score = player1Score, Player2Score = player2Score
            };

            //act
            var result = new MinimumScoreRule().IsAchieved(set);

            //assert
            Assert.Equal(expectedResult, result);
        }
Esempio n. 18
0
        private static SetResult SetImpl(IInput context, Stream input)
        {
            var outputStream = new MemoryStream();

            try
            {
                using (var excel = new ExcelPackage(input))
                {
                    foreach (var ws in excel.Workbook.Worksheets)
                    {
                        var hasDimension = ws.Dimension != null;
                        if (!hasDimension)
                        {
                            continue;
                        }

                        ws.Cells[ws.Dimension.Address].AutoFitColumns();

                        var start = ws.Cells[ws.Dimension.Address].Start.Column;
                        var end   = ws.Cells[ws.Dimension.Address].End.Column;
                        for (int col = start; col <= end; col++)
                        {
                            ws.Column(col).BestFit = true;
                            ws.Column(col).Width   = ws.Column(col).Width + 1;
                        }
                    }

                    excel.SaveAs(outputStream);

                    return(SetResult.CreateSuccessResult(new SetResultData
                    {
                        Context = context,
                        InputStream = input,
                        OutputStream = outputStream
                    }));
                }
            }
            catch (Exception ex)
            {
                return(SetResult.FromException(
                           ex,
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Esempio n. 19
0
        public SetResult ConductSet(Player player1, Player player2)
        {
            var setResult = new SetResult(player1, player2);

            while (!_setRules.All(r => r.IsAchieved(setResult)))
            {
                setResult.Play();
            }

            setResult.IsFinished = true;

            setResult.Winner = setResult.Player2Score > setResult.Player1Score ? player2 : player1;

            return(setResult);
        }
Esempio n. 20
0
        public async Task Calculate_WhenSingleGame_ExpectResultReturned()
        {
            var fixture = new Fixture();

            var tennisGame = fixture.Create <TennisGame>();

            var setResult = new SetResult(fixture.Create <TennisSet>(),
                                          new TennisGame(new List <char>()));

            _mockSetCalculator.Calculate(tennisGame).Returns(setResult);

            var tennisMatch = await _sut.Calculate(tennisGame);

            tennisMatch.Sets.Should().BeEquivalentTo(setResult.Set);
        }
Esempio n. 21
0
        private static SetResult SetImpl(IInput context, Stream input, string sheetName, IEnumerable <ColumnDefinition> columns)
        {
            var outputStream = new MemoryStream();

            try
            {
                using (var excel = new ExcelPackage(input))
                {
                    var ws = excel.Workbook.Worksheets.FirstOrDefault(worksheet => worksheet.Name.Equals(sheetName, StringComparison.OrdinalIgnoreCase));
                    if (ws == null)
                    {
                        return(SetResult.CreateErroResult(
                                   $"Sheet '{sheetName}' not found",
                                   new SetResultData
                        {
                            Context = context,
                            InputStream = input,
                            OutputStream = input
                        }));
                    }

                    foreach (var column in columns)
                    {
                        ws.Column(column.Column).Width = column.Width;
                    }

                    excel.SaveAs(outputStream);

                    return(SetResult.CreateSuccessResult(new SetResultData
                    {
                        Context = context,
                        InputStream = input,
                        OutputStream = outputStream
                    }));
                }
            }
            catch (Exception ex)
            {
                return(SetResult.FromException(
                           ex,
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Evaluates the setObjects in the tree. This method invokes the Evaluate method in the recursive form.
        /// The evaluation starts in the more deep level in the tree of objects.
        /// Then the upper levels will evaluated based on result of the deeper levels.
        /// </summary>
        /// <param name="setElement">The set element.</param>
        /// <returns></returns>
        private SetResult EvaluateOtherSets(set setElement)
        {
            IEnumerable <set> otherSetsElements = setElement.GetSets();
            SetResult         resultFirstSet    = this.Evaluate(otherSetsElements.First());
            SetResult         resultSecondSet   = new SetResult(new List <String>(), FlagEnumeration.notcollected);

            //the max number of set is 2 (reference: oval_definitions schema)
            if (otherSetsElements.Count() == MAX_NUMBER_OF_OBJECTS_IN_SET)
            {
                resultSecondSet = this.Evaluate(otherSetsElements.ElementAt(1));
            }
            SetOperation         operation  = this.GetOperation(setElement.set_operator);
            IEnumerable <string> results    = operation.Execute(resultFirstSet.Result, resultSecondSet.Result);
            FlagEnumeration      objectFlag = operation.GetObjectFlag(resultFirstSet.ObjectFlag, resultSecondSet.ObjectFlag);

            return(new SetResult(results, objectFlag));
        }
Esempio n. 23
0
        public async Task Calculate_WhenSingleGame_ExpectCalculatorCalledOnce()
        {
            var fixture = new Fixture();

            var tennisGame = fixture.Create <TennisGame>();

            var setResult = new SetResult(fixture.Create <TennisSet>(),
                                          new TennisGame(new List <char>()));

            _mockSetCalculator.Calculate(tennisGame).Returns(setResult);

            await _sut.Calculate(tennisGame);

            await _mockSetCalculator
            .Received(1)
            .Calculate(tennisGame);
        }
Esempio n. 24
0
        private static SetResult SetImpl(IInput context, Stream input, string sheetName, YesNo show)
        {
            var outputStream = new MemoryStream();

            try
            {
                using (var excel = new ExcelPackage(input))
                {
                    var ws = excel.Workbook.Worksheets.FirstOrDefault(worksheet => worksheet.Name.Equals(sheetName, StringComparison.OrdinalIgnoreCase));
                    if (ws == null)
                    {
                        return(SetResult.CreateErroResult(
                                   $"Sheet '{sheetName}' not found",
                                   new SetResultData
                        {
                            Context = context,
                            InputStream = input,
                            OutputStream = input
                        }));
                    }

                    ws.View.ShowGridLines = show == YesNo.Yes;

                    excel.SaveAs(outputStream);

                    return(SetResult.CreateSuccessResult(new SetResultData
                    {
                        Context = context,
                        InputStream = input,
                        OutputStream = outputStream
                    }));
                }
            }
            catch (Exception ex)
            {
                return(SetResult.FromException(
                           ex,
                           new SetResultData
                {
                    Context = context,
                    InputStream = input,
                    OutputStream = input
                }));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Try to set an element in this input.
        /// </summary>
        /// <param name="data">Reference to seteable object information</param>
        /// <returns>
        /// <para>
        /// A <see cref="SetResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b>
        /// property will be <b>true</b> and the <b>Result</b> property will contain the Result; Otherwise, the the <b>Success</b> property
        /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in.
        /// </para>
        /// <para>
        /// The type of the return Result is <see cref="SetResultData"/>, which contains the operation result
        /// </para>
        /// </returns>
        public SetResult Set(ISet data)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Utilities.DocX.Writer, Namespace: iTin.Utilities.DocX.Writer, Class: DocXInput");
            Logger.Instance.Debug(" Try to set an element in this input");
            Logger.Instance.Debug($" > Signature: ({typeof(SetResult)}) Set({typeof(ISet)})");
            Logger.Instance.Debug($"   > data: {data}");

            SetResult result = SetImplStrategy(data, this);

            if (AutoUpdateChanges)
            {
                Input = result.Result.OutputStream;
            }

            Logger.Instance.Debug($" > Output: Setted = {result.Success}");

            return(result);
        }
Esempio n. 26
0
        public async Task <IActionResult> GetHotSearch30()
        {
            var res = await comicRankService.RangeSearchAsync(0, 30);

            var size = await comicRankService.SizeSearchAsync();

            var items = res.Select(x => new HotSearchItem
            {
                Keyword = x.Element.ToString(),
                Scope   = x.Score
            }).ToArray();
            var ds = new SetResult <HotSearchItem>
            {
                Skip  = 0,
                Take  = 50,
                Total = size,
                Datas = items,
            };

            return(Ok(ds));
        }
Esempio n. 27
0
        public async Task <IActionResult> GetHotSearch30()
        {
            var res = await hotSearchService.GetHotSearchAsync(0, 30);

            var size = await hotSearchService.SizeAsync();

            var items = res.Select(x => new SortedItem
            {
                Address = x.Element.ToString(),
                Scope   = x.Score
            }).ToArray();
            var ds = new SetResult <SortedItem>
            {
                Skip  = 0,
                Take  = 50,
                Total = size,
                Datas = items,
            };

            return(Ok(ds));
        }
Esempio n. 28
0
        private SetResult ExecuteOperationForSetElement(set setElement, IEnumerable <sc.ObjectType> objectTypes)
        {
            sc.ObjectType        firstObjectType      = objectTypes.First();
            sc.ObjectType        secondObjectType     = null;
            IEnumerable <string> firstReferenceTypes  = firstObjectType.GetReferenceTypesInString();
            IEnumerable <string> secondReferenceTypes = new List <string>();
            FlagEnumeration      firstObjectFlag      = firstObjectType.flag;
            FlagEnumeration      secondObjectFlag     = FlagEnumeration.complete;

            if (objectTypes.Count() == MAX_NUMBER_OF_OBJECTS_IN_SET)
            {
                //the max number to the Object_Reference is 2 (reference: oval_definitions schema)
                secondObjectType     = objectTypes.ElementAt(1);
                secondReferenceTypes = secondObjectType.GetReferenceTypesInString();
                secondObjectFlag     = secondObjectType.flag;
            }
            SetOperation         operation  = this.GetOperation(setElement.set_operator);
            IEnumerable <string> results    = operation.Execute(firstReferenceTypes, secondReferenceTypes);
            FlagEnumeration      objectFlag = operation.GetObjectFlag(firstObjectFlag, secondObjectFlag);
            SetResult            result     = new SetResult(results, objectFlag);

            return(result);
        }
Esempio n. 29
0
            protected void SetValue(
                IXmlNode parentNode,
                string childName,
                object oldValue,
                object newValue,
                SetResult expectedResult
                )
            {
                var    cursor = SelectChild(parentNode, childName);
                var    node   = cursor as IXmlNode;
                var    value  = newValue as object;
                object token;

                var proceed = Manager.OnAssigningValue(node, oldValue, ref value, out token);

                switch (expectedResult)
                {
                case SetResult.ProceedUntracked:
                    Assert.True(proceed);
                    Assert.AreEqual(newValue, value);
                    Assert.IsNull(token);
                    break;

                case SetResult.ProceedTracked:
                    Assert.True(proceed);
                    Assert.AreEqual(newValue, value);
                    Assert.NotNull(token);
                    Manager.OnAssignedValue(node, value, value, token);
                    break;

                case SetResult.Return:
                    Assert.False(proceed);
                    Assert.AreEqual(newValue, value);
                    Assert.IsNull(token);
                    break;
                }
            }
Esempio n. 30
0
 private void SetResultfun(string result, int count)
 {
     if (this.Disposing)
     {
         return;
     }
     if (textBox1.InvokeRequired)
     {
         try
         {
             SetResult d = new SetResult(SetResultfun);
             this.Invoke(d, new object[] { result, count });
         }
         catch (Exception) { }
     }
     else
     {
         textBox1.Text += string.Format(result + "\r\n");
         textBox1.Select(textBox1.Text.Length - 1, textBox1.Text.Length - 1);
         textBox1.ScrollToCaret();
         toolStripStatusLabel1.Text = count + " پیامک در مجموع ارسال شد";
         this.Text = " عملیات ارسال اس ام اس " + count.ToString() + " از " + datarows.RowCount.ToString();
     }
 }
Esempio n. 31
0
        protected virtual void OnSetResult(object resObject)
        {
            SelectedObject = resObject;
            var ea = new SetResultEventArgs {
                ResultPars = CtrlsProc.PrepareParams(resObject, null, ResultMap),
                Handled    = false
            };

            SetResult?.Invoke(this, ea);
            SelectedValues = ea.ResultPars;
            if (!ea.Handled)
            {
                CtrlsProc.SetValues(TargetObject, SelectedValues);
                if (TargetObject is DataRow)
                {
                    (TargetObject as DataRow).EndEdit();
                }
                if (TargetObject is BindingSource)
                {
                    (TargetObject as BindingSource).EndEdit();
                }
            }
            AfterSetResult?.Invoke(this, new EventArgs());
        }
Esempio n. 32
0
 public PropertyHandler(GetResult get, SetResult set)
 {
     _get = get;
     _set = set;
 }
			protected void SetValue(IXmlNode parentNode, string childName, object oldValue, object newValue, SetResult expectedResult)
			{
				var cursor = SelectChild(parentNode, childName);
				var node   = cursor as IXmlNode;
				var value  = newValue as object;
				object token;

				var proceed = Manager.OnAssigningValue(node, oldValue, ref value, out token);

				switch (expectedResult)
				{
					case SetResult.ProceedUntracked:
						Assert.True(proceed);
						Assert.AreEqual(newValue, value);
						Assert.IsNull(token);
						break;

					case SetResult.ProceedTracked:
						Assert.True(proceed);
						Assert.AreEqual(newValue, value);
						Assert.NotNull(token);
						Manager.OnAssignedValue(node, value, value, token);
						break;

					case SetResult.Return:
						Assert.False(proceed);
						Assert.AreEqual(newValue, value);
						Assert.IsNull(token);
						break;
				}
			}
Esempio n. 34
0
        public ActionResult CompletedChallenges_Read([DataSourceRequest]DataSourceRequest request)
        {
            /* To get the challenges that the current user is participating in,
             * first find all ChallengePlayer objects associated with that user.
             * Next, loop through the ChallengePlayer objects to get the challenges
             * associated with them.
             */

            // get the current user that is logged in
            string userID = User.Identity.GetUserId();
            int id = System.Convert.ToInt32(userID);
            Users.User user = Users.User.Load(id);

            // get all ChallengePlayer objects for current user
            ChallengePlayerCollection challengePlayers = ChallengePlayerCollection.LoadByPlayer(user);

            Dictionary<Challenge, SetResultCollection> challengesSetResPairs = new Dictionary<Challenge, SetResultCollection>();

            foreach (ChallengePlayer cp in challengePlayers)
            {
                if (cp.Challenge.StatusId == 3) //completed
                {
                    challengesSetResPairs.Add(cp.Challenge, SetResultCollection.LoadByChallenge(cp.Challenge));
                }

            }
            SetResult defaultSR = new SetResult() { SetNum = 0, Score = 0, TieBreak = 0 };
            DataSourceResult result = challengesSetResPairs.ToDataSourceResult(request, challengeSetRes => new CompletedChallengesViewModel
            {
                ChallengeId = challengeSetRes.Key.Id,
                ChallengeName = "Challenge " + challengeSetRes.Key.Id,

                // will need to change for doubles capability
                OpponentName = ChallengePlayerCollection.LoadByChallenge(challengeSetRes.Key)
                                    .Where(cp => cp.PlayerId != user.Id).First().Player.FirstName + " " +
                               ChallengePlayerCollection.LoadByChallenge(challengeSetRes.Key)
                                    .Where(cp => cp.PlayerId != user.Id).First().Player.LastName,

                LadderName = challengeSetRes.Key.Ladder.Name,
                FacilityName = challengeSetRes.Key.Facility.FullName,
                CourtName = challengeSetRes.Key.Court.Name,
                MatchType = challengeSetRes.Key.MatchType.Type,
                MatchFormat = challengeSetRes.Key.MatchFormat.Format,
                numSets = challengeSetRes.Key.MatchFormat.NumSets,
                MatchDateTime = challengeSetRes.Key.MatchDateTime.ToString("dd MMMM yyyy, HH:mm"),

                // will need to change for doubles capability
                PlayerPointsAwarded = ChallengePlayerCollection.LoadByChallenge(challengeSetRes.Key)
                                            .Where(p => p.PlayerId == user.Id).First().PointsAwarded,
                OpponentPointsAwarded = ChallengePlayerCollection.LoadByChallenge(challengeSetRes.Key)
                                            .Where(p => p.PlayerId != user.Id).First().PointsAwarded,

                PlayerSet1Score = challengeSetRes.Value.Where(sr => sr.PlayerId == user.Id).Where(sr => sr.SetNum == 1).DefaultIfEmpty(defaultSR).First().Score,
                PlayerSet2Score = challengeSetRes.Value.Where(sr => sr.PlayerId == user.Id).Where(sr => sr.SetNum == 2).DefaultIfEmpty(defaultSR).First().Score,
                PlayerSet3Score = challengeSetRes.Value.Where(sr => sr.PlayerId == user.Id).Where(sr => sr.SetNum == 3).DefaultIfEmpty(defaultSR).First().Score,
                PlayerSet4Score = challengeSetRes.Value.Where(sr => sr.PlayerId == user.Id).Where(sr => sr.SetNum == 4).DefaultIfEmpty(defaultSR).First().Score,
                PlayerSet5Score = challengeSetRes.Value.Where(sr => sr.PlayerId == user.Id).Where(sr => sr.SetNum == 5).DefaultIfEmpty(defaultSR).First().Score,

                OpponentSet1Score = challengeSetRes.Value.Where(sr => sr.PlayerId != user.Id).Where(sr => sr.SetNum == 1).DefaultIfEmpty(defaultSR).First().Score,
                OpponentSet2Score = challengeSetRes.Value.Where(sr => sr.PlayerId != user.Id).Where(sr => sr.SetNum == 2).DefaultIfEmpty(defaultSR).First().Score,
                OpponentSet3Score = challengeSetRes.Value.Where(sr => sr.PlayerId != user.Id).Where(sr => sr.SetNum == 3).DefaultIfEmpty(defaultSR).First().Score,
                OpponentSet4Score = challengeSetRes.Value.Where(sr => sr.PlayerId != user.Id).Where(sr => sr.SetNum == 4).DefaultIfEmpty(defaultSR).First().Score,
                OpponentSet5Score = challengeSetRes.Value.Where(sr => sr.PlayerId != user.Id).Where(sr => sr.SetNum == 5).DefaultIfEmpty(defaultSR).First().Score,
            });

            return Json(result);
        }
Esempio n. 35
0
        public ActionResult InputResults_Update([DataSourceRequest]DataSourceRequest request, ScheduledChallengesViewModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                string userID = User.Identity.GetUserId();
                int id = System.Convert.ToInt32(userID);
                Users.User user = Users.User.Load(id);

                bool playerWinner = true;
                bool tie = false;

                IEnumerable<ChallengePlayer> challengePlayers = ChallengePlayerCollection.LoadAll().Where(p => p.ChallengeId == model.ChallengeId);

                ChallengePlayer userChallengePlayer = challengePlayers.Where(p => p.PlayerId == user.Id).First();
                ChallengePlayer opponentChallengePlayer = challengePlayers.Where(p => p.PlayerId != user.Id).First();

                Challenge challenge = Challenge.LoadById(model.ChallengeId);

                Ladder ladder = Ladder.LoadById(challenge.LadderId);

                LadderPlayer userLadderPlayer = LadderPlayerCollection.LoadByPlayer(user).Where(p => p.LadderId == ladder.Id).First();
                LadderPlayer opponentLadderPlayer = LadderPlayerCollection.LoadByPlayer(opponentChallengePlayer.Player).Where(p => p.LadderId == ladder.Id).First();

                MatchFormat matchFormat = MatchFormatCollection.LoadAll().Where(p => p.Format == model.MatchFormat).First();

                LadderPoints userLadderPoints = LadderPointsCollection.LoadByRating(user.PlayerRating).Where(p => p.LadderId == ladder.Id).First();
                LadderPoints opponentLadderPoints = LadderPointsCollection.LoadByRating(opponentChallengePlayer.Player.PlayerRating).Where(p => p.LadderId == ladder.Id).First();

                SetResult playerSet1 = new SetResult()
                {
                    ChallengeId = model.ChallengeId,
                    PlayerId = user.Id,
                    SetNum = 1,
                    Score = model.PlayerSet1Score,
                };

                SetResult playerSet2 = new SetResult()
                {
                    ChallengeId = model.ChallengeId,
                    PlayerId = user.Id,
                    SetNum = 2,
                    Score = model.PlayerSet2Score,

                };

                SetResult playerSet3 = new SetResult()
                {
                    ChallengeId = model.ChallengeId,
                    PlayerId = user.Id,
                    SetNum = 3,
                    Score = model.PlayerSet3Score,
                };

                SetResult opponentSet1 = new SetResult()
                {
                    ChallengeId = model.ChallengeId,
                    PlayerId = opponentChallengePlayer.PlayerId,
                    SetNum = 1,
                    Score = model.OpponentSet1Score,
                };

                SetResult opponentSet2 = new SetResult()
                {
                    ChallengeId = model.ChallengeId,
                    PlayerId = opponentChallengePlayer.PlayerId,
                    SetNum = 2,
                    Score = model.OpponentSet2Score,
                };

                SetResult opponentSet3 = new SetResult()
                {
                    ChallengeId = model.ChallengeId,
                    PlayerId = opponentChallengePlayer.PlayerId,
                    SetNum = 3,
                    Score = model.OpponentSet3Score,
                };

                playerSet1.Save();
                playerSet2.Save();
                playerSet3.Save();
                opponentSet1.Save();
                opponentSet2.Save();
                opponentSet3.Save();

                int playerWins = 0;
                int opponentWins = 0;

                if (playerSet1.Score > opponentSet1.Score)
                {
                    playerWins++;
                }
                else
                {
                    if (playerSet1.Score == opponentSet1.Score)
                    {

                    }
                    else
                    {
                        opponentWins++;
                    }

                }

                if (playerSet2.Score > opponentSet2.Score)
                {
                    playerWins++;
                }
                else
                {
                    if (playerSet2.Score == opponentSet2.Score)
                    {

                    }
                    else
                    {
                        opponentWins++;
                    }

                }

                if (playerWins != 2 || opponentWins != 2)
                {
                    if (playerSet3.Score > opponentSet3.Score)
                    {
                        playerWins++;
                        if (matchFormat.NumSets == 3)
                        {
                            playerWinner = true;
                        }
                    }
                    else
                    {
                        if (playerSet3.Score == opponentSet3.Score)
                        {

                        }
                        else
                        {
                            opponentWins++;
                            if (matchFormat.NumSets == 3)
                            {
                                playerWinner = false;
                            }
                        }
                    }
                }
                else
                {
                    if (playerWins == 2 && matchFormat.NumSets == 3)
                    {
                        playerWinner = true;
                    }
                    if (opponentWins == 2 && matchFormat.NumSets == 3)
                    {
                        playerWinner = false;
                    }
                    if (playerSet3.Score > opponentSet3.Score && matchFormat.NumSets != 3)
                    {
                        playerWins++;
                        if (playerWins == 3)
                        {
                            playerWinner = true;
                        }
                    }
                    else
                    {
                        if (playerSet3.Score == opponentSet3.Score)
                        {

                        }
                        else
                        {
                            opponentWins++;
                            if (opponentWins == 3)
                            {
                                playerWinner = false;
                            }
                        }

                    }
                }

                if (matchFormat.NumSets == 5)
                {
                    SetResult playerSet4 = new SetResult()
                    {
                        ChallengeId = model.ChallengeId,
                        PlayerId = user.Id,
                        SetNum = 4,
                        Score = model.PlayerSet4Score,
                    };

                    SetResult playerSet5 = new SetResult()
                    {
                        ChallengeId = model.ChallengeId,
                        PlayerId = user.Id,
                        SetNum = 5,
                        Score = model.PlayerSet5Score,
                    };

                    SetResult opponentSet4 = new SetResult()
                    {
                        ChallengeId = model.ChallengeId,
                        PlayerId = opponentChallengePlayer.PlayerId,
                        SetNum = 4,
                        Score = model.OpponentSet4Score,
                    };

                    SetResult opponentSet5 = new SetResult()
                    {
                        ChallengeId = model.ChallengeId,
                        PlayerId = opponentChallengePlayer.PlayerId,
                        SetNum = 5,
                        Score = model.OpponentSet5Score,
                    };

                    playerSet4.Save();
                    playerSet5.Save();
                    opponentSet4.Save();
                    opponentSet5.Save();

                    if (playerSet4.Score > opponentSet4.Score)
                    {
                        playerWins++;
                        if (playerWins == 3)
                        {
                            playerWinner = true;
                        }

                    }
                    else
                    {
                        if (playerSet4.Score == opponentSet4.Score)
                        {

                        }
                        else
                        {
                            opponentWins++;
                            if (opponentWins == 3)
                            {
                                playerWinner = false;
                            }
                        }
                    }

                    if (playerWins != 3 && opponentWins != 3)
                    {
                        if (playerSet5.Score > opponentSet5.Score)
                        {
                            playerWinner = true;
                        }
                        else
                        {
                            if (playerSet5.Score == opponentSet5.Score)
                            {
                                tie = true;
                            }
                            else
                            {
                                playerWinner = false;
                            }
                        }
                    }

                }

                if (!tie)
                {

                    if (playerWinner)
                    {
                        userLadderPlayer.ChallengesWon++;
                        opponentLadderPlayer.ChallengesLost++;
                        if (userLadderPlayer.PlayerRank > opponentLadderPlayer.PlayerRank)
                        {
                            userLadderPlayer.PreviousPoints = userLadderPlayer.PlayerPoints;
                            userLadderPlayer.PlayerPoints += userLadderPoints.ExpectedWinPoints;
                            opponentLadderPlayer.PreviousPoints = opponentLadderPlayer.PlayerPoints;
                            opponentLadderPlayer.PlayerPoints -= opponentLadderPoints.ExpectedLossPoints;
                            if (opponentLadderPlayer.PlayerPoints < 0)
                            {
                                opponentLadderPlayer.PlayerPoints = 0;
                            }
                        }
                        else
                        {
                            userLadderPlayer.PreviousPoints = userLadderPlayer.PlayerPoints;
                            userLadderPlayer.PlayerPoints += userLadderPoints.UnexpectedWinPoints;
                            opponentLadderPlayer.PreviousPoints = opponentLadderPlayer.PlayerPoints;
                            opponentLadderPlayer.PlayerPoints -= opponentLadderPoints.UnexpectedLossPoints;
                            if (opponentLadderPlayer.PlayerPoints < 0)
                            {
                                opponentLadderPlayer.PlayerPoints = 0;
                            }
                        }
                    }
                    else
                    {
                        userLadderPlayer.ChallengesLost++;
                        opponentLadderPlayer.ChallengesWon++;
                        if (userLadderPlayer.PlayerRank > opponentLadderPlayer.PlayerRank)
                        {
                            userLadderPlayer.PreviousPoints = userLadderPlayer.PlayerPoints;
                            userLadderPlayer.PlayerPoints -= userLadderPoints.UnexpectedLossPoints;
                            opponentLadderPlayer.PreviousPoints = opponentLadderPlayer.PlayerPoints;
                            opponentLadderPlayer.PlayerPoints += opponentLadderPoints.UnexpectedWinPoints;
                            if (userLadderPlayer.PlayerPoints < 0)
                            {
                                userLadderPlayer.PlayerPoints = 0;
                            }
                        }
                        else
                        {
                            userLadderPlayer.PreviousPoints = userLadderPlayer.PlayerPoints;
                            userLadderPlayer.PlayerPoints -= userLadderPoints.ExpectedLossPoints;
                            opponentLadderPlayer.PreviousPoints = opponentLadderPlayer.PlayerPoints;
                            opponentLadderPlayer.PlayerPoints += opponentLadderPoints.ExpectedWinPoints;
                            if (userLadderPlayer.PlayerPoints < 0)
                            {
                                userLadderPlayer.PlayerPoints = 0;
                            }
                        }
                    }

                }

                userLadderPlayer.Save();
                opponentLadderPlayer.Save();

                IEnumerable<LadderPlayer> AllLadPlayers = LadderPlayerCollection.LoadByLadder(ladder)
                                                            .OrderByDescending(lp => lp.PlayerPoints)
                                                            .ThenByDescending(lp => (lp.PlayerPoints - lp.PreviousPoints));
                int rank = 1;
                foreach (LadderPlayer lp in AllLadPlayers)
                {
                    lp.PlayerRank = rank;
                    lp.Save();
                    rank++;
                }

                challenge.Status = ChallengeStatusCollection.LoadAll().Where(p => p.Status == "completed").First();

                challenge.Save();

            }

            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }