/// <summary>
        /// The next.
        /// </summary>
        /// <param name="criterion">
        /// The criterion.
        /// </param>
        /// <returns>
        /// The <see cref="double"/>.
        /// </returns>
        public override double Next(Criterion.Criterion criterion)
        {
            if (rightBound - leftBound > Precision)
            {
                double criterionDistortion = criterion.Distortion();
                if (lastDistortion > criterionDistortion)
                {
                    Value = current;
                    lastDistortion = criterionDistortion;
                }

                current = (rightBound + leftBound) / 2.0;

                if (criterionDistortion < 0)
                {
                    leftBound = current;
                }
                else
                {
                    rightBound = current;
                }

                return current;
            }

            return -1;
        }
Ejemplo n.º 2
0
 public void SutIsEquatable()
 {
     var sut = new Criterion<string>(
         "ploeh",
         new DelegatingEqualityComparer<string>());
     Assert.IsAssignableFrom<IEquatable<string>>(sut);
 }
Ejemplo n.º 3
0
        public EdgeReorderer(List<Edge> origEdges, Criterion c) {
            EdgeOrientations = new List<Side>();
            Edges = new List<Edge>();

            if (origEdges.Count > 0) {
                ReorderEdges(origEdges, c);
            }
        }
        public void add_criteria_criterion_with_successfully()
        {
            var criterion = new Criterion();
            var dateBirthdaySpecificarion = new PatientDateBirthdayEqualsSpecification();
            dateBirthdaySpecificarion.AddCriteria(new Patient() { DateBirthday = DateTime.Now }, criterion);

            Assert.AreEqual(criterion.criterions.Count(), 1);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of an object.
 /// </summary>
 /// <param name="copyFrom">Criterion to copy state from.</param>
 public Criterion(Criterion copyFrom)
 {
     if (copyFrom != null)
     {
         this.Name = copyFrom.Name;
         this.Value = copyFrom.Value;
     }
 }
Ejemplo n.º 6
0
 public void TargetIsCorrect(int expected)
 {
     var sut = new Criterion<int>(
         expected,
         new DelegatingEqualityComparer<int>());
     var actual = sut.Target;
     Assert.Equal(expected, actual);
 }
Ejemplo n.º 7
0
        public void add_criteria_criterion_with_successfully()
        {
            var criterion = new Criterion();
            var nameEqualsSpecification = new PatientNameEqualsSpecification();
            nameEqualsSpecification.AddCriteria(new Patient() { Name = "test" }, criterion);

            Assert.AreEqual(criterion.criterions.Count(), 1);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the keyword.
        /// </param>
        /// <param name="keywordId">Id of the keyword to be updated.</param>
        public void Run(AdWordsUser user, long adGroupId, long keywordId)
        {
            // Get the AdGroupCriterionService.
              AdGroupCriterionService adGroupCriterionService =
              (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService);

              // Since we are not updating any keyword-specific fields, it is enough to
              // create a criterion object.
              Criterion criterion = new Criterion();
              criterion.id = keywordId;

              // Create ad group criterion.
              BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
              biddableAdGroupCriterion.adGroupId = adGroupId;
              biddableAdGroupCriterion.criterion = criterion;

              // Create the bids.
              BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
              CpcBid cpcBid = new CpcBid();
              cpcBid.bid = new Money();
              cpcBid.bid.microAmount = 1000000;
              biddingConfig.bids = new Bids[] {cpcBid};

              biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

              // Create the operation.
              AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
              operation.@operator = Operator.SET;
              operation.operand = biddableAdGroupCriterion;

              try {
            // Update the keyword.
            AdGroupCriterionReturnValue retVal =
            adGroupCriterionService.mutate(new AdGroupCriterionOperation[] {operation});

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              AdGroupCriterion adGroupCriterion = retVal.value[0];
              long bidAmount = 0;
              foreach (Bids bids in (adGroupCriterion as BiddableAdGroupCriterion).
              biddingStrategyConfiguration.bids) {
            if (bids is CpcBid) {
              bidAmount = (bids as CpcBid).bid.microAmount;
              break;
            }
              }

              Console.WriteLine("Keyword with ad group id = '{0}', id = '{1}' was updated with " +
              "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
              adGroupCriterion.criterion.id, bidAmount);
            } else {
              Console.WriteLine("No keyword was updated.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to update keyword.", e);
              }
        }
Ejemplo n.º 9
0
        private void ReorderEdges(List<Edge> edges, Criterion c) {
            var n = edges.Count;
            var done = new List<bool>();
            for (int i = 0; i < n; i++) {
                done.Add(false);
            }
            var newEdges = new List<Edge>();
            var edge = edges.First();
            newEdges.Add(edge);
            EdgeOrientations.Add(LR.Side.Left);

            ICoord firstPoint, lastPoint;
            if (!GetPoints(edge, c, out firstPoint, out lastPoint)) {
                return;
            }
            if (firstPoint == Vertex.VertexAtInfinity || lastPoint == Vertex.VertexAtInfinity) {
                return;
            }

            done[0] = true;
            var nDone = 1;
            while (nDone < n) {
                for (int i = 1; i < n; i++) {
                    if ( done[i]) continue;

                    edge = edges[i];
                    ICoord leftPoint, rightPoint;
                    if (!GetPoints(edge, c, out leftPoint, out rightPoint)) return;

                    if (leftPoint == lastPoint) {
                        lastPoint = rightPoint;
                        EdgeOrientations.Add(LR.Side.Left);
                        newEdges.Add(edge);
                        done[i] = true;
                    } else if (rightPoint == firstPoint) {
                        firstPoint = leftPoint;
                        EdgeOrientations.Insert(0, LR.Side.Left);
                        newEdges.Insert(0, edge);
                        done[i] = true;
                    } else if (leftPoint == firstPoint) {
                        firstPoint = rightPoint;
                        EdgeOrientations.Insert(0, LR.Side.Right);
                        newEdges.Insert(0, edge);
                        done[i] = true;
                    } else if (rightPoint == lastPoint) {
                        lastPoint = leftPoint;
                        EdgeOrientations.Add(LR.Side.Right);
                        newEdges.Add(edge);
                        done[i] = true;
                    }
                    if (done[i]) {
                        ++nDone;
                    }
                }
            }
            Edges = newEdges;
        }
Ejemplo n.º 10
0
        public void ComparerIsCorrect()
        {
            var expected = new DelegatingEqualityComparer<decimal>();
            var sut = new Criterion<decimal>(1337m, expected);

            var actual = sut.Comparer;

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 11
0
 public void Add(Criterion criterion)
 {
     if (!IsNamedQuery())
     {
         _criteria.Add(criterion);
     }
     else
         throw new ApplicationException(
             "You cannot add additionalcriteria to named queries");
 }
Ejemplo n.º 12
0
        public void SutEqualsIdenticalValue()
        {
            var target = Guid.NewGuid();
            var comparer = new DelegatingEqualityComparer<Guid>();
            var sut = new Criterion<Guid>(target, comparer);

            var other = new Criterion<Guid>(target, comparer);
            var actual = sut.Equals(other);

            Assert.True(actual, "Expected structural equality to hold.");
        }
        /// <summary>
        /// The next.
        /// </summary>
        /// <param name="criterion">
        /// The criterion.
        /// </param>
        /// <returns>
        /// The <see cref="double"/>.
        /// </returns>
        public override double Next(Criterion.Criterion criterion)
        {
            if (current > leftBound)
            {
                current = rightBound;
                rightBound = rightBound - step;
                return current;
            }

            return -1;
        }
Ejemplo n.º 14
0
        void ProcessStep(Step step, Criterion criterion, ScenarioContext scenarioContext,
            IExecutionContextFactory executionContextFactory)
        {
            dynamic executionContext = executionContextFactory.Create(scenarioContext.Scenario, step);

            _progressReporter.Report(new StepStartedReport(scenarioContext.Scenario.ScenarioId, criterion.CriterionId,
                step.StepId, executionContext.ExecutionContextId));

            StepExecutionResult result = executionContext.Execute(step as dynamic, scenarioContext);

            _progressReporter.Report(new StepStoppedReport(scenarioContext.Scenario.ScenarioId, criterion.CriterionId,
                step.StepId, executionContext.ExecutionContextId, result));
        }
Ejemplo n.º 15
0
        public void Run(Criterion criterion, ScenarioContext scenarioContext,
            IExecutionContextFactory executionContextFactory)
        {
            _progressReporter.Report(new CriterionStartedReport(scenarioContext.Scenario.ScenarioId,
                criterion.CriterionId));

            foreach (Step step in criterion.Steps)
            {
                ProcessStep(step, criterion, scenarioContext, executionContextFactory);
            }

            _progressReporter.Report(new CriterionStoppedReport(scenarioContext.Scenario.ScenarioId,
                criterion.CriterionId));
        }
Ejemplo n.º 16
0
        public void Should_compose_expressions_using_OR()
        {
            var criterion = new Criterion {
                FieldName = "foo",
                Values = new[] {
                    new CriterionFieldValue { RawValue = "bar" },
                    new CriterionFieldValue { RawValue = "foo", Modifier = FieldValueModifier.BooleanOr }
                }
            };

            var expression = new DefaultValueHandler().CreateExpression<MyEntity>(criterion);
            Assert.That(expression.Compile()(new MyEntity { Foo = "bar" }), Is.True);

            expression = new DefaultValueHandler().CreateExpression<MyEntity>(criterion);
            Assert.That(expression.Compile()(new MyEntity { Foo = "foo" }), Is.True);
        }
 /// <summary>
 /// Initializes a new instance of the ExtraTreeRegressor class.
 /// </summary>
 /// <param name="criterion"> The function to measure the quality of a split. The only supported
 /// criterion is <see cref="Criterion.Mse"/> for the mean squared error.</param>
 /// <param name="splitter">The strategy used to choose the split at each node. Supported
 /// strategies are <see cref="Splitter.Best"/> to choose the best split and <see cref="Splitter.Random"/> to choose
 /// the best random split.</param>
 /// <param name="maxDepth">The maximum depth of the tree. If <c>null</c>, then nodes are expanded until
 /// all leaves are pure or until all leaves contain less than
 /// <paramref name="minSamplesSplit"/> samples.</param>
 /// <param name="minSamplesSplit">The minimum number of samples required to split an internal node.</param>
 /// <param name="minSamplesLeaf">The minimum number of samples required to be at a leaf node.</param>
 /// <param name="maxFeatures">Number of features to consider when looking for the best split. If null - 
 /// then all features will be considered.</param>
 /// <param name="random">random number generator</param>
 public ExtraTreeRegressor(
     Criterion criterion = Criterion.Mse,
     Splitter splitter = Splitter.Random,
     int? maxDepth = null,
     int minSamplesSplit = 2,
     int minSamplesLeaf = 1,
     MaxFeaturesChoice maxFeatures = null,
     Random random = null) : base(criterion,
                                  splitter,
                                  maxDepth,
                                  minSamplesSplit,
                                  minSamplesLeaf,
                                  maxFeatures ?? MaxFeaturesChoice.Auto(),
                                  random)
 {
 }
Ejemplo n.º 18
0
        public void doSearchTest()
        {
            Station target = CreateTestStation();

            Criterion c1 = new Criterion("F1", "EQ", "V1");
            Criterion c2 = new Criterion("F2", "EQ", "V2");
            Criterion c3 = new Criterion("F1", "GT", "V3");

            ICollection<Criterion> crit = new List<Criterion>();
            crit.Add(c1);
            crit.Add(c2);
            crit.Add(c3);

            InstanceRefList actual;
            actual = target.DoSearch(crit);
            Assert.IsTrue(actual.List.Count > 1);
        }
Ejemplo n.º 19
0
        public void getCriterionByFieldTest()
        {
            Criterion c1 = new Criterion("F1", "EQ", "V1");
            Criterion c2 = new Criterion("F2", "EQ", "V2");
            Criterion c3 = new Criterion("F1", "GT", "V3");

            ICollection<Criterion> crit = new List<Criterion>();
            crit.Add(c1);
            crit.Add(c2);
            crit.Add(c3);

            string field = "F1";
            List<Criterion> crit2 = Criterion.GetCriteriaByField(crit, field);
            Criterion actual = crit2[0];
            Assert.AreEqual("V1", actual.Value);
            Assert.IsFalse(actual.IsUnaryOperator());
            Assert.AreEqual(2, crit2.Count);
        }
Ejemplo n.º 20
0
        public void EqualsReturnsComparerResult(
            string target,
            string candidate,
            bool expected)
        {
            var comparer = new DelegatingEqualityComparer<string>
            {
                OnEquals = (x, y) =>
                {
                    Assert.Equal(target, x);
                    Assert.Equal(candidate, y);
                    return expected;
                }
            };
            var sut = new Criterion<string>(target, comparer);

            var actual = sut.Equals(candidate);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 21
0
        public void Should_evaluate_complex_expression()
        {
            var criterion = new Criterion {
                FieldName = "bar",
                Values = new[] {
                    new CriterionFieldValue { RawValue = "6", Operator = FieldValueOperator.NotEqual },
                    new CriterionFieldValue { RawValue = "5", Operator = FieldValueOperator.Equal },
                    new CriterionFieldValue { RawValue = "4", Operator = FieldValueOperator.GreaterThan },
                    new CriterionFieldValue { RawValue = "0", Operator = FieldValueOperator.LessThan, Modifier = FieldValueModifier.BooleanOr}
                }
            };

            var expression = new DefaultValueHandler().CreateExpression<MyEntity>(criterion);
            Assert.That(expression.Compile()(new MyEntity { Bar = 6 }), Is.False);

            expression = new DefaultValueHandler().CreateExpression<MyEntity>(criterion);
            Assert.That(expression.Compile()(new MyEntity { Bar = 5 }), Is.True);

            expression = new DefaultValueHandler().CreateExpression<MyEntity>(criterion);
            Assert.That(expression.Compile()(new MyEntity { Bar = -1 }), Is.True);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the keyword.
        /// </param>
        /// <param name="keywordId">Id of the keyword to be removed.</param>
        public void Run(AdWordsUser user, long adGroupId, long keywordId)
        {
            // Get the AdGroupCriterionService.
              AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(
              AdWordsService.v201601.AdGroupCriterionService);

              // Create base class criterion to avoid setting keyword-specific fields.
              Criterion criterion = new Criterion();
              criterion.id = keywordId;

              // Create the ad group criterion.
              BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
              adGroupCriterion.adGroupId = adGroupId;
              adGroupCriterion.criterion = criterion;

              // Create the operation.
              AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
              operation.operand = adGroupCriterion;
              operation.@operator = Operator.REMOVE;

              try {
            // Remove the keyword.
            AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
            new AdGroupCriterionOperation[] {operation});

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              AdGroupCriterion removedKeyword = retVal.value[0];
              Console.WriteLine("Keyword with ad group id = \"{0}\" and id = \"{1}\" was removed.",
              removedKeyword.adGroupId, removedKeyword.criterion.id);
            } else {
              Console.WriteLine("No keywords were removed.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to remove keyword.", e);
              }
        }
Ejemplo n.º 23
0
 private bool compareCriterionIds(Criterion criterion)
 {
     return(criterion.ID.Equals(currentlyProcessedCriterionId));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which experiments are
        /// added.</param>
        /// <param name="adGroupId">Id of the ad group to which experiments are
        /// added.</param>
        /// <param name="criterionId">Id of the criterion for which experiments
        /// are added.</param>
        public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId)
        {
            // Get the ExperimentService.
              ExperimentService experimentService =
              (ExperimentService) user.GetService(AdWordsService.v201601.ExperimentService);

              // Get the AdGroupService.
              AdGroupService adGroupService =
              (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService);

              // Get the AdGroupCriterionService.
              AdGroupCriterionService adGroupCriterionService =
              (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService);

              // Create the experiment.
              Experiment experiment = new Experiment();
              experiment.campaignId = campaignId;
              experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
              experiment.queryPercentage = 10;
              experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss");

              // Optional: Set the end date.
              experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss");

              // Optional: Set the status.
              experiment.status = ExperimentStatus.ENABLED;

              // Create the operation.
              ExperimentOperation experimentOperation = new ExperimentOperation();
              experimentOperation.@operator = Operator.ADD;
              experimentOperation.operand = experiment;

              try {
            // Add the experiment.
            ExperimentReturnValue experimentRetVal = experimentService.mutate(
            new ExperimentOperation[] {experimentOperation});

            // Display the results.
            if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value.
            Length > 0) {
              long experimentId = 0;

              Experiment newExperiment = experimentRetVal.value[0];

              Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n",
              newExperiment.name, newExperiment.id);
              experimentId = newExperiment.id;

              // Set ad group for the experiment.
              AdGroup adGroup = new AdGroup();
              adGroup.id = adGroupId;

              // Create experiment bid multiplier rule that will modify ad group bid
              // for the experiment.
              ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier =
              new ManualCPCAdGroupExperimentBidMultipliers();
              adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier();
              adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5;

              // Set experiment data to the ad group.
              AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData();
              adGroupExperimentData.experimentId = experimentId;
              adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
              adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier;

              adGroup.experimentData = adGroupExperimentData;

              // Create the operation.
              AdGroupOperation adGroupOperation = new AdGroupOperation();
              adGroupOperation.operand = adGroup;
              adGroupOperation.@operator = Operator.SET;

              // Update the ad group.
              AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] {
              adGroupOperation});

              // Display the results.
              if (adGroupRetVal != null && adGroupRetVal.value != null &&
              adGroupRetVal.value.Length > 0) {
            AdGroup updatedAdGroup = adGroupRetVal.value[0];
            Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " +
                "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id,
                updatedAdGroup.status);
              } else {
            Console.WriteLine("No ad groups were updated.");
              }

              // Set ad group criteria for the experiment.
              Criterion criterion = new Criterion();
              criterion.id = criterionId;

              BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
              adGroupCriterion.adGroupId = adGroupId;
              adGroupCriterion.criterion = criterion;

              // Create experiment bid multiplier rule that will modify criterion bid
              // for the experiment.
              ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier =
              new ManualCPCAdGroupCriterionExperimentBidMultiplier();
              bidMultiplier.maxCpcMultiplier = new BidMultiplier();
              bidMultiplier.maxCpcMultiplier.multiplier = 1.5;

              // Set experiment data to the criterion.
              BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData =
              new BiddableAdGroupCriterionExperimentData();
              adGroupCriterionExperimentData.experimentId = experimentId;
              adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
              adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier;

              adGroupCriterion.experimentData = adGroupCriterionExperimentData;

              // Create the operation.
              AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
              adGroupCriterionOperation.operand = adGroupCriterion;
              adGroupCriterionOperation.@operator = Operator.SET;

              // Update the ad group criteria.
              AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate(
              new AdGroupCriterionOperation[] {adGroupCriterionOperation});

              // Display the results.
              if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null &&
              adGroupCriterionRetVal.value.Length > 0) {
            AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0];
            Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = "
                + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n",
                updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id,
                updatedAdGroupCriterion.criterion.CriterionType);
              } else {
            Console.WriteLine("No ad group criteria were updated.");
              }
            } else {
              Console.WriteLine("No experiments were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add experiment.", e);
              }
        }
Ejemplo n.º 25
0
        public void SutDoesNotEqualOtherWhenComparerDiffers(string target)
        {
            var sut = new Criterion<string>(
                target,
                new DelegatingEqualityComparer<string>());

            var other = new Criterion<string>(
                target,
                new DelegatingEqualityComparer<string>());
            var actual = sut.Equals(other);

            Assert.False(
                actual,
                "SUT shouldn't equal other with different comparer.");
        }
 private static string AddFilterClauseFrom(Criterion criterion)
 {
     return string.Format("{0} {1} @{2} ", FindTableColumnFor(criterion.PropertyName), FindSQLOperatorFor(criterion.CriteriaOperator), criterion.PropertyName);
 }
Ejemplo n.º 27
0
 private CompareWithAttribute(Func <ValidationContext, IComparable> getComparableValue, Criterion criterion)
 {
     if (!comparingFuncs.TryGetValue(criterion, out var compareFunc))
     {
         throw new ArgumentException("Property with this name not found");
     }
     GetComparableValue = getComparableValue;
     this.criterion     = criterion;
 }
 public List <Enter.Common.DTO.SurveyAnswerDTO> GetList(Criterion criterion = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 29
0
        public static List <LinkItem> CreateLinksForCollection(this IUrlHelper urlHelper, string methodName, Criterion criterion, int totalCount)
        {
            List <LinkItem> links = new List <LinkItem>();

            // self
            links.Add(
                new LinkItem(urlHelper.Link(methodName, new
            {
                pagecount = criterion.PageSize,
                page      = criterion.CurrentPage,
                orderby   = criterion.SortBy
            }), "self", "GET"));

            links.Add(new LinkItem(urlHelper.Link(methodName, new
            {
                pagecount = criterion.PageSize,
                page      = 1,
                orderby   = criterion.SortBy
            }), "first", "GET"));

            links.Add(new LinkItem(urlHelper.Link(methodName, new
            {
                pagecount = criterion.PageSize,
                page      = criterion.GetTotalPages(totalCount),
                orderby   = criterion.SortBy
            }), "last", "GET"));

            if (criterion.HasNext(totalCount))
            {
                links.Add(new LinkItem(urlHelper.Link(methodName, new
                {
                    pagecount = criterion.PageSize,
                    page      = criterion.CurrentPage + 1,
                    orderby   = criterion.SortBy
                }), "next", "GET"));
            }

            if (criterion.HasPrevious())
            {
                links.Add(new LinkItem(urlHelper.Link(methodName, new
                {
                    pagecount = criterion.PageSize,
                    page      = criterion.CurrentPage - 1,
                    orderby   = criterion.SortBy
                }), "previous", "GET"));
            }

            return(links);
        }
Ejemplo n.º 30
0
        private static string AddFilterClauseFrom(Criterion criterion)
        {
            string clip = string.Format("{0} {1} @{2}", FindTableColumnFor(criterion.PropertyName), FindSQLOperatorFor(criterion.CriteriaOperator));

            return(clip);
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which experiments are
    /// added.</param>
    /// <param name="adGroupId">Id of the ad group to which experiments are
    /// added.</param>
    /// <param name="criterionId">Id of the criterion for which experiments
    /// are added.</param>
    public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId) {
      // Get the ExperimentService.
      ExperimentService experimentService =
          (ExperimentService) user.GetService(AdWordsService.v201502.ExperimentService);

      // Get the AdGroupService.
      AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201502.AdGroupService);

      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201502.AdGroupCriterionService);

      // Create the experiment.
      Experiment experiment = new Experiment();
      experiment.campaignId = campaignId;
      experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
      experiment.queryPercentage = 10;
      experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss");

      // Optional: Set the end date.
      experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss");

      // Optional: Set the status.
      experiment.status = ExperimentStatus.ENABLED;

      // Create the operation.
      ExperimentOperation experimentOperation = new ExperimentOperation();
      experimentOperation.@operator = Operator.ADD;
      experimentOperation.operand = experiment;

      try {
        // Add the experiment.
        ExperimentReturnValue experimentRetVal = experimentService.mutate(
            new ExperimentOperation[] {experimentOperation});

        // Display the results.
        if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value.
            Length > 0) {
          long experimentId = 0;

          Experiment newExperiment = experimentRetVal.value[0];

          Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n",
              newExperiment.name, newExperiment.id);
          experimentId = newExperiment.id;

          // Set ad group for the experiment.
          AdGroup adGroup = new AdGroup();
          adGroup.id = adGroupId;

          // Create experiment bid multiplier rule that will modify ad group bid
          // for the experiment.
          ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier =
              new ManualCPCAdGroupExperimentBidMultipliers();
          adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier();
          adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5;

          // Set experiment data to the ad group.
          AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData();
          adGroupExperimentData.experimentId = experimentId;
          adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
          adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier;

          adGroup.experimentData = adGroupExperimentData;

          // Create the operation.
          AdGroupOperation adGroupOperation = new AdGroupOperation();
          adGroupOperation.operand = adGroup;
          adGroupOperation.@operator = Operator.SET;

          // Update the ad group.
          AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] {
              adGroupOperation});

          // Display the results.
          if (adGroupRetVal != null && adGroupRetVal.value != null &&
              adGroupRetVal.value.Length > 0) {
            AdGroup updatedAdGroup = adGroupRetVal.value[0];
            Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " +
                "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id,
                updatedAdGroup.status);
          } else {
            Console.WriteLine("No ad groups were updated.");
          }

          // Set ad group criteria for the experiment.
          Criterion criterion = new Criterion();
          criterion.id = criterionId;

          BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
          adGroupCriterion.adGroupId = adGroupId;
          adGroupCriterion.criterion = criterion;

          // Create experiment bid multiplier rule that will modify criterion bid
          // for the experiment.
          ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier =
              new ManualCPCAdGroupCriterionExperimentBidMultiplier();
          bidMultiplier.maxCpcMultiplier = new BidMultiplier();
          bidMultiplier.maxCpcMultiplier.multiplier = 1.5;

          // Set experiment data to the criterion.
          BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData =
              new BiddableAdGroupCriterionExperimentData();
          adGroupCriterionExperimentData.experimentId = experimentId;
          adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
          adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier;

          adGroupCriterion.experimentData = adGroupCriterionExperimentData;

          // Create the operation.
          AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
          adGroupCriterionOperation.operand = adGroupCriterion;
          adGroupCriterionOperation.@operator = Operator.SET;

          // Update the ad group criteria.
          AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate(
              new AdGroupCriterionOperation[] {adGroupCriterionOperation});

          // Display the results.
          if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null &&
              adGroupCriterionRetVal.value.Length > 0) {
            AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0];
            Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = "
                + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n",
                updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id,
                updatedAdGroupCriterion.criterion.CriterionType);
          } else {
            Console.WriteLine("No ad group criteria were updated.");
          }
        } else {
          Console.WriteLine("No experiments were added.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to add experiment.", e);
      }
    }
Ejemplo n.º 32
0
        private CheckConditionResponse CheckLevelCondition(Level newLevel, Customer customer)
        {
            IEnumerable <Condition> conditions = newLevel.Conditions;
            CheckConditionResponse  response   = new CheckConditionResponse();

            Infrastructure.Querying.Query query = new Infrastructure.Querying.Query();
            Criterion criteria = new Criterion("Customer.ID", customer.ID, CriteriaOperator.Equal);

            query.Add(criteria);
            IEnumerable <Sale> sales = _saleRepository.FindBy(query);

            response.CanEnter = true;

            foreach (Condition condition in conditions)
            {
                // اگر کوئری از نوع هایبرنیت باشد
                if (condition.nHibernate)
                {
                    bool canEnter = _customerRepository.CheckCondition(condition, newLevel, customer);
                    response.CanEnter = response.CanEnter & canEnter;

                    if (!canEnter)
                    {
                        response.ErrorMessages.Add(condition.ErrorText);
                    }
                }
                // اگر کوئری از نوع هایبرنیت نباشد
                else
                {
                    // StatusIsAdameEmkan
                    // وضعیت مرکز تحت پوشش باشد
                    if (condition.QueryText == "CenterStatusIsSupport")
                    {
                        response.CanEnter = customer.Center.StatusKey == "Support" ? true : false;
                        response.ErrorMessages.Add(condition.ErrorText);
                    }
                    // وضعیت مرکز تحت پوشش نباشد
                    if (condition.QueryText == "StatusIsNotSupport")
                    {
                        response.CanEnter = customer.Center.StatusKey == "NotSupport" ? true : false;
                        response.ErrorMessages.Add(condition.ErrorText);
                    }
                    // وضعیت مرکز عدم امکان موقت باشد
                    if (condition.QueryText == "StatusIsAdameEmkan")
                    {
                        response.CanEnter = customer.Center.StatusKey == "AdameEmkan" ? true : false;
                        response.ErrorMessages.Add(condition.ErrorText);
                    }
                    // کالا تحویل نشده نداشته باشد و یا برگشت شده باشد
                    if (condition.QueryText == "HasNoUndeliveredProductsOrAllRollbacked")
                    {
                        foreach (var sale in sales)
                        {
                            foreach (var saleDetail in sale.ProductSaleDetails)
                            {
                                // تحویل نشده ی برگشت نشده فالس است
                                if (!saleDetail.Delivered && !saleDetail.Rollbacked && !saleDetail.IsRollbackDetail)
                                {
                                    response.CanEnter = false;
                                }
                            }
                            //foreach (var saleDetail in sale.CreditSaleDetails)
                            //{
                            //    // تحویل نشده ی برگشت نشده فالس است
                            //    if (!saleDetail.Delivered && !saleDetail.Rollbacked && !saleDetail.IsRollbackDetail)
                            //    {
                            //        response.CanEnter = false;

                            //    }
                            //}
                            //foreach (var saleDetail in sale.UncreditSaleDetails)
                            //{
                            //    // تحویل نشده ی برگشت نشده فالس است
                            //    if (!saleDetail.Delivered && !saleDetail.Rollbacked && !saleDetail.IsRollbackDetail)
                            //    {
                            //        response.CanEnter = false;

                            //    }
                            //}

                            response.ErrorMessages.Add(condition.ErrorText);
                        }
                    }
                    // خدمات اعتباری تحویل نشده نداشته باشد و یا برگشت شده باشد
                    else if (condition.QueryText == "HasNoUndeliveredCreditOrAllRollbacked")
                    {
                        foreach (var sale in sales)
                        {
                            foreach (var saleDetail in sale.CreditSaleDetails)
                            {
                                // تحویل نشده ی برگشت نشده فالس است
                                if (!saleDetail.Delivered && !saleDetail.Rollbacked && !saleDetail.IsRollbackDetail)
                                {
                                    response.CanEnter = false;
                                    response.ErrorMessages.Add(condition.ErrorText);
                                }
                            }
                        }
                    }
                    // خدمات غیر اعتباری تحویل نشده نداشته باشد و یا برگشت شده باشد
                    else if (condition.QueryText == "HasNoUndeliveredUncreditOrAllRollbacked")
                    {
                        foreach (var sale in sales)
                        {
                            foreach (var saleDetail in sale.UncreditSaleDetails)
                            {
                                // تحویل نشده ی برگشت نشده فالس است
                                if (!saleDetail.Delivered && !saleDetail.Rollbacked && !saleDetail.IsRollbackDetail)
                                {
                                    response.CanEnter = false;
                                    response.ErrorMessages.Add(condition.ErrorText);
                                }
                            }
                        }
                    }
                    // آخرین خدمات اعتباری که فروخته شده منقضی شده باشد
                    else if (condition.QueryText == "LastCreditExpired")
                    {
                        CreditSaleDetail saleDetail = sales.OrderByDescending(o => o.CreateDate).FirstOrDefault().CreditSaleDetails.OrderByDescending(o => o.CreateDate).FirstOrDefault();
                        // شرط عدم انقضاء
                        if (saleDetail.CreditService.ExpDays >= PersianDateTime.DateDiff(PersianDateTime.Now, saleDetail.CreateDate))
                        {
                            response.CanEnter = false;
                            response.ErrorMessages.Add(condition.ErrorText);
                        }
                    }
                    //آخرین خدمات اعتباری که فروخته شده منقضی نشده باشد
                    else if (condition.QueryText == "LastCreditNotExpired")
                    {
                        CreditSaleDetail saleDetail = sales.OrderByDescending(o => o.CreateDate).FirstOrDefault().CreditSaleDetails.OrderByDescending(o => o.CreateDate).FirstOrDefault();
                        // شرط انقضاء
                        if (saleDetail.CreditService.ExpDays < PersianDateTime.DateDiff(PersianDateTime.Now, saleDetail.CreateDate))
                        {
                            response.CanEnter = false;
                            response.ErrorMessages.Add(condition.ErrorText);
                        }
                    }
                    // شبکه انتخاب شده برای مشتری تحت پوشش باشد
                    else if (condition.QueryText == "NetworkOfCustomerIsSupport")
                    {
                        if (customer.Network != null)
                        {
                            if (!customer.Network.NetworkCenters.Where(w => w.Status == NetworkCenterStatus.Support && w.Center == customer.Center).Any())
                            {
                                response.CanEnter = false;
                                response.ErrorMessages.Add(condition.ErrorText);
                            }
                        }
                        else
                        {
                            response.CanEnter = false;
                            response.ErrorMessages.Add("برای انتقال مشتری به این مرحله ، حتما باید شبکه مشتری مشخص باشد. لطفا در ثبت نام کامل ، شبکه مشتری را انتخاب کنید.");
                        }
                    }
                    // شبکه انتخاب شده برای مشتری عدم پوشش باشد
                    else if (condition.QueryText == "NetworkOfCustomerIsNotSupport")
                    {
                        if (!customer.Network.NetworkCenters.Where(w => w.Status == NetworkCenterStatus.NotSupport && w.Center == customer.Center).Any())
                        {
                            response.CanEnter = false;
                            response.ErrorMessages.Add(condition.ErrorText);
                        }
                    }
                    // شبکه انتخاب شده برای مشتری عدم امکان موقت باشد
                    else if (condition.QueryText == "NetworkOfCustomerIsAdameEmkan")
                    {
                        if (!customer.Network.NetworkCenters.Where(w => w.Status == NetworkCenterStatus.NotSupport && w.Center == customer.Center).Any())
                        {
                            response.CanEnter = false;
                            response.ErrorMessages.Add(condition.ErrorText);
                        }
                    }
                    // امکان تحویل حداقل یک کالا یا خدمات فروخته شده وجود داشته باشد
                    else if (condition.QueryText == "CanDeliverAtLeastOnItem")
                    {
                        foreach (Sale sale in sales)
                        {
                            if (sale.Closed)
                            {
                                foreach (var saleDetail in sale.CreditSaleDetails)
                                {
                                    // جمع سطر کمتر از مانده قابل تحویل باشد
                                    if (saleDetail.LineTotal <= customer.CanDeliverCost)
                                    {
                                        response.CanEnter = true;
                                    }
                                }
                                foreach (var saleDetail in sale.UncreditSaleDetails)
                                {
                                    // جمع سطر کمتر از مانده قابل تحویل باشد
                                    if (saleDetail.LineTotal <= customer.CanDeliverCost)
                                    {
                                        response.CanEnter = true;
                                    }
                                }
                                foreach (var saleDetail in sale.ProductSaleDetails)
                                {
                                    // جمع سطر کمتر از مانده قابل تحویل باشد
                                    if (saleDetail.LineTotal <= customer.CanDeliverCost)
                                    {
                                        response.CanEnter = true;
                                    }
                                }

                                response.ErrorMessages.Add(condition.ErrorText);
                            }
                        }
                    }
                    else if (condition.QueryText == "HasNoOpenCSupport")
                    {
                        if (customer.Supports.Any())
                        {
                            IEnumerable <Support> support =
                                customer.Supports.Where(x => x.SupportStatus.IsLastSupportState != true);

                            if (support.Count() > 0)
                            {
                                response.CanEnter = false;
                                response.ErrorMessages.Add(condition.ErrorText);
                            }
                        }
                    }
                }
            }

            return(response);
        }
Ejemplo n.º 33
0
        public GeneralResponse PrepareToAddCustomerLevel(AddCustomerLevelRequest request)
        {
            GeneralResponse response = new GeneralResponse();

            try
            {
                CustomerLevel customerLevel = new CustomerLevel();
                customerLevel.ID             = Guid.NewGuid();
                customerLevel.CreateDate     = PersianDateTime.Now;
                customerLevel.CreateEmployee = _employeeRepository.FindBy(request.CreateEmployeeID);
                customerLevel.Customer       = this._customerRepository.FindBy(request.CustomerID);
                customerLevel.Level          = this._levelRepository.FindBy(request.NewLevelID);
                customerLevel.Note           = request.Note;


                customerLevel.RowVersion = 1;

                #region Validation

                if (customerLevel.GetBrokenRules().Count() > 0)
                {
                    foreach (BusinessRule businessRule in customerLevel.GetBrokenRules())
                    {
                        response.ErrorMessages.Add(businessRule.Rule);
                    }

                    return(response);
                }

                #endregion

                #region Check Conditions

                if (customerLevel.Customer.Center == null)
                {
                    response.ErrorMessages.Add("هیچ گونه مرکز مخابراتی برای مشتری مورد نظر تعریف نشده است. لطفاً با مراجعه به تنظیمات، مرکز مخابراتی مربوط به پیش شماره مشتری را تعریف کنید.");

                    return(response);
                }

                CheckConditionResponse cres = CheckLevelCondition(customerLevel.Level, customerLevel.Customer);
                if (!cres.CanEnter)
                {
                    foreach (string error in cres.ErrorMessages)
                    {
                        response.ErrorMessages.Add(error);
                    }

                    return(response);
                }

                #endregion

                #region Change Customer Query Count

                #endregion

                #region CreateSupport

                if (customerLevel.Level.CreateSupportOnEnter)
                {
                    Support support = new Support();
                    support.ID             = Guid.NewGuid();
                    support.CreateDate     = PersianDateTime.Now;
                    support.CreateEmployee = customerLevel.CreateEmployee;
                    support.SupportTitle   = "پشتیبانی ";
                    support.SupportComment = "پشتیبانی ایجاد شده خودکار توسط سیستم";
                    support.Customer       = customerLevel.Customer;
                    support.CreateBy       = Support.Creator.BySystem;
                    support.SupportStatus  =
                        _supportStatusRepository.FindAll().Where(x => x.Key == "NoStatus").FirstOrDefault();
                    _supportRepository.Add(support);
                }

                #endregion

                _customerLevelRepository.Add(customerLevel);

                #region Query Customer Count

                //اگر مشتری جدید بود فقط به مرحله جدید یک واحد اضافه کن
                if (request.NewCustomer == true)
                {
                    Infrastructure.Querying.Query newQuery = new Infrastructure.Querying.Query();
                    Criterion crt1 = new Criterion("Level.ID", request.NewLevelID, CriteriaOperator.Equal);
                    newQuery.Add(crt1);
                    Model.Customers.Query OldQuery = _queryRepository.FindBy(newQuery).FirstOrDefault();
                    if (OldQuery != null)
                    {
                        OldQuery.CustomerCount += 1;
                        _queryRepository.Save(OldQuery);
                    }
                }
                // اگر مشتری قبلی بود از مرحله قبل یکی کم و به مرحله جدید یکی اضافه کنذ
                else
                {
                    Infrastructure.Querying.Query oldQuery = new Infrastructure.Querying.Query();
                    Criterion crt1 = new Criterion("Level.ID", customerLevel.Customer.Level.ID, CriteriaOperator.Equal);
                    oldQuery.Add(crt1);
                    Model.Customers.Query OldQuery = _queryRepository.FindBy(oldQuery).FirstOrDefault();
                    OldQuery.CustomerCount -= 1;
                    _queryRepository.Save(OldQuery);

                    Infrastructure.Querying.Query newQuery = new Infrastructure.Querying.Query();
                    Criterion crt2 = new Criterion("Level.ID", request.NewLevelID, CriteriaOperator.Equal);
                    newQuery.Add(crt2);
                    Model.Customers.Query NewQuery = _queryRepository.FindBy(newQuery).FirstOrDefault();
                    NewQuery.CustomerCount += 1;
                    _queryRepository.Save(NewQuery);
                }

                #endregion

                #region Change Customer Level In Customer Table

                Customer customer = _customerRepository.FindBy(request.CustomerID);
                customer.Level          = _levelRepository.FindBy(request.NewLevelID);
                customer.LevelEntryDate = PersianDateTime.Now;
                _customerRepository.Save(customer);


                #endregion

                _uow.Commit();

                #region Sending Email

                string displayName = "ماهان نت";
                string subject;
                //List<string> recipients = new List<string>();
                GeneralResponse sendResponse = new GeneralResponse();


                // if OnEnterSendEmail is true
                if (customerLevel.Level.OnEnterSendEmail)
                {
                    email.ID             = Guid.NewGuid();
                    email.CreateDate     = PersianDateTime.Now;
                    email.CreateEmployee = customerLevel.CreateEmployee;
                    email.Customer       = customerLevel.Customer;
                    subject          = customer.Name;
                    email.Subject    = subject;
                    email.RowVersion = 1;

                    #region Validation

                    if (email.GetBrokenRules().Count() > 0)
                    {
                        foreach (BusinessRule businessRule in email.GetBrokenRules())
                        {
                            response.ErrorMessages.Add(businessRule.Rule);
                        }

                        return(response);
                    }

                    #endregion

                    #region Send Email

                    // Replacing:
                    string emailBody = ReplaceTemplate(customerLevel.Level.EmailText, customerLevel.Customer.ConvertToCustomerView());

                    email.Body = emailBody;

                    string recipient = email.Customer.Email;
                    if (recipient == null || recipient == string.Empty)
                    {
                        response.ErrorMessages.Add("برای مشتری مورد نظر هیچ ایمیلی در سیستم تعریف نشده است.");

                        return(response);
                    }

                    //===============  Threading:
                    EmailData emailData = new EmailData()
                    {
                        displayName = displayName,
                        body        = emailBody,
                        subject     = subject,
                        recipient   = recipient
                    };

                    Thread oThread = new Thread(SendEmailVoid);
                    oThread.Start(emailData);

                    #endregion

                    _emailRepository.Add(email);
                }

                #endregion

                #region Sending Sms

                if (customerLevel.Level.OnEnterSendSMS)
                {
                    Sms sms = new Sms();
                    sms.ID             = Guid.NewGuid();
                    sms.CreateDate     = PersianDateTime.Now;
                    sms.CreateEmployee = customerLevel.CreateEmployee;
                    //sms.Body = customerLevel.Level.SMSText;
                    sms.Customer   = customerLevel.Customer;
                    sms.RowVersion = 1;

                    #region Validation

                    if (sms.GetBrokenRules().Count() > 0)
                    {
                        foreach (BusinessRule businessRule in sms.GetBrokenRules())
                        {
                            response.ErrorMessages.Add(businessRule.Rule);
                        }

                        return(response);
                    }

                    #endregion

                    string smsBody = ReplaceTemplate(customerLevel.Level.SMSText, customerLevel.Customer.ConvertToCustomerView());

                    // Threading
                    SmsData smsData = new SmsData()
                    {
                        body = smsBody, phoneNumber = customerLevel.Customer.Mobile1
                    };
                    Thread oThread = new Thread(SendSmsVoid);
                    oThread.Start(smsData);

                    _smsRepository.Add(sms);
                }

                #endregion
            }
            catch (Exception ex)
            {
                response.ErrorMessages.Add(ex.Message);
            }

            return(response);
        }
Ejemplo n.º 34
0
        private static DecisionTreeNode <TItem> GenerateNode(
            TreeBuilderContext context,
            DecisionCriterionValueEqualityComparer comparer,
            IList <ItemDescriptor <TItem> > items)
        {
            // The extreme use of generics here is intended to reduce the number of intermediate
            // allocations of wrapper classes. Performance testing found that building these trees allocates
            // significant memory that we can avoid and that it has a real impact on startup.
            var criteria = new Dictionary <string, Criterion>(StringComparer.OrdinalIgnoreCase);

            // Matches are items that have no remaining criteria - at this point in the tree
            // they are considered accepted.
            var matches = new List <TItem>();

            // For each item in the working set, we want to map it to it's possible criteria-branch
            // pairings, then reduce that tree to the minimal set.
            foreach (var item in items)
            {
                var unsatisfiedCriteria = 0;

                foreach (var kvp in item.Criteria)
                {
                    // context.CurrentCriteria is the logical 'stack' of criteria that we've already processed
                    // on this branch of the tree.
                    if (context.CurrentCriteria.Contains(kvp.Key))
                    {
                        continue;
                    }

                    unsatisfiedCriteria++;

                    Criterion criterion;
                    if (!criteria.TryGetValue(kvp.Key, out criterion))
                    {
                        criterion = new Criterion(comparer);
                        criteria.Add(kvp.Key, criterion);
                    }

                    List <ItemDescriptor <TItem> > branch;
                    if (!criterion.TryGetValue(kvp.Value, out branch))
                    {
                        branch = new List <ItemDescriptor <TItem> >();
                        criterion.Add(kvp.Value, branch);
                    }

                    branch.Add(item);
                }

                // If all of the criteria on item are satisfied by the 'stack' then this item is a match.
                if (unsatisfiedCriteria == 0)
                {
                    matches.Add(item.Item);
                }
            }

            // Iterate criteria in order of branchiness to determine which one to explore next. If a criterion
            // has no 'new' matches under it then we can just eliminate that part of the tree.
            var reducedCriteria = new List <DecisionCriterion <TItem> >();

            foreach (var criterion in criteria.OrderByDescending(c => c.Value.Count))
            {
                var reducedBranches = new Dictionary <object, DecisionTreeNode <TItem> >(comparer.InnerComparer);
                DecisionTreeNode <TItem> fallback = null;

                foreach (var branch in criterion.Value)
                {
                    var reducedItems = new List <ItemDescriptor <TItem> >();
                    foreach (var item in branch.Value)
                    {
                        if (context.MatchedItems.Add(item))
                        {
                            reducedItems.Add(item);
                        }
                    }

                    if (reducedItems.Count > 0)
                    {
                        var childContext = new TreeBuilderContext(context);
                        childContext.CurrentCriteria.Add(criterion.Key);

                        var newBranch = GenerateNode(childContext, comparer, branch.Value);
                        if (branch.Key.IsCatchAll)
                        {
                            fallback = newBranch;
                        }
                        else
                        {
                            reducedBranches.Add(branch.Key.Value, newBranch);
                        }
                    }
                }

                if (reducedBranches.Count > 0 || fallback != null)
                {
                    var newCriterion = new DecisionCriterion <TItem>()
                    {
                        Key      = criterion.Key,
                        Branches = reducedBranches,
                        Fallback = fallback,
                    };

                    reducedCriteria.Add(newCriterion);
                }
            }

            return(new DecisionTreeNode <TItem>()
            {
                Criteria = reducedCriteria.ToList(),
                Matches = matches,
            });
        }
Ejemplo n.º 35
0
        public static MetaResultsWeight MetaWeightEvaluate(
            DiseasesData PredictionData,
            DiseasesData RealData,
            Tuple <TFType, IDFType> tuple,
            double pas,
            Criterion criterion)
        {
            //Create MetaResult
            MetaResultsWeight metaResultsWeight = new MetaResultsWeight();

            //Compute all results and put them in metaResults
            List <Results> listResults = new List <Results>();

            for (double i = 0.00; i < 0.17; i += pas)
            {
                Results currentRes = Evaluate(PredictionData, RealData, tuple, i);
                listResults.Add(currentRes);
                metaResultsWeight.perThreshold.Add(
                    new PerThreshold(
                        currentRes.general.TimeStamp,
                        currentRes.general.NumberOfDiseasesWithKnownPhenotypes,
                        currentRes.general.NumberOfDiseasesWithPublicationsInPredictionData,
                        currentRes.general.NumberOfDiseasesEvaluatedForReal,
                        currentRes.general.Type,
                        currentRes.general.MeanNumberOfRelatedEntitiesFound,
                        currentRes.general.StandardDeviationNumberOfRelatedEntitiesFound,
                        currentRes.general.TFType,
                        currentRes.general.IDFType,
                        currentRes.general.WeightThreshold,
                        currentRes.general.RealPositives,
                        currentRes.general.FalsePositives,
                        currentRes.general.FalseNegatives,
                        currentRes.general.Precision,
                        currentRes.general.Recall,
                        currentRes.general.F_Score,
                        currentRes.general.MeanRankRealPositives,
                        currentRes.general.StandardDeviationRankRealPositivesGeneral,
                        criterion
                        ));
            }

            //Find best results and sort by perCombinaison
            Results Best_Result;

            switch (criterion)
            {
            case Criterion.MeanRankRealPositives:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.MeanRankRealPositives < savedRes.general.MeanRankRealPositives ? currentRes : savedRes);
                metaResultsWeight.perThreshold = metaResultsWeight.perThreshold.OrderBy(pc => pc.MeanRankRealPositives).ToList();
                break;

            case Criterion.F_Score:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.F_Score > savedRes.general.F_Score ? currentRes : savedRes);
                metaResultsWeight.perThreshold = metaResultsWeight.perThreshold.OrderByDescending(pc => pc.F_Score).ToList();
                break;

            case Criterion.Precision:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.Precision > savedRes.general.Precision ? currentRes : savedRes);
                metaResultsWeight.perThreshold = metaResultsWeight.perThreshold.OrderByDescending(pc => pc.Precision).ToList();
                break;

            case Criterion.Recall:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.Recall > savedRes.general.Recall ? currentRes : savedRes);
                metaResultsWeight.perThreshold = metaResultsWeight.perThreshold.OrderByDescending(pc => pc.Recall).ToList();
                break;

            default:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.MeanRankRealPositives < savedRes.general.MeanRankRealPositives ? currentRes : savedRes);
                metaResultsWeight.perThreshold = metaResultsWeight.perThreshold.OrderBy(pc => pc.MeanRankRealPositives).ToList();
                break;
            }

            //Complete metaResults
            metaResultsWeight.bestThreshold = new BestThreshold(
                Best_Result.general.TimeStamp,
                Best_Result.general.NumberOfDiseasesWithKnownPhenotypes,
                Best_Result.general.NumberOfDiseasesWithPublicationsInPredictionData,
                Best_Result.general.NumberOfDiseasesEvaluatedForReal,
                Best_Result.general.Type,
                Best_Result.general.MeanNumberOfRelatedEntitiesFound,
                Best_Result.general.StandardDeviationNumberOfRelatedEntitiesFound,
                Best_Result.general.TFType,
                Best_Result.general.IDFType,
                Best_Result.general.WeightThreshold,
                Best_Result.general.RealPositives,
                Best_Result.general.FalsePositives,
                Best_Result.general.FalseNegatives,
                Best_Result.general.Precision,
                Best_Result.general.Recall,
                Best_Result.general.F_Score,
                Best_Result.general.MeanRankRealPositives,
                Best_Result.general.StandardDeviationRankRealPositivesGeneral,
                criterion
                );

            return(metaResultsWeight);
        }
Ejemplo n.º 36
0
        /*
         * public static MetaResults MetaEvaluate(DiseasesData PredictionData, DiseasesData RealData, Tuple<TFType, IDFType> WeightCombinaison, double minWeight, double maxWeight, double step, Criterion criterion)
         * {
         *  //Create MetaResult
         *  MetaResults metaResults = new MetaResults(WeightCombinaison.Item1, WeightCombinaison.Item2);
         *
         *  //Compute all results and put them in metaResults
         *  List<Results> listResults = new List<Results>();
         *  for (double i = minWeight; i <= maxWeight; i+=step)
         *  {
         *      Results currentRes = Evaluate(PredictionData, RealData, WeightCombinaison, i);
         *      listResults.Add(currentRes);
         *      metaResults.perThreshold.Add(
         *          new PerThreshold(
         *              i,
         *              currentRes.general.Type,
         *              currentRes.general.RealPositives,
         *              currentRes.general.FalsePositives,
         *              currentRes.general.FalseNegatives,
         *              currentRes.general.Precision,
         *              currentRes.general.Recall,
         *              currentRes.general.F_Score
         *              ));
         *  }
         *
         *  //Find best results
         *  Results Best_Result;
         *  switch (criterion)
         *  {
         *      case Criterion.F_Score:
         *          Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.F_Score > savedRes.general.F_Score ? currentRes : savedRes);
         *          break;
         *      case Criterion.Precision:
         *          Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.Precision > savedRes.general.Precision ? currentRes : savedRes);
         *          break;
         *      case Criterion.Recall:
         *          Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.Recall > savedRes.general.Recall ? currentRes : savedRes);
         *          break;
         *      default:
         *          Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.F_Score > savedRes.general.F_Score ? currentRes : savedRes);
         *          break;
         *  }
         *
         *  //Complete metaResults
         *  metaResults.bestInfos = new BestInfos(
         *          Best_Result.general.TimeStamp,
         *          Best_Result.general.Type,
         *          Best_Result.general.Threshold,
         *          Best_Result.general.Precision,
         *          Best_Result.general.Recall,
         *          Best_Result.general.F_Score,
         *          criterion
         *      );
         *
         *  return metaResults;
         * }*/

        public static MetaResults MetaEvaluate(DiseasesData PredictionData, DiseasesData RealData, Criterion criterion, params Tuple <TFType, IDFType>[] WeightCombinaisons)
        {
            //Create MetaResult
            MetaResults metaResults = new MetaResults();

            //Compute all results and put them in metaResults
            List <Results> listResults = new List <Results>();

            //If not precised, we generate
            if (WeightCombinaisons.Length == 0)
            {
                WeightCombinaisons = GenerateDisctinctsTupleForWeightComputation().ToArray();
            }

            foreach (var tuple in WeightCombinaisons)
            {
                Results currentRes = Evaluate(PredictionData, RealData, tuple);
                listResults.Add(currentRes);
                metaResults.perCombinaison.Add(
                    new PerCombinaison(
                        currentRes.general.TimeStamp,
                        currentRes.general.NumberOfDiseasesWithKnownPhenotypes,
                        currentRes.general.NumberOfDiseasesWithPublicationsInPredictionData,
                        currentRes.general.NumberOfDiseasesEvaluatedForReal,
                        currentRes.general.Type,
                        currentRes.general.MeanNumberOfRelatedEntitiesFound,
                        currentRes.general.StandardDeviationNumberOfRelatedEntitiesFound,
                        currentRes.general.TFType,
                        currentRes.general.IDFType,
                        currentRes.general.RealPositives,
                        currentRes.general.FalsePositives,
                        currentRes.general.FalseNegatives,
                        currentRes.general.Precision,
                        currentRes.general.Recall,
                        currentRes.general.F_Score,
                        currentRes.general.MeanRankRealPositives,
                        currentRes.general.StandardDeviationRankRealPositivesGeneral,
                        criterion
                        ));
            }

            //Find best results and sort by perCombinaison
            Results Best_Result;

            switch (criterion)
            {
            case Criterion.MeanRankRealPositives:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.MeanRankRealPositives < savedRes.general.MeanRankRealPositives ? currentRes : savedRes);
                metaResults.perCombinaison = metaResults.perCombinaison.OrderBy(pc => pc.MeanRankRealPositives).ToList();
                break;

            case Criterion.F_Score:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.F_Score > savedRes.general.F_Score ? currentRes : savedRes);
                metaResults.perCombinaison = metaResults.perCombinaison.OrderByDescending(pc => pc.F_Score).ToList();
                break;

            case Criterion.Precision:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.Precision > savedRes.general.Precision ? currentRes : savedRes);
                metaResults.perCombinaison = metaResults.perCombinaison.OrderByDescending(pc => pc.Precision).ToList();
                break;

            case Criterion.Recall:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.Recall > savedRes.general.Recall ? currentRes : savedRes);
                metaResults.perCombinaison = metaResults.perCombinaison.OrderByDescending(pc => pc.Recall).ToList();
                break;

            default:
                Best_Result = listResults.Aggregate((savedRes, currentRes) => currentRes.general.MeanRankRealPositives < savedRes.general.MeanRankRealPositives ? currentRes : savedRes);
                metaResults.perCombinaison = metaResults.perCombinaison.OrderBy(pc => pc.MeanRankRealPositives).ToList();
                break;
            }

            //Complete metaResults
            metaResults.bestInfos = new BestInfos(
                Best_Result.general.TimeStamp,
                Best_Result.general.NumberOfDiseasesWithKnownPhenotypes,
                Best_Result.general.NumberOfDiseasesWithPublicationsInPredictionData,
                Best_Result.general.NumberOfDiseasesEvaluatedForReal,
                Best_Result.general.Type,
                Best_Result.general.MeanNumberOfRelatedEntitiesFound,
                Best_Result.general.StandardDeviationNumberOfRelatedEntitiesFound,
                Best_Result.general.TFType,
                Best_Result.general.IDFType,
                Best_Result.general.RealPositives,
                Best_Result.general.FalsePositives,
                Best_Result.general.FalseNegatives,
                Best_Result.general.Precision,
                Best_Result.general.Recall,
                Best_Result.general.F_Score,
                Best_Result.general.MeanRankRealPositives,
                Best_Result.general.StandardDeviationRankRealPositivesGeneral,
                criterion
                );

            return(metaResults);
        }
Ejemplo n.º 37
0
        public CriterionRow(IGraphElementModel graphElementModel,
                            CriteriaModel criteriaModel,
                            Criterion criterion,
                            Stencil stencil,
                            Store store,
                            ExpandedContainer parentElement,
                            Action <EventBase> onDeleteCriterion)
            : base(string.Empty, graphElementModel as ComponentQueryDeclarationModel, store, parentElement, null, null)
        {
            GraphElementModel = graphElementModel;
            CriteriaModel     = criteriaModel;
            Criterion         = criterion ?? throw new ArgumentNullException(nameof(criterion), "criterion should not be null");
            ClearClassList();
            AddToClassList("criterionRow");

            capabilities |= Capabilities.Selectable | Capabilities.Deletable;

            styleSheets.Add(AssetDatabase.LoadAssetAtPath <StyleSheet>(UnityEditor.VisualScripting.Editor.UICreationHelper.templatePath + "PropertyField.uss"));

            var deleteCriterionButton = new Button {
                name = "deleteCriterionIcon"
            };

            deleteCriterionButton.clickable.clickedWithEventInfo += onDeleteCriterion;
            ExpandableRowTitleContainer.Insert(0, deleteCriterionButton);

            userData = criterion.GetHashCode();

            var criterionContainer = new VisualElement {
                name = "rowCriterionContainer"
            };

            string criterionNamespace = criterion.ObjectType.GetMetadata(stencil).Namespace;
            string criterionName      = criterion.ObjectType.ToTypeSyntax(stencil).ToString().Replace(criterionNamespace + ".", "");

            var criterionStr = new StringBuilder(criterionName);

            if (criterion.Member.Path.Any())
            {
                criterionStr.Append(" > ");
                criterionStr.Append(string.Join(" > ", criterion.Member.Path));
            }

            var criterionPillContainer = new VisualElement {
                name = "rowPillContainer"
            };
            var criterionPill = new Pill {
                text = criterionStr.ToString()
            };

            criterionPillContainer.Add(criterionPill);

            criterionPillContainer.Add(new Label()
            {
                name = "criterionOperatorKind", text = criterion.Operator.NicifyBinaryOperationKindName(OperatorExtensions.NicifyBinaryOperationKindType.String)
            });

            if (criterion.Value.NodeAssetReference != null)
            {
                m_WatchedObject = new SerializedObject(criterion.Value.NodeAssetReference);
            }
            m_EditorElement = SetupConstantEditor(criterion.Value);
            var label = m_EditorElement.Q <Label>();

            if (label != null && !EditorNeedsLabel)
            {
                label.style.width = 0;
            }

            criterionPillContainer.Add(m_EditorElement);

            criterionContainer.Add(criterionPillContainer);

            ExpandableRowTitleContainer.Add(criterionContainer);

            // CriterionRow's are NOT expandable (for now, until we find a reason to) but since we need everything
            // else that is provided by SortableExpandableRow, we'll just disable expansion altogether
            ExpandedButton.style.display = DisplayStyle.None;

            RegisterCallback <AttachToPanelEvent>(OnAttachToPanel);
            RegisterCallback <DetachFromPanelEvent>(OnDetachFromPanel);

            this.AddManipulator(new ContextualMenuManipulator(OnContextualMenuEvent));
        }
Ejemplo n.º 38
0
        protected override void ProcessFile(string filePath)
        {
            ValidateFilePath(filePath);
            ValidateFileExtension(filePath, ".utx");

            //load XML
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(filePath);

            //var nameAttributeId = "";
            var descriptionAttributeName = "";

            var attributes = xmlDoc.GetElementsByTagName("ATTRIBUTES");

            var objects = xmlDoc.GetElementsByTagName("OBJECTS");

            // iterate on its nodes
            foreach (XmlNode attribute in attributes[0].ChildNodes)
            {
                var criterion = new Criterion {
                    LinearSegments = 1
                };
                // for UTX ID and Name are the same value
                criterion.Name = criterion.ID = checkCriteriaIdsUniqueness(attribute.Attributes["AttrID"].Value);
                var saveCriterion           = true;
                var enumIdsNamesDictionary  = new Dictionary <string, string>();
                var enumIdsValuesDictionary = new Dictionary <string, double>();

                foreach (XmlNode attributePart in attribute)
                {
                    var value = attributePart.Attributes["Value"].Value;

                    switch (attributePart.Name)
                    {
                    case "TYPE":
                        if (value == "Enum")
                        {
                            criterion.IsEnum = true;
                            foreach (XmlNode enumName in attributePart)
                            {
                                enumIdsNamesDictionary.Add(enumName.Attributes["EnumID"].Value,
                                                           enumName.Attributes["Value"].Value);
                            }
                        }

                        break;

                    case "DESCRIPTION":
                        criterion.Description = value;
                        break;

                    case "CRITERION":
                        // if value is enum type
                        if (value == "Rank")
                        {
                            foreach (XmlNode enumValue in attributePart)
                            {
                                checkEnumValue(criterion.Name, enumValue.Attributes["EnumID"].Value,
                                               enumValue.Attributes["Value"].Value);
                                enumIdsValuesDictionary.Add(enumValue.Attributes["EnumID"].Value,
                                                            double.Parse(enumValue.Attributes["Value"].Value, CultureInfo.InvariantCulture));
                            }

                            criterion.CriterionDirection = "Cost";
                        }
                        else
                        {
                            // "Cost" or "Gain"
                            criterion.CriterionDirection = value == "Cost" ? "Cost" : "Gain";
                        }

                        break;

                    case "ROLE":
                        if (value == "Description")
                        {
                            saveCriterion            = false;
                            descriptionAttributeName = criterion.Name;
                        }
                        else
                        {
                            saveCriterion = true;
                        }

                        break;

                    case "SEGMENTS":
                        CheckIfIntegerValueIsValid(value, "SEGMENT in ATTRIBUTE", criterion.ID);
                        criterion.LinearSegments = int.Parse(value);
                        break;

                    default:
                        throw new Exception("Attribute " + attributePart.Name + " is not compatible with application.");
                    }
                }

                if (saveCriterion)
                {
                    criterion = validateCriterion(criterion, enumIdsNamesDictionary, enumIdsValuesDictionary);
                    criterionList.Add(criterion);
                }
            }


            foreach (XmlNode instance in objects[0].ChildNodes)
            {
                // check if number of all child nodes (except INFO node - which isn't about criterion) is equal to criterionList.Count
                var alternativesCountValidation = 0;
                var alternative = new Alternative {
                    Name = checkAlternativesNamesUniqueness(instance.Attributes["ObjID"].Value)
                };
                alternative.ID = alternative.Name;

                var criteriaValuesList = new ObservableCollection <CriterionValue>();

                foreach (XmlNode instancePart in instance)
                {
                    if (instancePart.Name.Equals("RANK"))
                    {
                        var value = instancePart.Attributes["Value"].Value;
                        CheckIfIntegerValueIsValid(value, "RANK in OBJECT", alternative.ID);
                        alternative.ReferenceRank = int.Parse(value) - 1;
                    }
                    else if (instancePart.Name.Equals("VALUE"))
                    {
                        var value         = instancePart.Attributes["Value"].Value;
                        var attributeName = instancePart.Attributes["AttrID"].Value;

                        if (attributeName != descriptionAttributeName)
                        {
                            alternativesCountValidation++;
                            var criterion = criterionList.Find(element => element.Name == attributeName);

                            if (criterion == null)
                            {
                                throw new ImproperFileStructureException(
                                          "Error while processing alternative " + alternative.Name + ": criterion named " +
                                          attributeName + " does not exist.");
                            }


                            if (criterion.IsEnum)
                            {
                                var enumValue = _criterionEnumsList.Find(o => o.CriterionId == criterion.ID).EnumDictionary[value];
                                criteriaValuesList.Add(new CriterionValue(criterion.Name, enumValue));
                            }
                            else
                            {
                                checkIfValueIsValid(value, criterion.Name, alternative.Name);
                                criteriaValuesList.Add(new CriterionValue(criterion.Name,
                                                                          double.Parse(value, CultureInfo.InvariantCulture)));
                            }
                        }
                    }
                }

                if (alternativesCountValidation != criterionList.Count)
                {
                    throw new ImproperFileStructureException("Error while processing alternative " + alternative.Name +
                                                             ": there are provided " + alternativesCountValidation +
                                                             " criteria values and required are " + criterionList.Count + ".");
                }

                alternative.CriteriaValuesList = criteriaValuesList;
                alternativeList.Add(alternative);
            }
        }
Ejemplo n.º 39
0
        public GeneralResponse Confirm(ConfirmRequest request)
        {
            GeneralResponse response = new GeneralResponse();

            Fiscal fiscal = new Fiscal();

            fiscal = _fiscalRepository.FindBy(request.FiscalID);
            Customer customer = _customerRepository.FindBy(fiscal.Customer.ID);

            if (fiscal != null)
            {
                try
                {
                    if (fiscal.MoneyAccount.Has9Digits)
                    {
                        if (request.FiscalReciptNumber < 100000000 || request.FiscalReciptNumber > 999999999)
                        {
                            response.ErrorMessages.Add("شماره رسید نمیتواند کمتر از 9 رقم باشد");
                            return(response);
                        }
                    }

                    fiscal.Confirm     = request.Confirm;
                    fiscal.ConfirmDate = PersianDateTime.Now;

                    fiscal.ConfirmedCost   = fiscal.Cost < 0 ? -request.ConfirmedCost : request.ConfirmedCost;
                    fiscal.ConfirmEmployee = _employeeRepository.FindBy(request.ConfirmEmployeeID);

                    if (request.Confirm == ConfirmEnum.Confirmed)
                    {
                        fiscal.SerialNumber = NewSerialNumber(fiscal.MoneyAccount);
                    }

                    #region Check Permission
                    // Check if the Employee can confirm or not
                    if (!fiscal.EmployeesWhoCanConfirm.Contains(fiscal.ConfirmEmployee))
                    {
                        response.ErrorMessages.Add("YouCanNotConfirmThisMoneyAccountKey");
                        return(response);
                    }
                    #endregion

                    #region Check the Cost
                    // Check if (ConfirmCost > Cost) then Rais error
                    if (request.ConfirmedCost > Math.Abs(fiscal.Cost))
                    {
                        response.ErrorMessages.Add("InvalidConfirmCostKey");
                        return(response);
                    }
                    #endregion

                    #region RowVresion Check

                    if (fiscal.RowVersion != request.RowVersion)
                    {
                        response.ErrorMessages.Add("EditConcurrencyKey");
                        return(response);
                    }
                    else
                    {
                        fiscal.RowVersion += 1;
                    }
                    fiscal.AccountingSerialNumber = NewAccountingSerialNumber;

                    #endregion

                    if (customer.Balance < request.ConfirmedCost && fiscal.ConfirmedCost < 0 && request.Confirm == ConfirmEnum.Confirmed)
                    {
                        response.ErrorMessages.Add("مبلغ پرداختی به مشتری بیش از بستانکاری مشتری میباشد");
                        return(response);
                    }

                    #region Change Customer Balance
                    if ((int)request.Confirm != 1 && (int)request.Confirm != 3)
                    {
                        if (fiscal.MoneyAccount.HasUniqueSerialNumber)
                        {
                            Query     query           = new Query();
                            Criterion uniqueCriterion = new Criterion("FiscalReciptNumber", request.FiscalReciptNumber, CriteriaOperator.Equal);
                            query.Add(uniqueCriterion);
                            Criterion uniqueCriterion1 = new Criterion("MoneyAccount.ID", fiscal.MoneyAccount.ID, CriteriaOperator.Equal);
                            query.Add(uniqueCriterion1);
                            IEnumerable <FiscalView> fiscalView = _fiscalRepository.FindByQuery(query).data.ConvertToFiscalViews();
                            if (fiscalView.Count() > 0)
                            {
                                response.ErrorMessages.Add("  این شماره قبلا به  " + fiscalView.FirstOrDefault().CustomerName + " با شماره تلفن " + fiscalView.FirstOrDefault().ADSLPhone + " داده شده است ");
                                return(response);
                            }
                        }

                        fiscal.FiscalReciptNumber = request.FiscalReciptNumber;
                        customer.Balance         += fiscal.ConfirmedCost;
                        long confirmedCost = fiscal.ConfirmedCost == null ? 0 : (long)fiscal.ConfirmedCost;
                        customer.CanDeliverCost += confirmedCost;
                        _customerRepository.Save(customer);
                        if (customer.CanDeliverCost < 0)
                        {
                            response.ErrorMessages.Add(" هشدار ! با انجام این عملیات معین تحویل مشتری منفی میشود. لطفا با برنامه نویس تماس بگیرید");
                            return(response);
                        }
                    }

                    #endregion

                    _fiscalRepository.Save(fiscal);
                    _uow.Commit();
                }
                catch (Exception ex)
                {
                    response.ErrorMessages.Add(ex.Message);
                    if (ex.InnerException != null)
                    {
                        response.ErrorMessages.Add(ex.InnerException.Message);
                    }
                }
            }
            else
            {
                response.ErrorMessages.Add("NoItemToEditKey");
                return(response);
            }

            return(response);
        }
 List <SurveyAnswerResponse> IRepository <SurveyAnswerResponse> .GetList(Criterion criterion = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 41
0
 public virtual ICriterion GenerateSqlCriterion(Criterion criterion)
 {
     throw new ApplicationException("No operator defined");
 }
Ejemplo n.º 42
0
 public void SutDoesNotEqualAnyObject(object other)
 {
     var sut = new Criterion<PlatformID>(
         PlatformID.Unix,
         new DelegatingEqualityComparer<PlatformID>());
     var actual = sut.Equals(other);
     Assert.False(actual, "SUT should not equal object of other type.");
 }
Ejemplo n.º 43
0
        public void doSearchIDTest()
        {
            FileFolderStation s = CreateRemoteTestStation();

            ICollection<Criterion> crit = new List<Criterion>();
            Criterion c1 = new Criterion(Field.InstanceUpdateDate, Criterion.GreaterThanOrEqual, "5/1/2010");
            crit.Add(c1);
            Criterion c2 = new Criterion(Field.EntityId, Criterion.Equal, "3230596");
            crit.Add(c2);

            InstanceRefList actual = s.DoSearch(crit);

            List<Instance> instances = actual.InstanceList;

            foreach (Instance i in instances)
            {
                Console.WriteLine(i.Details);
            }

            Assert.AreEqual(2, actual.List.Count);
            Assert.IsTrue(FoundResult(instances, "3230596", "Archive", "3230596.pdf"));
        }
Ejemplo n.º 44
0
 public static string GetDescription(this Criterion criterion)
 {
     return("Идентификатор переменной: " + criterion.VariableIdentifier +
            "\nТип: " + CriterionTypeManager.GetCriterionTypeName(criterion.Type) +
            "\nВесовой коэффициент: " + criterion.Weight.ToString());
 }
 /// <summary>
 /// Calculates a new value of the threshold subject to taken criterion
 /// </summary>
 /// <param name="criterion">a rule subject to the threshold changes</param>
 /// <returns>the new value of threshold</returns>
 public abstract double Next(Criterion.Criterion criterion);
Ejemplo n.º 46
0
 public override void DisplayResults(StateOperator @operator, SystemBipartition bipartition)
 {
     Criterion.Evaluate(@operator, bipartition);
     SetVisuals((ComputableCrossNormCriterion)Criterion);
 }
Ejemplo n.º 47
0
 public CompareWithAttribute(string comparisonProperty, Criterion criterion) : this(vc => GetFieldByName(vc, comparisonProperty), criterion)
 {
 }
 public int GetCount(Criterion criterion = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 49
0
        public void SutDoesNotEqualOtherWhenTargetDiffers(
            int sutTarget,
            int otherTarget)
        {
            var comparer = new DelegatingEqualityComparer<int>();
            var sut = new Criterion<int>(sutTarget, comparer);

            var other = new Criterion<int>(otherTarget, comparer);
            var actual = sut.Equals(other);

            Assert.False(
                actual,
                "SUT shouldn't equal other with different target");
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the keyword.
        /// </param>
        /// <param name="keywordId">Id of the keyword to be updated.</param>
        public void Run(AdWordsUser user, long adGroupId, long keywordId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201705.AdGroupCriterionService);

            // Since we are not updating any keyword-specific fields, it is enough to
            // create a criterion object.
            Criterion criterion = new Criterion();

            criterion.id = keywordId;

            // Create ad group criterion.
            BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();

            biddableAdGroupCriterion.adGroupId = adGroupId;
            biddableAdGroupCriterion.criterion = criterion;

            // Create the bids.
            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            CpcBid cpcBid = new CpcBid();

            cpcBid.bid             = new Money();
            cpcBid.bid.microAmount = 1000000;
            biddingConfig.bids     = new Bids[] { cpcBid };

            biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

            // Create the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation();

            operation.@operator = Operator.SET;
            operation.operand   = biddableAdGroupCriterion;

            try {
                // Update the keyword.
                AdGroupCriterionReturnValue retVal =
                    adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { operation });

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    AdGroupCriterion adGroupCriterion = retVal.value[0];
                    long             bidAmount        = 0;
                    foreach (Bids bids in (adGroupCriterion as BiddableAdGroupCriterion).
                             biddingStrategyConfiguration.bids)
                    {
                        if (bids is CpcBid)
                        {
                            bidAmount = (bids as CpcBid).bid.microAmount;
                            break;
                        }
                    }

                    Console.WriteLine("Keyword with ad group id = '{0}', id = '{1}' was updated with " +
                                      "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
                                      adGroupCriterion.criterion.id, bidAmount);
                }
                else
                {
                    Console.WriteLine("No keyword was updated.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to update keyword.", e);
            }
        }
Ejemplo n.º 51
0
 public CompareWithAttribute(object comparisonConstant, Criterion criterion) : this(vc => comparisonConstant as IComparable, criterion)
 {
 }
Ejemplo n.º 52
0
        static void Main(string[] args)
        {
            string conn = "Data Source=QH-20140814XCYI;Initial Catalog=Test;Integrated Security=True";
            SqlServerDataFactory dataFactory = new SqlServerDataFactory(conn);
            DataTable            dttest      = new DataTable();
            DataColumn           dc          = new DataColumn("d", typeof(string));

            dttest.Columns.Add(dc);

            DataColumn dc1 = new DataColumn("c", typeof(int));

            dttest.Columns.Add(dc1);

            DataRow dr = dttest.NewRow();

            dr["c"] = 2;
            dr["d"] = "123ss";
            dttest.Rows.Add(dr);
            DataRow dr1 = dttest.NewRow();

            dr1["c"] = 3;
            dr1["d"] = "123ss";
            dttest.Rows.Add(dr1);
            //dataFactory.Insert("B", dttest);

            string[] key = { "c" };
            dataFactory.Update("B", dttest, key);
            Console.ReadKey();

            //////////////////////////////////////delete
            Delete delete = new Delete("tableName");

            delete.AddCriterions("a", "zhangxin", "1", CriteriaOperator.MoreThan);
            delete.AddCriterions("a", "zhangdi", 2, CriteriaOperator.LessThan);
            delete.AddCriterions("b", "2", CriteriaOperator.Equal);
            delete.AddSqlOperator(SqlOperator.OR);

            SqlCommand deleteCmd = new SqlCommand();

            DeleteTranslator.TranslateIntoDelete(delete, deleteCmd);
            Console.WriteLine(deleteCmd.CommandText);
            Console.WriteLine(deleteCmd.Parameters.Count);
            //Console.ReadKey();
            //////////////////////////////////////////////////

            Test test = new Test
            {
                a = "1",
                b = "2",
                c = "3"
            };
            Insert <Test> insert = new Insert <Test>("tableName", test);

            insert.AddExcludeField("a");
            SqlCommand insertCmd = new SqlCommand();

            SaveTranslator.TranslateIntoInsert <Test>(insert, insertCmd);
            Console.WriteLine(insertCmd.CommandText);
            Console.WriteLine(insertCmd.Parameters.Count);
            //Console.ReadKey();
            ////////////////////////////////////////////////////////////

            Test test1 = new Test
            {
                a = "1",
                b = "2",
                c = "3"
            };
            Update <Test> update = new Update <Test>("taleName", test1);

            update.AddCriterion("a", "a", "1", CriteriaOperator.Equal);
            update.AddCriterion("b", "b", "2", CriteriaOperator.Equal);
            update.AddExcludeField("c");
            update.AddSqlOperator(SqlOperator.AND);
            SqlCommand updateCmd = new SqlCommand();

            SaveTranslator.TranslateIntoUpdate <Test>(update, updateCmd);
            Console.WriteLine(updateCmd.CommandText);
            Console.WriteLine(updateCmd.Parameters.Count);
            //Console.ReadKey();

            ////////////////////////////////////////////////////////////

            Query query = new Query("tableName");

            query.AddCriterion("a.b", "1", CriteriaOperator.Equal);
            //query.AddCriterion("b", "b", "2", CriteriaOperator.Equal);
            query.AddCriterion("c", "____", CriteriaOperator.Like);
            query.AddOrderByClause(new OrderByClause("a", false));
            query.AddOrderByClause(new OrderByClause("b", true));
            //query.AddSqlOperator(SqlOperator.AND);
            SqlCommand queryCmd = new SqlCommand();

            QueryTranslator.TranslateIntoSelect(query, queryCmd);
            Console.WriteLine(queryCmd.CommandText);
            Console.WriteLine(queryCmd.Parameters.Count);
            //Console.ReadKey();

            //////////////////////////////////////////////////////////////

            ComplexQuery cmquery = new ComplexQuery();

            IList <NeedField> list      = new List <NeedField>();
            NeedField         needField = new NeedField
            {
                TableName    = "tableName1",
                FieldName    = "a",
                VariableName = ""
            };

            list.Add(needField);
            cmquery.NeedFields = list;
            cmquery.AddNeedField("tableName2", "b");
            cmquery.AddNeedField("tableName3", "c", "test");
            IDictionary <string, string> testjoin = new Dictionary <string, string>();

            testjoin.Add("tableName1", "c1");
            testjoin.Add("tableName2", "c2");
            testjoin.Add("tableName3", "c3");


            //cmquery.AddJoinCriterion("assss", JoinType.FULL_JOIN);
            cmquery.AddJoinCriterion(testjoin, JoinType.INNER_JOIN);



            //cmquery.IsDictinct = true;
            //cmquery.TopNumber = 9;
            cmquery.AddCriterion("a", "a", "1", CriteriaOperator.Equal);
            cmquery.AddCriterion("b", "b", "2", CriteriaOperator.Equal);
            cmquery.AddCriterion("c", "c", "3", CriteriaOperator.Like);
            List <OrderByClause> orders = new List <OrderByClause>();

            orders.Add(new OrderByClause("a", true));
            orders.Add(new OrderByClause("b", false));
            cmquery.OrderByClauses = orders;
            SqlCommand cmqueryCmd = new SqlCommand();

            ComplexQueryTranslator.TranslateIntoComplexQuery(cmquery, cmqueryCmd);
            Console.WriteLine(cmqueryCmd.CommandText);
            Console.WriteLine(cmqueryCmd.Parameters.Count);
            //Console.ReadKey();


            ///////////////////////////////////////////////////////////
            ComplexQuery testquery = new ComplexQuery();

            Console.WriteLine(testquery.TopNumber);
            Console.WriteLine(DateTime.Today);
            Console.WriteLine(DateTime.Now.AddDays(-1).Date);
            //Console.ReadKey();

            ///////////////////////////////////////////////////////

            //Query testQuery = new Query("B");
            //SqlServerDataFactory dataFactory = new SqlServerDataFactory("Data Source=QH-20140814XCYI;Initial Catalog=Test;Integrated Security=True");
            //IEnumerable<BModle> result = dataFactory.Query<BModle>(testQuery);
            //foreach (var item in result)
            //{
            //    //BModle a = (BModle)item;
            //    Console.WriteLine(item.d);
            //    Console.WriteLine(item.c);
            //}
            //Console.WriteLine(result.Count());
            //Console.ReadKey();

            JoinCriterion joinCri = new JoinCriterion();

            Console.WriteLine("++" + joinCri.DefaultJoinFieldName + "++");
            Console.ReadKey();

            Criterion testcri = new Criterion("name", "", 1, CriteriaOperator.Equal);

            Console.WriteLine(testcri.ParameterName);
            Console.ReadKey();

            //SqlServerDataFactory dataFactory = new SqlServerDataFactory("");
            //SqlParameter a = new SqlParameter();
            //SqlParameter b = new SqlParameter("", typeof(int));
            //dataFactory.Query("", a, b);
            //dataFactory.Query("");
            //SqlParameter[] arry = { new SqlParameter(), new SqlParameter("", typeof(int)) };
            //dataFactory.Query("", arry);
        }
        public static void ConstructRepo()
        {
            #region 读取故障项(组件和故障模式)

            Repo.FaultItems.Clear();
            foreach (DataRow row in PumpSysLib.TableFaultItem.Rows)
            {
                Repo.FaultItems.Add(new FaultItem {
                    CompType    = Repo.Map.TypeToEnum[row["TypeName"].ToString()],
                    EventMode   = row["EventMode"].ToString(),
                    Description = row["Description"].ToString(),
                    Advise      = row["Advise"].ToString()
                });
            }

            #endregion


            #region 构建判据

            //读取判据模板
            var ctTemplates = new List <CriterionTemplate>();
            foreach (DataRow row in PumpSysLib.TableCriterionTemplate.Rows)
            {
                ctTemplates.Add(new CriterionTemplate {
                    Id                 = int.Parse(row["ID"].ToString()),
                    Desciption         = row["Description"].ToString(),
                    FuncName           = row["FuncName"].ToString(),
                    ExpressionTemplate = row["ExpressionTemplate"].ToString(),
                    GradeVar           = row["GradeVar"].ToString(),
                    FilteCount         = int.Parse(row["FilteCount"].ToString()),
                    ThresholdField     = row["ThresholdField"].ToString(),
                    AsReportResult     = (bool)row["AsReportResult"]
                });
            }

            //区分模板中带函数的和不带函数的, 并替换 函数名 为 表达式
            var ctTemplates_Func = ctTemplates.Where(ct => !string.IsNullOrEmpty(ct.FuncName)).OrderByDescending(ct => ct.FuncName.Length).ToArray();
            Debug.Assert(ctTemplates_Func.Distinct().Count() == ctTemplates_Func.Length, "判据模板函数必须没有重复");
            Debug.Assert(ctTemplates_Func[0].FuncName.Length >= ctTemplates_Func[1].FuncName.Length, "判据模板函数名必须按函数名长度倒序");
            var ctTemplates_all = ctTemplates;
            foreach (var cttemplate in ctTemplates_all)
            {
                foreach (var cttFunc in ctTemplates_Func)
                {
                    if (cttemplate != cttFunc)
                    {
                        if (cttemplate.ExpressionTemplate.Contains(cttFunc.FuncName))
                        {
                            cttemplate.ExpressionTemplate = cttemplate.ExpressionTemplate.Replace(cttFunc.FuncName, cttFunc.ExpressionTemplate);
                        }
                    }
                }
            }


            //读取要构建的判据表
            var ctToBuildList = new List <CriterionToBuild>();
            foreach (DataRow row in PumpSysLib.TableCriterionToBuild.Rows)
            {
                //                var splitIndex = evMode.IndexOf("_", StringComparison.Ordinal);
                //                var compStr = evMode.Substring(0, splitIndex);
                //                var evModeStr = evMode.Substring()
                var fitem = Repo.FindFaultItem(row["EventMode"].ToString());
                if (fitem != null)
                {
                    var cttb = new CriterionToBuild {
                        CompType   = fitem.CompType,
                        EventMode  = fitem.EventMode,
                        LibId      = int.Parse(row["LibID"].ToString()),
                        TemplateId = int.Parse(row["TemplateID"].ToString()),
                        PosRemark  = row["PosRemark"].ToString(),
                        _VAR_A     = row["_VAR_A"].ToString(),
                        _VAR_B     = row["_VAR_B"].ToString(),
                        _VAR_C     = row["_VAR_C"].ToString(),
                        _VAR_D     = row["_VAR_D"].ToString(),
                    };
                    ctToBuildList.Add(cttb);
                }
                else
                {
                    Log.Error(
                        $"构建判据错误:Access中{nameof(PumpSysLib.TableCriterionToBuild)}故障模式无法读取: {row["EventMode"]}");
                }
            }

            //设置判据
            Repo.Criteria.Clear();
            foreach (var ctToBuild in ctToBuildList)
            {
                var template = ctTemplates_all.FirstOrDefault(tpl => tpl.Id == ctToBuild.TemplateId);
                var fitem    = Repo.FaultItems.FirstOrDefault(fi => fi.IsSameFaultItem(ctToBuild));

                if (template == null)
                {
                    Log.Error($"构建判据错误:ID为{ctToBuild.LibId}的判据模板未找到");
                }
                else if (template.ExpressionTemplate.Contains("PREV"))
                {
                    continue; //不加载带有PREV函数的判据)
                }
                else if (fitem == null)
                {
                    Log.Error($"构建判据错误:{ctToBuild.CompType} AND {ctToBuild.EventMode}的故障项未找到");
                }
                else
                {
                    Criterion ct;
                    if (string.IsNullOrEmpty(template.GradeVar))
                    {
                        ct = new Criterion();
                    }
                    else
                    {
                        ct = new GradedCriterion {
                            ServerityGradeField = template.GradeVar
                        };
                    }
                    ct.LibId      = ctToBuild.LibId;
                    ct.TemplateId = template.Id;
                    ct.CompType   = ctToBuild.CompType;
                    ct.EventMode  = ctToBuild.EventMode;
                    ct.Expression = template.ExpressionTemplate;

                    #region 替换表达式中的_VAR_变量

                    ct.Expression = ct.Expression.Replace(nameof(ctToBuild._VAR_A), ctToBuild._VAR_A);
                    ct.Expression = ct.Expression.Replace(nameof(ctToBuild._VAR_B), ctToBuild._VAR_B);
                    ct.Expression = ct.Expression.Replace(nameof(ctToBuild._VAR_C), ctToBuild._VAR_C);
                    ct.Expression = ct.Expression.Replace(nameof(ctToBuild._VAR_D), ctToBuild._VAR_D);

                    #endregion

                    ct.Description = $"{fitem.Description}({template.Desciption})";
                    ct.Advise      = fitem.Advise;

                    ct.ThresholdField = template.ThresholdField;
                    ct.AsReportResult = template.AsReportResult;

                    //加入到FaultItem中
                    fitem.Criteria.Add(ct);

                    //设置faultitem的阈值字段
                    fitem.ThresholdField = ct.ThresholdField;

                    ct.PosRemark = ctToBuild.PosRemark;

                    Repo.Criteria.Add(ct);
                }
            }

            #endregion


            #region 构建推断组合项列表

            Repo.InferCombos.Clear();
            foreach (DataRow row in PumpSysLib.TableInferCombo.Rows)
            {
                var fItem = Repo.FindFaultItem(row["EventMode"].ToString());

                var icitem = new InferComboItem {
                    EventMode   = fItem.EventMode,
                    CompType    = fItem.CompType,
                    Id          = int.Parse(row["ID"].ToString()),
                    Expression  = row["Expression"].ToString(),
                    FaultResult = row["FaultResult"].ToString(),
                };
                var prevIdsStr = row["PrevIds"].ToString();
                if (!string.IsNullOrEmpty(prevIdsStr))
                {
                    icitem.PrevIds = prevIdsStr.Split(',').Select(int.Parse).ToArray();
                }
                else
                {
                    icitem.PrevIds = new int[] {};
                }
                Repo.InferCombos.Add(icitem);
            }

            #endregion
        }
Ejemplo n.º 54
0
 public override int GetHashCode() => Criterion?.GetHashCode() ?? 0;
Ejemplo n.º 55
0
        protected override IEnumerable <SopInstance> FilterResults(IEnumerable <SopInstance> results)
        {
            var criterion = Criterion.GetInt32(0, 0);

            return(results.Where(s => s.InstanceNumber == criterion));
        }
Ejemplo n.º 56
0
            protected override IEnumerable <SopInstance> FilterResults(IEnumerable <SopInstance> results)
            {
                var criterion = DicomStringHelper.GetStringArray(Criterion.ToString());

                return(results.Where(s => criterion.Contains(s.SopInstanceUid)));
            }
Ejemplo n.º 57
0
        private bool IsBankBranchPresent(BankBranch bankbranch)
        {
            bool      isPresent        = false;
            Query     query            = new Query();
            Criterion criteriaName     = new Criterion(Constants.BANKBRANCHNAME, bankbranch.Name, CriteriaOperator.Equal);
            Criterion criteriaCAId     = new Criterion(Constants.CAID, bankbranch.CAId, CriteriaOperator.Equal);
            Criterion criteriaCAIdNull = new Criterion(Constants.CAID, null, CriteriaOperator.IsNullOrZero);
            Criterion criteriaBankId   = new Criterion("bank.BankId", bankbranch.BranchOfBank.BankId, CriteriaOperator.Equal);

            query.AddAlias(new Alias("bank", "BranchOfBank"));
            Criterion criteriaCV = new Criterion("cv.CityVillageId", bankbranch.BranchAddress.CityVillage.CityVillageId, CriteriaOperator.Equal);

            query.AddAlias(new Alias("ba", "BranchAddress"));
            query.AddAlias(new Alias("cv", "ba.CityVillage"));

            if (bankbranch.CAId == null)
            {
                query.Add(criteriaName);
                query.Add(criteriaCAIdNull);
                query.Add(criteriaBankId);
                query.Add(criteriaCV);
                query.QueryOperator = QueryOperator.And;
                var branchlist = FindByQuery(query);
                isPresent = (branchlist.TotalRecords != 0) ? true : false;
                //For Update Scenario
                if (isPresent && branchlist.TotalRecords == 1 && branchlist.Entities.ToList().FirstOrDefault().BranchId == bankbranch.BranchId)
                {
                    isPresent = false;
                }
            }
            else
            {
                query.Add(criteriaName);
                query.Add(criteriaBankId);
                query.Add(criteriaCV);

                Query subquery = new Query();
                subquery.Add(criteriaCAId);
                subquery.Add(criteriaCAIdNull);
                subquery.QueryOperator = QueryOperator.Or;
                query.AddSubQuery(subquery);

                query.QueryOperator = QueryOperator.And;
                query.CAId          = (int)bankbranch.CAId;

                var branchlist = FindByQuery(query);
                IEnumerable <BankBranchDto> bankbranchDtoList = branchlist.Entities.AsEnumerable();
                isPresent = (bankbranchDtoList.Count() != 0) ? true : false;
                //For Update Scenario
                if (bankbranchDtoList.Count() == 1 && bankbranchDtoList.FirstOrDefault().BranchId == bankbranch.BranchId)
                {
                    isPresent = false;
                }
                if (bankbranchDtoList.Count() == 1 && bankbranchDtoList.FirstOrDefault().BranchId == bankbranch.BaseBranchId)
                {
                    isPresent = false;
                }
            }

            return(isPresent);
        }
Ejemplo n.º 58
0
        /// <summary>
        /// yc: this copy the rubric information from one assignment to another.
        /// </summary>
        /// <param name="Source"></param>
        /// <param name="Destination"></param>
        /// <returns>bool for if success or fail</returns>
        public bool CopyRubric(Assignment Source, Assignment Destination)
        {
            try
            {
                int sid = -1;

                if (Source.RubricID != null)
                {
                    sid = (int)Source.RubricID;
                    //create a new reburic thats an exact copy with the same critera
                    Rubric nr = new Rubric();
                    nr.HasGlobalComments        = Source.Rubric.HasGlobalComments;
                    nr.HasCriteriaComments      = Source.Rubric.HasCriteriaComments;
                    nr.EnableHalfStep           = Source.Rubric.EnableHalfStep;
                    nr.EnableQuarterStep        = Source.Rubric.EnableQuarterStep;
                    nr.Description              = Source.Rubric.Description;
                    Destination.Rubric          = nr;
                    db.Entry(Destination).State = EntityState.Modified;
                    db.SaveChanges();

                    //now get all the stuff for it
                    Dictionary <int, int> clevelHolder     = new Dictionary <int, int>();
                    Dictionary <int, int> ccriterionHolder = new Dictionary <int, int>();

                    List <Level> pls = (from rl in db.Levels
                                        where rl.RubricID == sid
                                        select rl).ToList();
                    foreach (Level pl in pls)
                    {
                        Level nl = new Level();
                        nl.LevelTitle  = pl.LevelTitle;
                        nl.PointSpread = pl.PointSpread;
                        nl.RubricID    = nr.ID;
                        db.Levels.Add(nl);
                        db.SaveChanges();
                        clevelHolder.Add(pl.ID, nl.ID);
                    }

                    List <Criterion> prcs = (from rc in db.Criteria
                                             where rc.RubricID == sid
                                             select rc).ToList();

                    foreach (Criterion prc in prcs) //create a new criteron
                    {
                        Criterion nrc = new Criterion();
                        nrc.CriterionTitle = prc.CriterionTitle;
                        nrc.Weight         = prc.Weight;
                        nrc.RubricID       = nr.ID;
                        db.Criteria.Add(nrc);
                        db.SaveChanges();
                        ccriterionHolder.Add(prc.ID, nrc.ID);
                    }

                    //now descriptions
                    //for some reason, cell descriptions do not come with this assignment so lets do a search fo rit
                    List <CellDescription> pcds = (from cd in db.CellDescriptions
                                                   where cd.RubricID == sid
                                                   select cd).ToList();

                    foreach (CellDescription pcd in pcds)
                    {
                        CellDescription ncd = new CellDescription();
                        ncd.CriterionID = ccriterionHolder[pcd.CriterionID];
                        ncd.LevelID     = clevelHolder[pcd.LevelID];
                        ncd.RubricID    = nr.ID;
                        ncd.Description = pcd.Description;
                        db.CellDescriptions.Add(ncd);
                        db.SaveChanges();
                    }
                }
                if (Source.StudentRubricID != null)
                {
                    sid = (int)Source.StudentRubricID;
                    //create a new reburic thats an exact copy with the same critera
                    Rubric nr = new Rubric();
                    nr.HasGlobalComments   = Source.Rubric.HasGlobalComments;
                    nr.HasCriteriaComments = Source.Rubric.HasCriteriaComments;
                    nr.EnableHalfStep      = Source.Rubric.EnableHalfStep;
                    nr.EnableQuarterStep   = Source.Rubric.EnableQuarterStep;
                    nr.Description         = Source.Rubric.Description;

                    db.Rubrics.Add(nr);
                    db.SaveChanges();

                    Destination.StudentRubricID = nr.ID;
                    db.Entry(Destination).State = EntityState.Modified;
                    db.SaveChanges();

                    //now get all the stuff for it
                    Dictionary <int, int> slevelHolder     = new Dictionary <int, int>();
                    Dictionary <int, int> scriterionHolder = new Dictionary <int, int>();

                    List <Level> pls = (from rl in db.Levels
                                        where rl.RubricID == sid
                                        select rl).ToList();
                    foreach (Level pl in pls)
                    {
                        Level nl = new Level();
                        nl.LevelTitle  = pl.LevelTitle;
                        nl.PointSpread = pl.PointSpread;
                        nl.RubricID    = nr.ID;
                        db.Levels.Add(nl);
                        db.SaveChanges();
                        slevelHolder.Add(pl.ID, nl.ID);
                    }

                    List <Criterion> prcs = (from rc in db.Criteria
                                             where rc.RubricID == sid
                                             select rc).ToList();

                    foreach (Criterion prc in prcs) //create a new criteron
                    {
                        Criterion nrc = new Criterion();
                        nrc.CriterionTitle = prc.CriterionTitle;
                        nrc.Weight         = prc.Weight;
                        nrc.RubricID       = nr.ID;
                        db.Criteria.Add(nrc);
                        db.SaveChanges();
                        scriterionHolder.Add(prc.ID, nrc.ID);
                    }

                    //now descriptions
                    //for some reason, cell descriptions do not come with this assignment so lets do a search fo rit
                    List <CellDescription> pcds = (from cd in db.CellDescriptions
                                                   where cd.RubricID == sid
                                                   select cd).ToList();

                    foreach (CellDescription pcd in pcds)
                    {
                        CellDescription ncd = new CellDescription();
                        ncd.CriterionID = scriterionHolder[pcd.CriterionID];
                        ncd.LevelID     = slevelHolder[pcd.LevelID];
                        ncd.RubricID    = nr.ID;
                        ncd.Description = pcd.Description;
                        db.CellDescriptions.Add(ncd);
                        db.SaveChanges();
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 59
0
 public void Add(Criterion criteria)
 {
     _criteria.Add(criteria);
 }
Ejemplo n.º 60
0
 private void ParseCriterion()
 {
     _parsedCriterion = true;
     DateRangeHelper.Parse(Criterion.GetString(0, ""), out _date1, out _date2, out _isRange);
 }