Пример #1
0
        public static void Add3DPolygon(LocalVectorDataSource source, Projection projection)
        {
            // Create 3d polygon style and poses
            Polygon3DStyleBuilder polygon3DStyleBuilder = new Polygon3DStyleBuilder();
            polygon3DStyleBuilder.Color = new Color(51, 51, 255, 255);

            MapPosVector polygon3DPoses = new MapPosVector();
            polygon3DPoses.Add(projection.FromWgs84(new MapPos(24.635930, 59.416659)));
            polygon3DPoses.Add(projection.FromWgs84(new MapPos(24.642453, 59.411354)));
            polygon3DPoses.Add(projection.FromWgs84(new MapPos(24.646187, 59.409607)));
            polygon3DPoses.Add(projection.FromWgs84(new MapPos(24.652667, 59.413123)));
            polygon3DPoses.Add(projection.FromWgs84(new MapPos(24.650736, 59.416703)));
            polygon3DPoses.Add(projection.FromWgs84(new MapPos(24.646444, 59.416245)));

            // Create 3d polygon holes poses
            MapPosVector holePositions = new MapPosVector();
            holePositions.Add(projection.FromWgs84(new MapPos(24.643409, 59.411922)));
            holePositions.Add(projection.FromWgs84(new MapPos(24.651207, 59.412896)));
            holePositions.Add(projection.FromWgs84(new MapPos(24.643207, 59.414411)));

            MapPosVectorVector holes = new MapPosVectorVector();
            holes.Add(holePositions);

            // Add to datasource
            Polygon3D polygon = new Polygon3D(polygon3DPoses, holes, polygon3DStyleBuilder.BuildStyle(), 150);
            polygon.SetMetaDataElement("ClickText", new Variant("Polygon 3D"));
            source.Add(polygon);
        }
        public void with_the_normal_casing()
        {
            var projection = new Projection<SomeTarget>();

            //projection.CamelCaseAttributeNames();
            projection.Value(x => x.Name);
            projection.Value(x => x.Age);
            projection.Child(x => x.Child).Configure(_ =>
            {
                _.Value(x => x.Name);
            });

            var node = new DictionaryMediaNode();
            var someTarget = new SomeTarget
            {
                Active = true,
                Age = 40,
                Name = "Jeremy",
                Child = new SomeChild { Name = "Max" }
            };

            projection.As<IProjection<SomeTarget>>().Write(new ProjectionContext<SomeTarget>(new InMemoryServiceLocator(), someTarget), node);

            node.Values["Name"].ShouldEqual("Jeremy");
            node.Values["Age"].ShouldEqual(40);

            node.Values["Child"].As<IDictionary<string, object>>()["Name"].ShouldEqual("Max");
        }
Пример #3
0
        //获取polygon内部的点
        public List<PointF> getInnerPoints()
        {
            List<PointF> pts = new List<PointF>();

            getBbox(cfg.resolution);

            for (int i = 0; i < bbox.Count;i++ )
            {
                if (InPolygon(ContourGeomes, bbox[i]))

            //    //-----------nettopologysuite method-----
            //    //GeoAPI.Geometries.IGeometryFactory gfact = new GeometryFactory();
            //    //GeoAPI.Geometries.IPoint ipoint;
            //    //ipoint = gfact.CreatePoint(new GeoAPI.Geometries.Coordinate(bbox[i].X, bbox[i].Y));
            //    //bool a = polygon.Contains(ipoint);
            //    //if (polygon != null && a)

                {
                    //将经纬度坐标转为大地坐标
                    PointF tmppoint = new PointF();
                    Projection pj = new Projection();
                    tmppoint = pj.GetXYFromLatLon(bbox[i],cfg.pjPara);
                    pts.Add(tmppoint);
                }

            }

            ////random points builder
            //NetTopologySuite.Shape.Random.RandomPointsBuilder rpb = new NetTopologySuite.Shape.Random.RandomPointsBuilder();
            //rpb.SetExtent(polygon);
            //IGeometry testGeo = rpb.GetGeometry();
            //testGeo.

                return pts;
        }
        public static Contact Load(this IContactService service, int id, Action<IProjection<Contact>> projection)
        {
            var contactProjection = new Projection<Contact>();
            projection(contactProjection);

            return service.Load(id, contactProjection.Build());
        }
 internal ProjectionInitializerInvocation(
     Projection                projection,
     Cell<IProjectionBehavior> behavior)
 {
     this.projection = projection;
     this.behavior   = behavior;
 }
        public static IEnumerable<Contact> FindByEmail(this IContactService service, string email,
                                                       Action<IProjection<Contact>> fieldSelection)
        {
            var projection = new Projection<Contact>();
            fieldSelection(projection);

            return service.FindByEmail(email, projection.Build());
        }
        public async Task A_stream_can_be_derived_from_an_index_projection_in_order_to_perform_a_reduce_operation()
        {
            store.WriteEvents(i => new AccountOpened
            {
                AccountType = i%2 == 0
                    ? BankAccountType.Checking
                    : BankAccountType.Savings
            }, howMany: 100);

            var eventsByAggregate = streamSource.StreamPerAggregate()
                                                .Trace()
                                                .Map(ss => ss.Select(s => s.Trace()));

            var indexCatchup = StreamCatchup.All(eventsByAggregate, batchSize: 1);
            var index = new Projection<ConcurrentBag<AccountOpened>, string>
            {
                Value = new ConcurrentBag<AccountOpened>()
            };

            // subscribe a catchup to the updates stream to build up an index
            indexCatchup.Subscribe(
                Aggregator.Create<Projection<ConcurrentBag<AccountOpened>>, IDomainEvent>(async (p, events) =>
                {
                    foreach (var e in events.OfType<AccountOpened>()
                                            .Where(e => e.AccountType == BankAccountType.Savings))
                    {
                        p.Value.Add(e);
                    }

                    return p;
                }).Trace(),
                async (streamId, aggregate) => await aggregate(index));

            // create a catchup over the index
            var savingsAccounts = Stream.Create<IDomainEvent, string>(
                "Savings accounts",
                async q => index.Value.SkipWhile(v => q.Cursor.HasReached(v.CheckpointToken))
                                .Take(q.BatchSize ?? 1000));
            var savingsAccountsCatchup = StreamCatchup.Create(savingsAccounts);

            var numberOfSavingsAccounts = new Projection<int, int>();
            savingsAccountsCatchup.Subscribe<Projection<int, int>, IDomainEvent, string>(
                manageProjection: async (streamId, aggregate) =>
                {
                    numberOfSavingsAccounts = await aggregate(numberOfSavingsAccounts);
                },
                aggregate: async (c, es) =>
                {
                    c.Value += es.Count;
                    return c;
                });

            using (indexCatchup.Poll(TimeSpan.FromMilliseconds(100)))
            using (savingsAccountsCatchup.Poll(TimeSpan.FromMilliseconds(50)))
            {
                await Wait.Until(() => numberOfSavingsAccounts.Value >= 50);
            }
        }
Пример #8
0
        public void TestFromCategory()
        {
            var subject = new Projection ("test")
                .FromCategory ("$stats");

            var actual = subject.ToJson ();

            actual.Should ().Be ("fromCategory('$stats')");
        }
Пример #9
0
 public void Projection_Forward()
 {
     Projection merc = new Projection("+init=epsg:3857");
     double[] latlong = new double[] { -122.33517, 47.63752 };
     double[] expected = new double[] { -13618288.8305, 6046761.54747 };
     double[] actual = merc.Forward(latlong[0], latlong[1]);
     Assert.AreEqual(expected[0], actual[0], .0001);
     Assert.AreEqual(expected[1], actual[1], .0001);
 }
Пример #10
0
 internal PropertySetterInvocation(
     Projection                projection,
     ProjectionProperty        property,
     Cell<IProjectionBehavior> behavior)
 {
     this.projection = projection;
     this.property   = property;
     this.behavior   = behavior;
 }
Пример #11
0
 /// <summary>
 /// Gibt an, ob sich 2 Projektionen überlagern.
 /// </summary>
 /// <param name="first">erste Projektion</param>
 /// <param name="second">zweite Projetion</param>
 /// <returns>überlagern die Projektionen sich</returns>
 public static bool Overlap(Projection first, Projection second)
 {
     if(first.Min < second.Min && second.Min < first.Max ||
        first.Max < second.Max && second.Max < first.Max)
         return true;
     if(second.Min < first.Min && first.Min < second.Max ||
        second.Min < first.Max && first.Max < first.Max)
         return true;
     return false;
 }
Пример #12
0
        /// <summary>
        /// Gibt den Wert an, mit dem sich 2 Projektionen überlagern.
        /// </summary>
        /// <param name="first">erste Projektion</param>
        /// <param name="second">zweite Projetion</param>
        /// <returns>Wert der Überlagerung</returns>
        public static float GetOverlap(Projection first, Projection second)
        {
            float firstOverlap = first.Max - second.Min;
            float secondOverlap = second.Max - first.Min;

            if(firstOverlap < secondOverlap)
                return firstOverlap;
            else
                return secondOverlap;
        }
        public static void ApplyMVPNParameter(OpenGL gl, ExtShaderProgram esp, Projection pr, ModelView mv, Normal nrml)
        {
            var prms = esp.Parameters as IMVPNParameters;
            var p = esp.Program;

            // Set the matrices.
            p.SetUniformMatrix4(gl, prms.ProjectionMatrixId, pr.ToArray());
            p.SetUniformMatrix4(gl, prms.ModelviewMatrixId, mv.ToArray());
            p.SetUniformMatrix3(gl, prms.NormalMatrixId, nrml.ToArray());
        }
        public void project_with_the_for_attribute_and_func_to_massage_the_data()
        {
            var projection = new Projection<Address>(DisplayFormatting.RawValues);

            projection.ForAttribute("anything").ValueFrom(x => x.Line1).Use(value => "aaa" + value);

            projection.As<IProjection<Address>>().Write(new ProjectionContext<Address>(null, aTarget), aNode);

            aNode.Element.GetAttribute("anything").ShouldEqual("aaa" + anAddress.Line1);
        }
Пример #15
0
        public void TestFromStreams()
        {
            var subject = new Projection ("test")
                .FromStreams (new[] {"stream1", "stream2", "stream3"})
                .WhenAny ((s, e) => null);

            var actual = subject.ToJson ();

            actual.Should ().Be ("fromStreams(['stream1','stream2','stream3']).whenAny(function(s,e) { return null; })");
        }
        public void project_with_the_for_attribute_method()
        {
            var projection = new Projection<Address>(DisplayFormatting.RawValues);

            projection.ForAttribute("anything").Use(context => "aaa" + context.ValueFor(x => x.Line1));

            projection.As<IProjection<Address>>().Write(new ProjectionContext<Address>(null, aTarget), aNode);

            aNode.Element.GetAttribute("anything").ShouldEqual("aaa" + anAddress.Line1);
        }
Пример #17
0
        public void TestFromAllSomeEvent()
        {
            var subject = new Projection("test")
                .FromAll ()
                .When("someEvent", (s, e) => null);

            var actual = subject.ToJson ();

            actual.Should ().Be ("fromAll().when({ 'someEvent':function(s,e) { return null; } })");
        }
Пример #18
0
        public void TestFromStream()
        {
            var subject = new Projection ("test")
                .FromStream ("events")
                .WhenAny((s, e) => null);

            var actual = subject.ToJson ();

            actual.Should ().Be ("fromStream('events').whenAny(function(s,e) { return null; })");
        }
Пример #19
0
        public void TestFromAllInit()
        {
            var subject = new Projection("test")
                .FromAll ()
                .Init(() => null);

            var actual = subject.ToJson ();

            actual.Should ().Be ("fromAll().when({ '$init':function() { return null; } })");
        }
Пример #20
0
 public void Projection_Inverse()
 {
     Projection merc = new Projection("+init=epsg:3857");
     double[] mercCoords = new double[] { -13627804.8659, 6041391.68077, -13608084.1728, 6053392.19471 };
     double[] expected = new double[] { -122.420654, 47.605006, -122.2435, 47.67764 };
     double[] actual = merc.Inverse(mercCoords[0], mercCoords[1], mercCoords[2], mercCoords[3]);
     Assert.AreEqual(expected[0], actual[0], .0001);
     Assert.AreEqual(expected[1], actual[1], .0001);
     Assert.AreEqual(expected[2], actual[2], .0001);
     Assert.AreEqual(expected[3], actual[3], .0001);
 }
        public void accessors()
        {
            var projection = new Projection<Address>(DisplayFormatting.RawValues);
            projection.Value(x => x.Address1);
            projection.Value(x => x.Address2);
            projection.Value(x => x.City);
            projection.Value(x => x.State);

            projection.As<IProjection<Address>>().Accessors().Select(x => x.Name)
                .ShouldHaveTheSameElementsAs("Address1", "Address2", "City", "State");
        }
Пример #22
0
 internal PropertyGetterInvocation(
     Projection                projection,
     ProjectionProperty        property,
     GetterOptions         options,
     Cell<IProjectionBehavior> behavior)
 {
     this.projection = projection;
     this.property   = property;
     this.options    = options;
     this.behavior   = behavior;
 }
        public void filter()
        {
            var projection = new Projection<Address>(DisplayFormatting.RawValues);
            projection.Value(x => x.Address1);
            projection.Value(x => x.Address2);
            projection.Value(x => x.City);
            projection.Value(x => x.State);

            var filtered = projection.Filter(a => a.Name.StartsWith("A"));
            filtered.As<IProjection<Address>>().Accessors().Select(x => x.Name)
                .ShouldHaveTheSameElementsAs("Address1", "Address2");
        }
        public void write_node_with_inline_writer()
        {
            var projection = new Projection<Address>(DisplayFormatting.RawValues);
            projection.WriteWith((context, node) =>
            {
                node.AddChild("address").SetAttribute("description", "I was here");
            });

            projection.As<IProjection<Address>>().Write(new ProjectionContext<Address>(null, aTarget), aNode);

            aNode.Element.InnerXml.ShouldEqual("<address description=\"I was here\" />");
        }
Пример #25
0
        public static void Add3DCar(LocalVectorDataSource source, Projection projection)
        {
            // Add a single 3D model to the vector layer
            // Be sure to add milktruck.nml to your *Assets*, not Drawable, folder (Android)
            string name = "milktruck.nml";

            MapPos modelPos = projection.FromWgs84(new MapPos(24.646469, 59.423939));
            NMLModel model = new NMLModel(modelPos, AssetUtils.LoadAsset(name));

            model.Scale = 20;
            model.SetMetaDataElement("ClickText", new Variant("Single model"));

            source.Add(model);
        }
Пример #26
0
        public void ProjTransform_Forward()
        {
            Projection src = new Projection("+init=epsg:4326");
            Projection dest = new Projection("+init=epsg:3857");
            ProjTransform tran = new ProjTransform(src, dest);
            double x = -122.33517;
            double y = 47.63752;
            double[] expected = new double[] { -13618288.8305, 6046761.54747 };

            //forward
            double[] actual = tran.Forward(x, y);
            Assert.AreEqual(expected[0], actual[0], .0001);
            Assert.AreEqual(expected[1], actual[1], .0001);
        }
Пример #27
0
        public void write_a_node_with_multiple_properties()
        {
            var projection = new Projection<Address>();
            projection.Value(x => x.Line1);
            projection.Value(x => x.City);
            projection.Value(x => x.State);
            projection.Value(x => x.ZipCode);

            projection.As<IValueProjection<Address>>().WriteValue(aTarget, aNode);

            aNode.Element.GetAttribute("Line1").ShouldEqual(anAddress.Line1);
            aNode.Element.GetAttribute("City").ShouldEqual(anAddress.City);
            aNode.Element.GetAttribute("State").ShouldEqual(anAddress.State);
            aNode.Element.GetAttribute("ZipCode").ShouldEqual(anAddress.ZipCode);
        }
        public void write_a_node_with_multiple_properties()
        {
            var projection = new Projection<Address>(DisplayFormatting.RawValues);
            projection.Value(x => x.Line1);
            projection.Value(x => x.City);
            projection.Value(x => x.State);
            projection.Value(x => x.ZipCode);


            projection.As<IProjection<Address>>().Write(new ProjectionContext<Address>(null, aTarget), aNode);

            aNode.Element.GetAttribute("Line1").ShouldEqual(anAddress.Line1);
            aNode.Element.GetAttribute("City").ShouldEqual(anAddress.City);
            aNode.Element.GetAttribute("State").ShouldEqual(anAddress.State);
            aNode.Element.GetAttribute("ZipCode").ShouldEqual(anAddress.ZipCode);
        }
Пример #29
0
        public void ProjTransform_NoChange()
        {
            Projection src = new Projection("+init=epsg:4326");
            Projection dest = new Projection("+init=epsg:4326");
            ProjTransform tran = new ProjTransform(src, dest);
            double[] expected = new double[] { -122.33517, 47.63752 };

            //forward
            double[] actual = tran.Forward(expected[0], expected[1]);
            Assert.AreEqual(expected[0], actual[0]);
            Assert.AreEqual(expected[1], actual[1]);

            //backward
            actual = tran.Backward(expected[0], expected[1]);
            Assert.AreEqual(expected[0], actual[0]);
            Assert.AreEqual(expected[1], actual[1]);
        }
Пример #30
0
        public void project_the_property_with_formatting_thru_display_formatter()
        {
            var projection = new Projection<Address>(DisplayFormatting.UseDisplayFormatting);
            projection.Value(x => x.Line1);

            var services = MockRepository.GenerateMock<IServiceLocator>();
            var formatter = MockRepository.GenerateMock<IDisplayFormatter>();
            services.Stub(x => x.GetInstance<IDisplayFormatter>()).Return(formatter);

            var accessor = ReflectionHelper.GetAccessor<Address>(x => x.Line1);
            var theFormattedValue = "formatted value";

            formatter.Stub(x => x.GetDisplayForValue(accessor, anAddress.Line1)).Return(theFormattedValue);

            var node = new DictionaryMediaNode();
            projection.As<IProjection<Address>>().Write(new ProjectionContext<Address>(services, aTarget), node);
            node.Values["Line1"].ShouldEqual(theFormattedValue);
        }
Пример #31
0
        public async Task <IReadOnlyList <Guid> > QueryNotFoundAsync(Guid appId, Guid schemaId, IList <Guid> contentIds)
        {
            var collection = GetCollection(appId);

            var contentEntities =
                await collection.Find(x => contentIds.Contains(x.Id) && x.AppId == appId).Project <BsonDocument>(Projection.Include(x => x.Id))
                .ToListAsync();

            return(contentIds.Except(contentEntities.Select(x => Guid.Parse(x["_id"].AsString))).ToList());
        }
 public static PurchaseOrderItemView Create(StockBatch po_item)
 {
     return(Projection.Compile().Invoke(po_item));
 }
Пример #33
0
        protected override Expression VisitChildren(ExpressionVisitor visitor)
        {
            var changed = false;

            var projections = new List <ProjectionExpression>();
            IDictionary <ProjectionMember, Expression> projectionMapping;

            if (Projection.Any())
            {
                projectionMapping = _projectionMapping;
                foreach (var item in Projection)
                {
                    var projection = (ProjectionExpression)visitor.Visit(item);
                    projections.Add(projection);

                    changed |= projection != item;
                }
            }
            else
            {
                projectionMapping = new Dictionary <ProjectionMember, Expression>();
                foreach (var mapping in _projectionMapping)
                {
                    var newProjection = visitor.Visit(mapping.Value);
                    changed |= newProjection != mapping.Value;

                    projectionMapping[mapping.Key] = newProjection;
                }
            }

            var tables = new List <TableExpressionBase>();

            foreach (var table in _tables)
            {
                var newTable = (TableExpressionBase)visitor.Visit(table);
                changed |= newTable != table;
                tables.Add(newTable);
            }

            var predicate = (SqlExpression)visitor.Visit(Predicate);

            changed |= predicate != Predicate;

            var orderings = new List <OrderingExpression>();

            foreach (var ordering in _orderings)
            {
                var orderingExpression = (SqlExpression)visitor.Visit(ordering.Expression);
                changed |= orderingExpression != ordering.Expression;
                orderings.Add(ordering.Update(orderingExpression));
            }

            var offset = (SqlExpression)visitor.Visit(Offset);

            changed |= offset != Offset;

            var limit = (SqlExpression)visitor.Visit(Limit);

            changed |= limit != Limit;

            if (changed)
            {
                var newSelectExpression = new SelectExpression(Alias, projections, tables, orderings)
                {
                    _projectionMapping = projectionMapping,
                    Predicate          = predicate,
                    Offset             = offset,
                    Limit      = limit,
                    IsDistinct = IsDistinct
                };

                return(newSelectExpression);
            }

            return(this);
        }
Пример #34
0
 public static Matrix4 CreateProjection(Projection p) => CreateProjection(p, new Size(16, 9));
Пример #35
0
        protected override void ApplyDocumentTextChanged(DocumentId id, SourceText text)
        {
            var document = GetDocument(id);

            if (document == null)
            {
                return;
            }
            bool isOpen;
            var  filePath = document.FilePath;
            var  data     = TextFileProvider.Instance.GetTextEditorData(filePath, out isOpen);

            // Guard against already done changes in linked files.
            // This shouldn't happen but the roslyn merging seems not to be working correctly in all cases :/
            if (document.GetLinkedDocumentIds().Length > 0 && isOpen && !(text.GetType().FullName == "Microsoft.CodeAnalysis.Text.ChangedText"))
            {
                return;
            }
            SourceText formerText;

            if (changedFiles.TryGetValue(filePath, out formerText))
            {
                if (formerText.Length == text.Length && formerText.ToString() == text.ToString())
                {
                    return;
                }
            }
            changedFiles [filePath] = text;

            Projection projection = null;

            foreach (var entry in ProjectionList)
            {
                var p = entry.Projections.FirstOrDefault(proj => FilePath.PathComparer.Equals(proj.Document.FileName, filePath));
                if (p != null)
                {
                    filePath   = entry.File.FilePath;
                    projection = p;
                    break;
                }
            }
            SourceText oldFile;

            if (!isOpen || !document.TryGetText(out oldFile))
            {
                oldFile = new MonoDevelopSourceText(data);
            }
            var changes = text.GetTextChanges(oldFile).OrderByDescending(c => c.Span.Start).ToList();
            int delta   = 0;

            if (!isOpen)
            {
                delta = ApplyChanges(projection, data, changes);
                var    formatter   = CodeFormatterService.GetFormatter(data.MimeType);
                var    mp          = GetMonoProject(CurrentSolution.GetProject(id.ProjectId));
                string currentText = data.Text;

                foreach (var change in changes)
                {
                    delta -= change.Span.Length - change.NewText.Length;
                    var startOffset = change.Span.Start - delta;

                    if (projection != null)
                    {
                        int originalOffset;
                        if (projection.TryConvertFromProjectionToOriginal(startOffset, out originalOffset))
                        {
                            startOffset = originalOffset;
                        }
                    }

                    string str;
                    if (change.NewText.Length == 0)
                    {
                        str = formatter.FormatText(mp.Policies, currentText, TextSegment.FromBounds(Math.Max(0, startOffset - 1), Math.Min(data.Length, startOffset + 1)));
                    }
                    else
                    {
                        str = formatter.FormatText(mp.Policies, currentText, new TextSegment(startOffset, change.NewText.Length));
                    }
                    data.ReplaceText(startOffset, change.NewText.Length, str);
                }
                data.Save();
                OnDocumentTextChanged(id, new MonoDevelopSourceText(data), PreservationMode.PreserveValue);
                FileService.NotifyFileChanged(filePath);
            }
            else
            {
                var formatter       = CodeFormatterService.GetFormatter(data.MimeType);
                var documentContext = IdeApp.Workbench.Documents.FirstOrDefault(d => FilePath.PathComparer.Compare(d.FileName, filePath) == 0);
                if (documentContext != null)
                {
                    var editor = (TextEditor)data;
                    using (var undo = editor.OpenUndoGroup()) {
                        delta = ApplyChanges(projection, data, changes);

                        foreach (var change in changes)
                        {
                            delta -= change.Span.Length - change.NewText.Length;
                            var startOffset = change.Span.Start - delta;
                            if (projection != null)
                            {
                                int originalOffset;
                                if (projection.TryConvertFromProjectionToOriginal(startOffset, out originalOffset))
                                {
                                    startOffset = originalOffset;
                                }
                            }
                            if (change.NewText.Length == 0)
                            {
                                formatter.OnTheFlyFormat(editor, documentContext, TextSegment.FromBounds(Math.Max(0, startOffset - 1), Math.Min(data.Length, startOffset + 1)));
                            }
                            else
                            {
                                formatter.OnTheFlyFormat(editor, documentContext, new TextSegment(startOffset, change.NewText.Length));
                            }
                        }
                    }
                }
                OnDocumentTextChanged(id, new MonoDevelopSourceText(data.CreateDocumentSnapshot()), PreservationMode.PreserveValue);
                Runtime.RunInMainThread(() => {
                    if (IdeApp.Workbench != null)
                    {
                        foreach (var w in IdeApp.Workbench.Documents)
                        {
                            w.StartReparseThread();
                        }
                    }
                });
            }
        }
        public static async Task PayInterestForSpecificAccount
            ([ActivityTrigger] IDurableActivityContext payInterestContext)
        {
            string accountNumber = payInterestContext.GetInput <string>();

            #region Tracing telemetry
            Activity.Current.AddTag("Account Number", accountNumber);
            #endregion

            Command cmdPayInterest = new Command(
                new CommandAttribute("Bank",
                                     "Pay Interest",
                                     payInterestContext.InstanceId)
                );

            if (!string.IsNullOrWhiteSpace(accountNumber))
            {
                string result = "";

                await cmdPayInterest.InitiateStep(AccountCommands.COMMAND_STEP_PAY_INTEREST,
                                                  "Bank",
                                                  "Account",
                                                  accountNumber);

                // 1- Get interest due...
                Projection prjInterestDue = new Projection(
                    new ProjectionAttribute(
                        "Bank",
                        "Account",
                        accountNumber,
                        nameof(InterestDue)
                        )
                    );

                // get the interest owed / due as now
                InterestDue interestDue = await prjInterestDue.Process <InterestDue>();

                if (null != interestDue)
                {
                    // pay the interest
                    decimal amountToPay = decimal.Round(interestDue.Due, 2, MidpointRounding.AwayFromZero);
                    if (amountToPay != 0.00M)
                    {
                        EventStream bankAccountEvents = new EventStream(
                            new EventStreamAttribute(
                                "Bank",
                                "Account",
                                accountNumber
                                )
                            );

                        InterestPaid evInterestPaid = new InterestPaid()
                        {
                            AmountPaid = decimal.Round(interestDue.Due, 2, MidpointRounding.AwayFromZero),
                            Commentary = $"Interest due {interestDue.Due} as at {interestDue.CurrentSequenceNumber}"
                        };
                        await bankAccountEvents.AppendEvent(evInterestPaid);

                        result = $"Interest paid: {evInterestPaid.AmountPaid} ({evInterestPaid.Commentary})";
                    }
                }

                await cmdPayInterest.StepCompleted(AccountCommands.COMMAND_STEP_PAY_INTEREST,
                                                   result,
                                                   "Bank",
                                                   "Account",
                                                   accountNumber);
            }
        }
Пример #37
0
        //private void ReflectionLaziness()
        //{
        //    Actions = new Dictionary<string, Action>();
        //    var operators = Assembly.GetExecutingAssembly().GetTypes()
        //        .Where(t => t.IsClass && t.GetInterface("IOperator") != null);

        //    foreach (var item in operators)
        //    {
        //        object obj = Activator.CreateInstance(item);

        //        var methods = item.GetMethods();
        //        foreach (var method in methods)
        //        {
        //            method.
        //            Actions.Add(method.Name, )
        //        }
        //    }
        //}

        private void ManualWithNimbleText()
        {
            Aggregation   Aggregation   = new Aggregation();
            Concatenation Concatenation = new Concatenation();
            Conversion    Conversion    = new Conversion();
            Element       Element       = new Element();
            Equal         Equal         = new Equal();
            Filter        Filter        = new Filter();
            Generate      Generate      = new Generate();
            Group         Group         = new Group();
            JoinOperation JoinOperation = new JoinOperation();
            Partition     Partition     = new Partition();
            Projection    Projection    = new Projection();
            Quantifier    Quantifier    = new Quantifier();
            Set           Set           = new Set();
            Sorting       Sorting       = new Sorting();

            Actions = new Dictionary <string, Action>();

            Actions.Add("OrderBy", Sorting.OrderBy);
            Actions.Add("OrderByDescending", Sorting.OrderByDescending);
            Actions.Add("ThenBy", Sorting.ThenBy);
            Actions.Add("ThenByDescending", Sorting.ThenByDescending);
            Actions.Add("Reverse", Sorting.Reverse);
            Actions.Add("Where", Filter.Where);
            Actions.Add("OfType", Filter.OfType);
            Actions.Add("Join", JoinOperation.Join);
            Actions.Add("GroupJoin", JoinOperation.GroupJoin);
            Actions.Add("SequenceEqual", Equal.SequenceEqual);
            Actions.Add("Concat", Concatenation.Concat);
            Actions.Add("GroupBy", Group.GroupBy);
            Actions.Add("ToLookup", Group.ToLookup);
            Actions.Add("DefaultIfEmpty", Generate.DefaultIfEmpty);
            Actions.Add("Empty", Generate.Empty);
            Actions.Add("Range", Generate.Range);
            Actions.Add("Repeat", Generate.Repeat);
            Actions.Add("Select", Projection.Select);
            Actions.Add("SelectMany", Projection.SelectMany);
            Actions.Add("All", Quantifier.All);
            Actions.Add("Any", Quantifier.Any);
            Actions.Add("Contains", Quantifier.Contains);
            Actions.Add("Distinct", Set.Distinct);
            Actions.Add("Except", Set.Except);
            Actions.Add("Intersect", Set.Intersect);
            Actions.Add("Union", Set.Union);
            Actions.Add("Skip", Partition.Skip);
            Actions.Add("SkipWhile", Partition.SkipWhile);
            Actions.Add("Take", Partition.Take);
            Actions.Add("TakeWhile", Partition.TakeWhile);
            Actions.Add("ElementAt", Element.ElementAt);
            Actions.Add("ElementAtOrDefault", Element.ElementAtOrDefault);
            Actions.Add("First", Element.First);
            Actions.Add("FirstOrDefault", Element.FirstOrDefault);
            Actions.Add("Last", Element.Last);
            Actions.Add("LastOrDefault", Element.LastOrDefault);
            Actions.Add("Single", Element.Single);
            Actions.Add("SingleOrDefault", Element.SingleOrDefault);
            Actions.Add("AsEnumerable", Conversion.AsEnumerable);
            Actions.Add("AsQueryable", Conversion.AsQueryable);
            Actions.Add("Cast", Conversion.Cast);
            Actions.Add("ToArray", Conversion.ToArray);
            Actions.Add("ToDictionary", Conversion.ToDictionary);
            Actions.Add("ToList", Conversion.ToList);
            Actions.Add("Aggregate", Aggregation.Aggregate);
            Actions.Add("Average", Aggregation.Average);
            Actions.Add("Count", Aggregation.Count);
            Actions.Add("LongCount", Aggregation.LongCount);
            Actions.Add("Max", Aggregation.Max);
            Actions.Add("Min", Aggregation.Min);
            Actions.Add("Sum", Aggregation.Sum);
        }
 public IQuery Save(Projection projection)
 {
     return(RawQuery.Create(_scriptProvider.Get("Projection.Save"))
            .AddParameterValue(Columns.Name, projection.Name)
            .AddParameterValue(Columns.SequenceNumber, projection.SequenceNumber));
 }
Пример #39
0
        /// <summary>
        /// Perform the underlying validation on the specified command
        /// </summary>
        /// <param name="commandId">
        /// The unique identifier of the command to validate
        /// </param>
        private static async Task <bool> ValidateCreateLeagueCommand(string commandId,
                                                                     ILogger log,
                                                                     IWriteContext writeContext = null)
        {
            const string COMMAND_NAME = @"create-league";

            Guid commandGuid;

            // use custom assembly resolve handler
            using (new AzureFunctionsResolveAssembly())
            {
                if (Guid.TryParse(commandId, out commandGuid))
                {
                    #region Logging
                    if (null != log)
                    {
                        log.LogDebug($"Validating command {commandId} in ValidateCreateLeagueCommand");
                    }
                    #endregion

                    // Get the current state of the command...
                    Projection getCommandState = new Projection(Constants.Domain_Command,
                                                                COMMAND_NAME,
                                                                commandGuid.ToString(),
                                                                nameof(Command_Summary_Projection));

                    if (null != getCommandState)
                    {
                        #region Logging
                        if (null != log)
                        {
                            log.LogDebug($"Projection processor created in ValidateCreateLeagueCommand");
                        }
                        #endregion

                        Command_Summary_Projection cmdProjection =
                            new Command_Summary_Projection(log);

                        await getCommandState.Process(cmdProjection);

                        if ((cmdProjection.CurrentSequenceNumber > 0) || (cmdProjection.ProjectionValuesChanged()))
                        {
                            #region Logging
                            if (null != log)
                            {
                                log.LogDebug($"Command { cmdProjection.CommandName} projection run for {commandGuid} in ValidateCreateLeagueCommand");
                            }
                            #endregion

                            if (cmdProjection.CurrentState ==
                                Command_Summary_Projection.CommandState.Completed)
                            {
                                // No need to validate a completed command
                                #region Logging
                                if (null != log)
                                {
                                    log.LogWarning($"Command {commandId} is complete so no need to validate in ValidateCreateLeagueCommand");
                                }
                                #endregion
                                return(true);
                            }

                            if (cmdProjection.CurrentState ==
                                Command_Summary_Projection.CommandState.Validated)
                            {
                                // No need to process a completed projection
                                #region Logging
                                if (null != log)
                                {
                                    log.LogWarning($"Command {commandId} is validated so no need to validate again in ValidateCreateLeagueCommand");
                                }
                                #endregion
                                return(true);
                            }

                            if ((cmdProjection.CurrentState ==
                                 Command_Summary_Projection.CommandState.Created) ||
                                (cmdProjection.CurrentState ==
                                 Command_Summary_Projection.CommandState.Invalid))
                            {
                                bool leagueNameValid      = false;
                                bool incoporatedDateValid = false;

                                // New or previously invalid command can be validated
                                if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.LeagueName)))
                                {
                                    // League name may not be blank
                                    string leagueName = cmdProjection.GetParameter <string>(nameof(Create_New_League_Definition.LeagueName));
                                    if (string.IsNullOrWhiteSpace(leagueName))
                                    {
                                        await CommandErrorLogRecord.LogCommandValidationError(commandGuid, COMMAND_NAME, true, "League name may not be blank");

                                        #region Logging
                                        if (null != log)
                                        {
                                            log.LogWarning($"Command {COMMAND_NAME } :: {commandId} has a blank league name in ValidateCreateLeagueCommand");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        leagueNameValid = true;

                                        // was the name already used?
                                        EventStream leagueEvents = new EventStream(@"Leagues",
                                                                                   "League",
                                                                                   leagueName);

                                        if (null != leagueEvents)
                                        {
                                            bool alreadyUsed = await leagueEvents.Exists();

                                            if (alreadyUsed)
                                            {
                                                await CommandErrorLogRecord.LogCommandValidationError(commandGuid,
                                                                                                      COMMAND_NAME, true,
                                                                                                      $"League name '{leagueName}' already created.");

                                                #region Logging
                                                if (null != log)
                                                {
                                                    log.LogWarning($"Command {COMMAND_NAME } :: {commandId} league name '{leagueName}' already created in ValidateCreateLeagueCommand");
                                                }
                                                #endregion

                                                leagueNameValid = false;
                                            }
                                        }
                                    }
                                }

                                // The incoporation date may not be in the future
                                if (cmdProjection.ParameterIsSet(nameof(ICreate_New_League_Definition.Date_Incorporated)))
                                {
                                    DateTime dateIncorporated = cmdProjection.GetParameter <DateTime>(nameof(ICreate_New_League_Definition.Date_Incorporated));
                                    if (dateIncorporated > DateTime.UtcNow)
                                    {
                                        await CommandErrorLogRecord.LogCommandValidationError(commandGuid, COMMAND_NAME, false, "Incorporation date is in the future");

                                        #region Logging
                                        if (null != log)
                                        {
                                            log.LogWarning($"Command {COMMAND_NAME } :: {commandId} has a future dated incorporation date in ValidateCreateLeagueCommand");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        incoporatedDateValid = true;
                                    }
                                }

                                if (incoporatedDateValid && leagueNameValid)
                                {
                                    await CommandErrorLogRecord.LogCommandValidationSuccess(commandGuid, COMMAND_NAME);
                                }

                                return(incoporatedDateValid && leagueNameValid);
                            }
                        }
                        else
                        {
                            // No events were read into the projection so do nothing
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"No command events read for {commandId} in ValidateCreateLeagueCommand");
                            }
                            #endregion
                        }
                    }
                }

                return(false);
            }
        }
Пример #40
0
		public Execution Get(Projection projection, Int64 executionId, FetchMode fetchMode = FetchMode.UseIdentityMap)
		{
			return ((IRepository<Execution>)this).Get(projection, executionId, fetchMode);
		}
Пример #41
0
		public Statement Get(Projection projection, Int64 statementId, params string[] fields)
		{
			return ((IRepository<Statement>)this).Get(projection, statementId, fields);
		}
Пример #42
0
		public Statement Get(Projection projection, Int64 statementId, FetchMode fetchMode = FetchMode.UseIdentityMap)
		{
			return ((IRepository<Statement>)this).Get(projection, statementId, fetchMode);
		}
        public IRequest Marshall(CreateTableRequest createTableRequest)
        {
            IRequest request = new DefaultRequest(createTableRequest, "AmazonDynamoDBv2");
            string   target  = "DynamoDB_20120810.CreateTable";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";



            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();


                if (createTableRequest != null && createTableRequest.AttributeDefinitions != null && createTableRequest.AttributeDefinitions.Count > 0)
                {
                    List <AttributeDefinition> attributeDefinitionsList = createTableRequest.AttributeDefinitions;
                    writer.WritePropertyName("AttributeDefinitions");
                    writer.WriteArrayStart();

                    foreach (AttributeDefinition attributeDefinitionsListValue in attributeDefinitionsList)
                    {
                        writer.WriteObjectStart();
                        if (attributeDefinitionsListValue != null && attributeDefinitionsListValue.IsSetAttributeName())
                        {
                            writer.WritePropertyName("AttributeName");
                            writer.Write(attributeDefinitionsListValue.AttributeName);
                        }
                        if (attributeDefinitionsListValue != null && attributeDefinitionsListValue.IsSetAttributeType())
                        {
                            writer.WritePropertyName("AttributeType");
                            writer.Write(attributeDefinitionsListValue.AttributeType);
                        }
                        writer.WriteObjectEnd();
                    }
                    writer.WriteArrayEnd();
                }
                if (createTableRequest != null && createTableRequest.IsSetTableName())
                {
                    writer.WritePropertyName("TableName");
                    writer.Write(createTableRequest.TableName);
                }

                if (createTableRequest != null && createTableRequest.KeySchema != null && createTableRequest.KeySchema.Count > 0)
                {
                    List <KeySchemaElement> keySchemaList = createTableRequest.KeySchema;
                    writer.WritePropertyName("KeySchema");
                    writer.WriteArrayStart();

                    foreach (KeySchemaElement keySchemaListValue in keySchemaList)
                    {
                        writer.WriteObjectStart();
                        if (keySchemaListValue != null && keySchemaListValue.IsSetAttributeName())
                        {
                            writer.WritePropertyName("AttributeName");
                            writer.Write(keySchemaListValue.AttributeName);
                        }
                        if (keySchemaListValue != null && keySchemaListValue.IsSetKeyType())
                        {
                            writer.WritePropertyName("KeyType");
                            writer.Write(keySchemaListValue.KeyType);
                        }
                        writer.WriteObjectEnd();
                    }
                    writer.WriteArrayEnd();
                }

                if (createTableRequest != null && createTableRequest.LocalSecondaryIndexes != null && createTableRequest.LocalSecondaryIndexes.Count > 0)
                {
                    List <LocalSecondaryIndex> localSecondaryIndexesList = createTableRequest.LocalSecondaryIndexes;
                    writer.WritePropertyName("LocalSecondaryIndexes");
                    writer.WriteArrayStart();

                    foreach (LocalSecondaryIndex localSecondaryIndexesListValue in localSecondaryIndexesList)
                    {
                        writer.WriteObjectStart();
                        if (localSecondaryIndexesListValue != null && localSecondaryIndexesListValue.IsSetIndexName())
                        {
                            writer.WritePropertyName("IndexName");
                            writer.Write(localSecondaryIndexesListValue.IndexName);
                        }

                        if (localSecondaryIndexesListValue != null && localSecondaryIndexesListValue.KeySchema != null && localSecondaryIndexesListValue.KeySchema.Count > 0)
                        {
                            List <KeySchemaElement> keySchemaList = localSecondaryIndexesListValue.KeySchema;
                            writer.WritePropertyName("KeySchema");
                            writer.WriteArrayStart();

                            foreach (KeySchemaElement keySchemaListValue in keySchemaList)
                            {
                                writer.WriteObjectStart();
                                if (keySchemaListValue != null && keySchemaListValue.IsSetAttributeName())
                                {
                                    writer.WritePropertyName("AttributeName");
                                    writer.Write(keySchemaListValue.AttributeName);
                                }
                                if (keySchemaListValue != null && keySchemaListValue.IsSetKeyType())
                                {
                                    writer.WritePropertyName("KeyType");
                                    writer.Write(keySchemaListValue.KeyType);
                                }
                                writer.WriteObjectEnd();
                            }
                            writer.WriteArrayEnd();
                        }

                        if (localSecondaryIndexesListValue != null)
                        {
                            Projection projection = localSecondaryIndexesListValue.Projection;
                            if (projection != null)
                            {
                                writer.WritePropertyName("Projection");
                                writer.WriteObjectStart();
                                if (projection != null && projection.IsSetProjectionType())
                                {
                                    writer.WritePropertyName("ProjectionType");
                                    writer.Write(projection.ProjectionType);
                                }

                                if (projection != null && projection.NonKeyAttributes != null && projection.NonKeyAttributes.Count > 0)
                                {
                                    List <string> nonKeyAttributesList = projection.NonKeyAttributes;
                                    writer.WritePropertyName("NonKeyAttributes");
                                    writer.WriteArrayStart();

                                    foreach (string nonKeyAttributesListValue in nonKeyAttributesList)
                                    {
                                        writer.Write(StringUtils.FromString(nonKeyAttributesListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }
                                writer.WriteObjectEnd();
                            }
                        }
                        writer.WriteObjectEnd();
                    }
                    writer.WriteArrayEnd();
                }

                if (createTableRequest != null)
                {
                    ProvisionedThroughput provisionedThroughput = createTableRequest.ProvisionedThroughput;
                    if (provisionedThroughput != null)
                    {
                        writer.WritePropertyName("ProvisionedThroughput");
                        writer.WriteObjectStart();
                        if (provisionedThroughput != null && provisionedThroughput.IsSetReadCapacityUnits())
                        {
                            writer.WritePropertyName("ReadCapacityUnits");
                            writer.Write(provisionedThroughput.ReadCapacityUnits);
                        }
                        if (provisionedThroughput != null && provisionedThroughput.IsSetWriteCapacityUnits())
                        {
                            writer.WritePropertyName("WriteCapacityUnits");
                            writer.Write(provisionedThroughput.WriteCapacityUnits);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Пример #44
0
 protected Proj4ProjectionInfo(Projection projection)
 {
     this.projection = projection;
 }
 private void ThenTheProjectionIsDeleted()
 {
     ProjectionStore.Received().Delete(Projection.StoreKey(ProjectId, ToggleKey));
 }
Пример #46
0
 public User Get(Projection projection, System.Int32 userId)
 {
     return(((IRepository <User>) this).Get(projection, userId, FetchMode.UseIdentityMap));
 }
        public static async Task <Tuple <string, bool> > SetOverdraftForInterestForSpecificAccount
            ([ActivityTrigger] IDurableActivityContext interestOverdraftContext)
        {
            string accountNumber = interestOverdraftContext.GetInput <string>();

            #region Tracing telemetry
            Activity.Current.AddTag("Account Number", accountNumber);
            #endregion

            bool success = true;

            Command cmdPayInterest = new Command(
                new CommandAttribute("Bank",
                                     "Pay Interest",
                                     interestOverdraftContext.InstanceId)
                );

            if (!string.IsNullOrWhiteSpace(accountNumber))
            {
                string result = "No overdraft required";

                await cmdPayInterest.InitiateStep(AccountCommands.COMMAND_STEP_OVERDRAFT,
                                                  "Bank",
                                                  "Account",
                                                  accountNumber);

                // run the "set overdraft limit for interest" function
                // 1- Get interest due...
                Projection prjInterestDue = new Projection(
                    new ProjectionAttribute(
                        "Bank",
                        "Account",
                        accountNumber,
                        nameof(InterestDue)
                        )
                    );

                // get the interest owed / due as now
                InterestDue interestDue = await prjInterestDue.Process <InterestDue>();

                if (null != interestDue)
                {
                    // if the interest due is negative we need to make sure the account has sufficient balance
                    if (interestDue.Due < 0.00M)
                    {
                        Projection prjBankAccountBalance = new Projection(
                            new ProjectionAttribute(
                                "Bank",
                                "Account",
                                accountNumber,
                                nameof(InterestDue)
                                )
                            );

                        Balance balance = await prjBankAccountBalance.Process <Balance>();

                        if (null != balance)
                        {
                            decimal availableBalance = balance.CurrentBalance;

                            // is there an overdraft?
                            Projection prjBankAccountOverdraft = new Projection(
                                new ProjectionAttribute(
                                    "Bank",
                                    "Account",
                                    accountNumber,
                                    nameof(OverdraftLimit)
                                    )
                                );

                            OverdraftLimit overdraft = await prjBankAccountOverdraft.Process <OverdraftLimit>();

                            if (null != overdraft)
                            {
                                availableBalance += overdraft.CurrentOverdraftLimit;
                            }

                            if (availableBalance < interestDue.Due)
                            {
                                // Force an overdraft extension
                                EventStream bankAccountEvents = new EventStream(
                                    new EventStreamAttribute(
                                        "Bank",
                                        "Account",
                                        accountNumber
                                        )
                                    );

                                decimal           newOverdraft = overdraft.CurrentOverdraftLimit;
                                decimal           extension    = 10.00M + Math.Abs(interestDue.Due % 10.00M);
                                OverdraftLimitSet evNewLimit   = new OverdraftLimitSet()
                                {
                                    OverdraftLimit = newOverdraft + extension,
                                    Commentary     = $"Overdraft extended to pay interest of {interestDue.Due} ",
                                    Unauthorised   = true
                                };

                                result = $"Overdraft set to {evNewLimit.OverdraftLimit } ({evNewLimit.Commentary})";

                                try
                                {
                                    await bankAccountEvents.AppendEvent(evNewLimit, balance.CurrentSequenceNumber);
                                }
                                catch (EventSourcingOnAzureFunctions.Common.EventSourcing.Exceptions.EventStreamWriteException)
                                {
                                    success = false;
                                }
                            }
                        }
                    }
                }

                // Log the step completion if it was successful
                if (success)
                {
                    await cmdPayInterest.StepCompleted(AccountCommands.COMMAND_STEP_OVERDRAFT,
                                                       result,
                                                       "Bank",
                                                       "Account",
                                                       accountNumber);
                }
            }

            return(new Tuple <string, bool>(accountNumber, success));
        }
Пример #48
0
 public Task <User> GetAsync(Projection projection, System.Int32 userId, FetchMode fetchMode = FetchMode.UseIdentityMap)
 {
     return(((IRepository <User>) this).GetAsync(projection, userId, fetchMode));
 }
        public static async Task <Tuple <string, bool> > AccrueInterestForSpecificAccount
            ([ActivityTrigger] IDurableActivityContext accrueInterestContext)
        {
            const decimal DEBIT_INTEREST_RATE  = 0.001M;
            const decimal CREDIT_INTEREST_RATE = 0.0005M;

            string accountNumber = accrueInterestContext.GetInput <string>();

            #region Tracing telemetry
            Activity.Current.AddTag("Account Number", accountNumber);
            #endregion

            if (!string.IsNullOrEmpty(accountNumber))
            {
                EventStream bankAccountEvents = new EventStream(new EventStreamAttribute("Bank", "Account", accountNumber));
                if (await bankAccountEvents.Exists())
                {
                    // Has the accrual been done today for this account?
                    Classification         clsAccruedToday = new Classification(new ClassificationAttribute("Bank", "Account", accountNumber, nameof(InterestAccruedToday)));
                    ClassificationResponse isAccrued       = await clsAccruedToday.Classify <InterestAccruedToday>();

                    if (isAccrued.Result != ClassificationResponse.ClassificationResults.Include)
                    {
                        // Get the account balance
                        Projection prjBankAccountBalance = new Projection(new ProjectionAttribute("Bank", "Account", accountNumber, nameof(Balance)));

                        // Get the current account balance, as at midnight
                        Balance projectedBalance = await prjBankAccountBalance.Process <Balance>(DateTime.Today);

                        if (null != projectedBalance)
                        {
                            Account.Events.InterestAccrued evAccrued = new Account.Events.InterestAccrued()
                            {
                                Commentary           = $"Daily scheduled interest accrual",
                                AccrualEffectiveDate = DateTime.Today  // set the accrual to midnight today
                            };
                            // calculate the accrual amount
                            if (projectedBalance.CurrentBalance >= 0)
                            {
                                // Using the credit rate
                                evAccrued.AmountAccrued        = CREDIT_INTEREST_RATE * projectedBalance.CurrentBalance;
                                evAccrued.InterestRateInEffect = CREDIT_INTEREST_RATE;
                            }
                            else
                            {
                                // Use the debit rate
                                evAccrued.AmountAccrued        = DEBIT_INTEREST_RATE * projectedBalance.CurrentBalance;
                                evAccrued.InterestRateInEffect = DEBIT_INTEREST_RATE;
                            }

                            try
                            {
                                await bankAccountEvents.AppendEvent(evAccrued, isAccrued.AsOfSequence);
                            }
                            catch (EventSourcingOnAzureFunctions.Common.EventSourcing.Exceptions.EventStreamWriteException)
                            {
                                // We can't be sure this hasn't already run...
                                return(new Tuple <string, bool>(accountNumber, false));
                            }
                        }
                    }
                }
            }
            return(new Tuple <string, bool>(accountNumber, true));
        }
Пример #50
0
 public Task <User> GetAsync(Projection projection, System.Int32 userId, params string[] fields)
 {
     return(((IRepository <User>) this).GetAsync(projection, userId, fields));
 }
Пример #51
0
        /// <summary>
        /// 預設指令碼
        /// </summary>
        /// <returns></returns>
        protected override string DefaultCommand()
        {
            if (YVariables == null)
            {
                throw new Exception("建立 Plot 指令時,未給定 YVariables");
            }
            if (XVariables == null)
            {
                throw new Exception("建立 Plot 指令時,未給定 XVariables");
            }


            Mtb.Column[] yvars = (Mtb.Column[])YVariables;
            Mtb.Column[] xvars = (Mtb.Column[])XVariables;

            Mtb.Column[] gps = null;
            if (GroupingVariables != null)
            {
                gps = (Mtb.Column[])GroupingVariables;
            }


            StringBuilder cmnd = new StringBuilder();

            if (GraphType == MultipleGraphType.Regular)
            {
                if (yvars.Length != xvars.Length)
                {
                    throw new ArgumentException("GraphType=Regular 時,X 變數和 Y 變數的數量不同");
                }
                cmnd.AppendLine("Plot &");
                for (int i = 0; i < yvars.Length; i++)
                {
                    cmnd.AppendFormat("{0}*{1} &\r\n", yvars[i].SynthesizedName, xvars[i].SynthesizedName);
                }
                cmnd.AppendLine(";");
            }
            else
            {
                cmnd.AppendFormat("Plot ({0})*({1});\r\n",
                                  string.Join(" &\r\n", yvars.Select(x => x.SynthesizedName).ToArray()),
                                  string.Join(" &\r\n", xvars.Select(x => x.SynthesizedName).ToArray()));
                if (GraphType == MultipleGraphType.Overlay)
                {
                    cmnd.AppendLine(" Over;");
                }
            }

            if (gps != null)
            {
                string[] gp = gps.Select(x => x.SynthesizedName).ToArray();
                Symbol.GroupingBy      = gp.Clone();
                Connectline.GroupingBy = gp.Clone();
                Projection.GroupingBy  = gp.Clone();
            }

            cmnd.AppendFormat("");

            cmnd.Append(GetOptionCommand());
            cmnd.Append(YScale.GetCommand());
            cmnd.Append(XScale.GetCommand());
            cmnd.Append(Symbol.GetCommand());
            cmnd.Append(Connectline.GetCommand());
            cmnd.Append(Projection.GetCommand());
            cmnd.Append(Panel.GetCommand());

            cmnd.Append(GetAnnotationCommand());
            cmnd.Append(GetRegionCommand());


            return(cmnd.ToString() + ".");
        }
        /// <summary>
        /// Perform the validation on the parameters of this "Get League Summary" query and, if all OK, mark it
        /// as allowed to continue
        /// </summary>
        /// <param name="queryId">
        /// Unique identifier of the query event stream for this "Get League Summary" query
        /// </param>
        /// <param name="log">
        /// If set, output progress to this trace writer
        /// </param>
        private static async Task <bool> ValidateGetLeagueSummaryQuery(string queryId,
                                                                       ILogger log)
        {
            const string QUERY_NAME = @"get-league-summary";
            Guid         queryGuid;

            if (Guid.TryParse(queryId, out queryGuid))
            {
                // Get the current state of the query...
                Projection getQueryState = new Projection(@"Query",
                                                          QUERY_NAME,
                                                          queryGuid.ToString(),
                                                          nameof(Query_Summary_Projection));

                if (null != getQueryState)
                {
                    #region Logging
                    if (null != log)
                    {
                        log.LogDebug($"Projection processor created in ValidateGetLeagueSummaryQuery");
                    }
                    #endregion

                    // Run the query summary projection
                    Query_Summary_Projection qryProjection =
                        new Query_Summary_Projection(log);

                    await getQueryState.Process(qryProjection);


                    if ((qryProjection.CurrentSequenceNumber > 0) || (qryProjection.ProjectionValuesChanged()))
                    {
                        // Process the query state as is now...
                        #region Logging
                        if (null != log)
                        {
                            log.LogDebug($"Query { qryProjection.QueryName } projection run for {queryGuid} in ValidateGetLeagueSummaryQuery");
                        }
                        #endregion

                        if (qryProjection.CurrentState == Query_Summary_Projection.QueryState.Completed)
                        {
                            // No need to validate a completed query
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Query {queryGuid} is complete so no need to validate in ValidateGetLeagueSummaryQuery");
                            }
                            #endregion
                            return(true);
                        }

                        if (qryProjection.CurrentState == Query_Summary_Projection.QueryState.Invalid)
                        {
                            // No need to validate an already invalid query
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Query {queryGuid} is already marked as invalid so no need to validate in ValidateGetLeagueSummaryQuery");
                            }
                            #endregion
                            return(false);
                        }

                        if (qryProjection.CurrentState == Query_Summary_Projection.QueryState.Validated)
                        {
                            // No need to validate an already validated query
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Query {queryGuid} is already validated so no need to validate in ValidateGetLeagueSummaryQuery");
                            }
                            #endregion
                            return(true);
                        }

                        // Validations - 1: Check league name is not empty
                        if (qryProjection.ParameterIsSet(nameof(Get_League_Summary_Definition.League_Name)))
                        {
                            string leagueNameParam = qryProjection.GetParameter <string>(nameof(Get_League_Summary_Definition.League_Name));
                            if (string.IsNullOrWhiteSpace(leagueNameParam))
                            {
                                await QueryLogRecord.LogQueryValidationError(queryGuid, QUERY_NAME, true, "League name may not be blank");

                                #region Logging
                                if (null != log)
                                {
                                    log.LogWarning($"Query {QUERY_NAME} :: {queryGuid} has a blank league name in ValidateGetLeagueSummaryQuery");
                                }
                                #endregion
                                return(false);
                            }
                            else
                            {
                                // any additional validation could go here (?)..
                                return(true);
                            }
                        }
                        else
                        {
                            // Parameter is mandatory but may not be set yet so leave the query as is
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Query { qryProjection.QueryName } has no value specified for the parameter {nameof(Get_League_Summary_Definition.League_Name)} in ValidateGetLeagueSummaryQuery");
                            }
                            #endregion
                            return(false);
                        }
                    }
                }
            }

            return(false);
        }
        /// <summary>
        /// Perform the underlying processing on the specified command
        /// </summary>
        /// <param name="commandId">
        /// The unique identifier of the command to process
        /// </param>
        private static async Task  HandleSetLeagueEmailAddressCommand(string commandId,
                                                                      ILogger log = null)
        {
            const string COMMAND_NAME = @"set-league-email-address";

            Guid commandGuid;

            if (Guid.TryParse(commandId, out commandGuid))
            {
                #region Logging
                if (null != log)
                {
                    log.LogDebug($"Validating command {commandId}  in HandleSetLeagueEmailAddressCommand");
                }
                #endregion

                // Get the current state of the command...
                Projection getCommandState = new Projection(@"Command",
                                                            COMMAND_NAME,
                                                            commandGuid.ToString(),
                                                            nameof(Command_Summary_Projection));

                if (null != getCommandState)
                {
                    #region Logging
                    if (null != log)
                    {
                        log.LogDebug($"Projection processor created in HandleSetLeagueEmailAddressCommand");
                    }
                    #endregion

                    Command_Summary_Projection cmdProjection =
                        new Command_Summary_Projection(log);

                    await getCommandState.Process(cmdProjection);

                    if ((cmdProjection.CurrentSequenceNumber > 0) || (cmdProjection.ProjectionValuesChanged()))
                    {
                        if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Completed)
                        {
                            // No need to process a completed projection
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Command {commandId} is complete so no need to process in HandleSetLeagueEmailAddressCommand");
                            }
                            #endregion
                            return;
                        }

                        if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Created)
                        {
                            // No need to process a completed projection
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Command {commandId} is not yet validated so cannot process in HandleSetLeagueEmailAddressCommand");
                            }
                            #endregion
                            return;
                        }

                        if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Invalid)
                        {
                            // No need to process a completed projection
                            #region Logging
                            if (null != log)
                            {
                                log.LogWarning($"Command {commandId} is not yet marked as invalid so cannot process in HandleSetLeagueEmailAddressCommand");
                            }
                            #endregion
                            return;
                        }

                        if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Validated)
                        {
                            string leagueName = string.Empty;

                            // New or previously invalid command can be validated
                            if (cmdProjection.ParameterIsSet(nameof(Set_Email_Address_Definition.LeagueName)))
                            {
                                // Get the league name we want to set the email address
                                leagueName = cmdProjection.GetParameter <string>(nameof(Set_Email_Address_Definition.LeagueName));
                            }

                            string twitterHandle = string.Empty;
                            if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.Twitter_Handle)))
                            {
                                twitterHandle = cmdProjection.GetParameter <string>(nameof(Create_New_League_Definition.Twitter_Handle));
                            }

                            string emailAddress = string.Empty;
                            if (cmdProjection.ParameterIsSet(nameof(Set_Email_Address_Definition.New_Email_Address)))
                            {
                                emailAddress = cmdProjection.GetParameter <string>(nameof(Set_Email_Address_Definition.New_Email_Address));
                            }

                            string notes = string.Empty;
                            if (cmdProjection.ParameterIsSet(nameof(Set_Email_Address_Definition.Notes)))
                            {
                                notes = cmdProjection.GetParameter <string>(nameof(Set_Email_Address_Definition.Notes));
                            }

                            // Create a new "Contact Details Changed" event
                            Leagues.League.eventDefinition.Contact_Details_Changed changedEvent = new Leagues.League.eventDefinition.Contact_Details_Changed(DateTime.UtcNow,
                                                                                                                                                             twitterHandle,
                                                                                                                                                             emailAddress);

                            EventStream leagueEvents = new EventStream(@"Leagues",
                                                                       "League",
                                                                       leagueName);

                            if ((null != leagueEvents) && (null != changedEvent))
                            {
                                await leagueEvents.AppendEvent(changedEvent);
                            }
                        }
                    }
                }
                else
                {
                    // No events were read into the projection so do nothing
                    #region Logging
                    if (null != log)
                    {
                        log.LogWarning($"No command events read for {commandId} in HandleSetLeagueEmailAddressCommand");
                    }
                    #endregion
                }
            }
        }
Пример #54
0
 bool IOctTreeInsertable.HitTest(Projection projection, BoundingRect rect, bool onlyInside)
 {   // kommt nicht dran
     throw new NotImplementedException();
 }
Пример #55
0
		public Execution Get(Projection projection, Int64 executionId, params string[] fields)
		{
			return ((IRepository<Execution>)this).Get(projection, executionId, fields);
		}
Пример #56
0
 internal bool GetOverlap(Projection projection, out float overlap)
 {
     overlap = Math.Min(this.Max, projection.Max) - Math.Max(this.Min, projection.Min);
     return(overlap > 0);
 }
Пример #57
0
        public static async Task <HttpResponseMessage> AboutQueryRun(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestMessage req,
            ILogger log,
            [EventStream(Constants.Domain_Query, "Test Case", "123")] EventStream esTest,
            [Projection(Constants.Domain_Query, "Test Case", "123", nameof(Query_Summary_Projection))] Projection prjTest,
            [Classifier(Constants.Domain_Query, "Test Case", "123", nameof(Query_InError_Classifier))] Classifier clsTest)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            if (null != esTest)
            {
                log.LogInformation($"Event stream created {esTest}");
                // add a test event
                await esTest.AppendEvent(new QueryCreated("Test Query",
                                                          Guid.NewGuid(),
                                                          aurhorisationTokenIn : "Duncan test 123"
                                                          ));
            }
            else
            {
                log.LogWarning($"Unable to create event stream parameter");
            }

            if (null != prjTest)
            {
                log.LogInformation($"Projection created {prjTest}");
                //
                Query_Summary_Projection projection = await prjTest.Process <Query_Summary_Projection>();

                if (null != projection)
                {
                    log.LogInformation($"Projection created {projection.CurrentSequenceNumber} status {projection.CurrentState } ");
                }
            }
            else
            {
                log.LogWarning($"Unable to create projection parameter");
            }

            if (null != clsTest)
            {
                log.LogInformation($"Classifier created {clsTest}");
                var result = await clsTest.Classify <Query_InError_Classifier>(forceExclude : true);

                log.LogInformation($"Classifier created {clsTest.ClassifierTypeName} result {result  } ");
            }
            else
            {
                log.LogWarning($"Unable to create classifier parameter");
            }

            // parse query parameter
            string name = req.GetQueryNameValuePairsExt()[@"name"];

            // Get request body
            dynamic data = await req.Content.ReadAsAsync <object>();

            // Set name to query string or body data
            name = name ?? data?.name;

            return(name == null
                ? req.CreateResponse(HttpStatusCode.OK, "The Long Run - Leagues Domain - Function App")
                : req.CreateResponse(HttpStatusCode.OK, GetFunctionAbout(name)));
        }
Пример #58
0
        public Raster ProcessRaster()
        {
            Cursor = Cursors.WaitCursor;

            Raster gResult = null;

            System.IO.FileInfo fiOutput = ProjectManager.Project.GetAbsolutePath(txtRasterPath.Text);

            if (fiOutput.Exists)
            {
                Exception ex = new Exception("The raster path already exists.");
                ex.Data.Add("Raster path", txtRasterPath.Text);
                throw ex;
            }

            fiOutput.Directory.Create();

            if (ExtImporter.RequiresResampling)
            {
                gResult = RasterOperators.BilinearResample(SourceRaster, fiOutput, ExtImporter.OutExtent, ProjectManager.OnProgressChange);
            }
            else
            {
                if (SourceRaster.Extent.Equals(ExtImporter.OutExtent))
                {
                    // Output extent is same as original raster. Simple dataset copy
                    if (SourceRaster.driver == Raster.RasterDriver.GTiff)
                    {
                        SourceRaster.Copy(fiOutput);
                        gResult = new Raster(fiOutput);
                    }
                    else
                    {
                        gResult = RasterOperators.ExtendedCopy(SourceRaster, fiOutput, ProjectManager.OnProgressChange);
                    }
                }
                else
                {
                    // Output extent differs from original raster. Use extended copy
                    gResult = RasterOperators.ExtendedCopy(SourceRaster, fiOutput, ExtImporter.OutExtent, ProjectManager.OnProgressChange);
                }
            }

            // This method will check to see if pyrmaids are need and then build if necessary.
            PerformRasterPyramids(new System.IO.FileInfo(txtRasterPath.Text));

            if (Purpose == Purposes.FirstDEM || Purpose == Purposes.SubsequentDEM || Purpose == Purposes.ReferenceSurface)
            {
                // Now try the hillshade for DEM Surveys and reference surfaces
                System.IO.FileInfo sHillshadePath = Surface.HillShadeRasterPath(fiOutput);
                RasterOperators.Hillshade(gResult, sHillshadePath, ProjectManager.OnProgressChange);
                ProjectManager.PyramidManager.PerformRasterPyramids(RasterPyramidManager.PyramidRasterTypes.Hillshade, sHillshadePath);
            }


            Cursor = Cursors.Default;

            Projection projRef = GISDatasetValidation.GetProjectProjection();

            if (projRef != null && NeedsForcedProjection)
            {
                gResult.SetProjection(projRef);
            }

            return(gResult);
        }
Пример #59
0
        public void ShowG(Graphics g, Projection pr = 0, Pen pen = null)
        {
            const double h  = 0.1;
            const double h0 = 0;

            System.Drawing.Rectangle r1 = new Rectangle(left, top, left + width, top + height);
            Pen p = new Pen(Color.Black);

            g.DrawRectangle(p, r1);

            // Создать шрифт
            Font       font = new Font("Courier New", 12, FontStyle.Bold);
            SolidBrush b    = new SolidBrush(Color.Blue);

            // рисование осей
            // ось X
            Zoom_XY(0, 0, 0, out xx1, out yy1);
            Zoom_XY(1.2, 0, 0, out xx2, out yy2);
            g.DrawLine(p, xx1, yy1, xx2, yy2);
            g.DrawString("X", font, b, xx2 + 3, yy2);

            // ось Y
            Zoom_XY(0, 0, 0, out xx1, out yy1);
            Zoom_XY(0, 1.2, 0, out xx2, out yy2);
            g.DrawLine(p, xx1, yy1, xx2, yy2);
            g.DrawString("Y", font, b, xx2 + 3, yy2);

            // ось Z
            Zoom_XY(0, 0, 0, out xx1, out yy1);
            Zoom_XY(0, 0, 1.2, out xx2, out yy2);
            g.DrawLine(p, xx1, yy1, xx2, yy2);
            g.DrawString("Z", font, b, xx2 + 3, yy2 - 3);

            // рисование поверхности
            p.Color = Color.Red;
            p.Width = 1;

            float dx = (Math.Abs(X0) + Math.Abs(X1)) / CountOfSplits;
            float dy = (Math.Abs(Y0) + Math.Abs(Y1)) / CountOfSplits;

            for (float j = X0; j <= X1; j += dx)
            {
                for (float i = Y0; i <= Y1; i += dy)
                {
                    Zoom_XY(h0 + h * i, h0 + h * j, F(h0 + h * i, h0 + h * j),
                            out xx[0], out yy[0]);
                    Zoom_XY(h0 + h * i, h + h * j, F(h0 + h * i, h + h * j),
                            out xx[1], out yy[1]);
                    Zoom_XY(h + h * i, h + h * j, F(h + h * i, h + h * j),
                            out xx[2], out yy[2]);

                    Zoom_XY(h + h * i, h0 + h * j, F(h + h * i, h0 + h * j),
                            out xx[3], out yy[3]);

                    g.DrawLine(p, xx[0], yy[0], xx[1], yy[1]);
                    g.DrawLine(p, xx[1], yy[1], xx[2], yy[2]);
                    g.DrawLine(p, xx[2], yy[2], xx[3], yy[3]);
                    g.DrawLine(p, xx[3], yy[3], xx[0], yy[0]);
                }
            }
        }
Пример #60
0
    /// <inheritdoc/>
    public override async Task Connect(
        IAsyncStreamReader <ProjectionClientToRuntimeMessage> runtimeStream,
        IServerStreamWriter <ProjectionRuntimeToClientMessage> clientStream,
        ServerCallContext context)
    {
        // TODO: It seems like things are not properly unregistered on exceptions?
        // TODO: I tested this out and while making the DI container work, it kept failing and telling me that the projection was already registered on the second attempt.

        Log.ConnectingProjections(_logger);
        using var cts = CancellationTokenSource.CreateLinkedTokenSource(_hostApplicationLifetime.ApplicationStopping, context.CancellationToken);
        var tryConnect = await _reverseCallServices.Connect(runtimeStream, clientStream, context, _protocol, cts.Token).ConfigureAwait(false);

        if (!tryConnect.Success)
        {
            return;
        }
        using var dispatcher = tryConnect.Result.dispatcher;
        var arguments        = tryConnect.Result.arguments;
        var executionContext = arguments.ExecutionContext;
        var definition       = arguments.ProjectionDefinition;

        var tryCreateExecutionContext = _executionContextCreator.TryCreateUsing(arguments.ExecutionContext);

        if (!tryCreateExecutionContext.Success)
        {
            await dispatcher.Reject(
                _protocol.CreateFailedConnectResponse($"Failed to register Projection because the execution context is invalid: ${tryCreateExecutionContext.Exception.Message}"),
                cts.Token).ConfigureAwait(false);

            return;
        }

        Log.ReceivedProjectionArguments(_logger, definition.Scope, definition.Projection);

        var projection   = new Projection(dispatcher, definition, arguments.Alias, arguments.HasAlias);
        var registration = await _projections.Register(projection, executionContext, cts.Token);

        if (!registration.Success)
        {
            Log.ErrorWhileRegisteringProjection(_logger, definition.Scope, definition.Projection, registration.Exception);
            await dispatcher.Reject(new ProjectionRegistrationResponse
            {
                Failure = new Failure(
                    ProjectionFailures.FailedToRegisterProjection,
                    $"Failed to register Projection {projection.Definition.Projection}. {registration.Exception.Message}")
            }, cts.Token).ConfigureAwait(false);

            return;
        }

        using var processor = registration.Result;
        var reverseCall = dispatcher.Accept(new ProjectionRegistrationResponse(), cts.Token);
        var processing  = processor.Start();

        var tasks = new TaskGroup(reverseCall, processing);

        tasks.OnFirstTaskFailure  += (_, ex) => Log.ErrorWhileRunningProjection(_logger, projection.Definition.Scope, projection.Definition.Projection, ex);
        tasks.OnAllTasksCompleted += () => Log.ProjectionDisconnected(_logger, projection.Definition.Scope, projection.Definition.Projection);

        await tasks.WaitForAllCancellingOnFirst(cts).ConfigureAwait(false);
    }