Example #1
0
 public virtual void Display(IViewData data)
 {
     foreach (IModel model in data.ModelList)
     {
         Console.WriteLine(model.GetStringData());
     }
 }
Example #2
0
        public void ChangeClientInfo(IViewData view)
        {
            ChangeClient cc = new ChangeClient(my.GetClientFromDB(view.NumPassOrInn));

            cc.ShowDialog();
            view.dataTable = LoaderData();
        }
Example #3
0
    public static IEnumerable <IViewData> AllDetailViewDataTypes()
    {
        IViewData[]    result        = new IViewData[3];
        IAttributeData subAttribData = Substitute.For <IAttributeData>();

        subAttribData.AttributeDictionary.Returns(
            delegate {
            return(GetStubAttributeDict());
        });

        result[0] = subAttribData;

        IPortraitData subPortraitData = Substitute.For <IPortraitData>();

        subPortraitData.Portrait.Returns(
            delegate {
            return(GetStubPortraitData());
        }
            );

        result[1] = subPortraitData;

        IDescriptionData subDescriptionData = Substitute.For <IDescriptionData>();

        subDescriptionData.Description.Returns(
            delegate {
            return(StringPlaceholders.GetLoremIpsumAsParagraphs(1));
        }
            );

        result[2] = subDescriptionData;

        return(result);
    }
        public void Record_CurrentContextNotSet()
        {
            IView view =
                View.Create(
                    VIEW_NAME,
                    "description",
                    MEASURE_DOUBLE,
                    Sum.Create(),
                    new List <ITagKey>()
            {
                KEY
            });

            viewManager.RegisterView(view);
            statsRecorder.NewMeasureMap().Put(MEASURE_DOUBLE, 1.0).Record();
            IViewData viewData = viewManager.GetView(VIEW_NAME);

            // record() should have used the default TagContext, so the tag value should be null.
            ICollection <TagValues> expected = new List <TagValues>()
            {
                TagValues.Create(new List <ITagValue>()
                {
                    null
                })
            };

            Assert.Equal(expected, viewData.AggregationMap.Keys);
        }
Example #5
0
        public void TestRecordWithEmptyStatsContext()
        {
            Stats.State = StatsCollectionState.ENABLED;

            IView view = CreateCumulativeView(CreateRandomViewName(), MeasureDouble, Distribution, new List <string>()
            {
                Key
            });

            viewManager.RegisterView(view);
            // DEFAULT doesn't have tags, but the view has tag key "Key".
            statsRecorder.NewMeasureMap().Put(MeasureDouble, 10.0).Record(tagger.Empty);
            IViewData viewData = viewManager.GetView(view.Name);
            var       tv       = TagValues.Create(new List <string>()
            {
                MutableViewData.UnknownTagValue
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                // Tag is missing for associated measureValues, should use default tag value
                // "unknown/not set".
                { tv,
                  // Should Record stats with default tag value: "Key" : "unknown/not set".
                  StatsTestUtil.CreateAggregationData(Distribution, MeasureDouble, 10.0) },
            },
                Epsilon);
        }
Example #6
0
        public void TestGetCumulativeViewDataWithoutBucketBoundaries()
        {
            IView view = CreateCumulativeView(CreateRandomViewName(), MeasureDouble, Mean, new List <string>()
            {
                Key
            });

            viewManager.RegisterView(view);
            statsRecorder
            .NewMeasureMap()
            .Put(MeasureDouble, 1.1)
            .Record(tagger.EmptyBuilder.Put(Key, Value).Build());
            IViewData viewData = viewManager.GetView(view.Name);
            var       tv       = TagValues.Create(new List <string>()
            {
                Value
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(Mean, MeasureDouble, 1.1) },
            },
                Epsilon);
        }
Example #7
0
        public void TestGetCumulativeViewDataWithoutBucketBoundaries()
        {
            IView view = CreateCumulativeView(VIEW_NAME, MEASURE_DOUBLE, MEAN, new List <ITagKey>()
            {
                KEY
            });

            clock.Time = (Timestamp.Create(1, 0));
            viewManager.RegisterView(view);
            statsRecorder
            .NewMeasureMap()
            .Put(MEASURE_DOUBLE, 1.1)
            .Record(tagger.EmptyBuilder.Put(KEY, VALUE).Build());
            clock.Time = Timestamp.Create(3, 0);
            IViewData viewData = viewManager.GetView(VIEW_NAME);
            var       tv       = TagValues.Create(new List <ITagValue>()
            {
                VALUE
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(MEAN, MEASURE_DOUBLE, 1.1) },
            },
                EPSILON);
        }
Example #8
0
        /// <summary>
        /// Create a view.
        /// </summary>
        /// <param name="context">Context to render</param>
        public void Render(IControllerContext context, IViewData viewData, TextWriter writer)
        {
            string layoutName;
            if (context.LayoutName != null)
                layoutName = context.LayoutName;
            else
            {
                var controllerName = context.ControllerUri.TrimEnd('/');
                int pos = controllerName.LastIndexOf('/');
                layoutName = context.ControllerUri;
                layoutName += pos == -1
                                  ? controllerName + ".haml"
                                  : controllerName.Substring(pos + 1) + ".haml";

                if (!MvcServer.CurrentMvc.ViewProvider.Exists(layoutName))
                    layoutName = "Shared/Application.haml";
            }

            string viewPath = context.ViewPath + ".haml";


            CompiledTemplate template = _templateEngine.Compile(new List<string> {layoutName, viewPath},
                                                                typeof (NHamlView));

            var instance = (NHamlView)template.CreateInstance();
            instance.ViewData = viewData;
            instance.Render(writer);
        }
Example #9
0
        public void TestRecordWithTagsThatDoNotMatchViewData()
        {
            viewManager.RegisterView(
                CreateCumulativeView(VIEW_NAME, MEASURE_DOUBLE, DISTRIBUTION, new List <ITagKey>()
            {
                KEY
            }));
            statsRecorder
            .NewMeasureMap()
            .Put(MEASURE_DOUBLE, 10.0)
            .Record(tagger.EmptyBuilder.Put(TagKey.Create("wrong key"), VALUE).Build());
            statsRecorder
            .NewMeasureMap()
            .Put(MEASURE_DOUBLE, 50.0)
            .Record(tagger.EmptyBuilder.Put(TagKey.Create("another wrong key"), VALUE).Build());
            IViewData viewData = viewManager.GetView(VIEW_NAME);
            var       tv       = TagValues.Create(new List <ITagValue>()
            {
                MutableViewData.UnknownTagValue
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                // Won't Record the unregistered tag key, for missing registered keys will use default
                // tag value : "unknown/not set".
                { tv,
                  // Should Record stats with default tag value: "KEY" : "unknown/not set".
                  StatsTestUtil.CreateAggregationData(DISTRIBUTION, MEASURE_DOUBLE, 10.0, 50.0) },
            },
                EPSILON);
        }
        public void TestGetCumulativeViewDataWithEmptyBucketBoundaries()
        {
            IAggregation noHistogram =
                Aggregations.Distribution.Create(OpenTelemetry.Stats.BucketBoundaries.Create(Enumerable.Empty <double>()));
            IView view = CreateCumulativeView(CreateRandomViewName(), MeasureDouble, noHistogram, new List <TagKey>()
            {
                Key
            });

            viewManager.RegisterView(view);
            statsRecorder
            .NewMeasureMap()
            .Put(MeasureDouble, 1.1)
            .Record(tagger.EmptyBuilder.Put(Key, Value).Build());
            IViewData viewData = viewManager.GetView(view.Name);
            var       tv       = TagValues.Create(new List <TagValue>()
            {
                Value
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(noHistogram, MeasureDouble, 1.1) },
            },
                Epsilon);
        }
        /// <summary>
        /// 交换两个子项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="index1"></param>
        /// <param name="index2"></param>
        /// <param name="dataList">不为空则交换前端数据</param>
        public void ExchangeItem <T>(int index1, int index2, List <T> dataList = null) where T : IViewData
        {
            int tempIndex = itemList[index1].transform.GetSiblingIndex();

            itemList[index1].transform.SetSiblingIndex(itemList[index2].transform.GetSiblingIndex());
            itemList[index1].Index = index2;
            itemList[index2].transform.SetSiblingIndex(tempIndex);
            itemList[index2].Index = index1;

            ScrollViewListItem tempScrollItem = itemList[index1];

            itemList[index1] = itemList[index2];
            itemList[index2] = tempScrollItem;

            IViewData tempData = itemData[index1];

            itemData[index1] = itemData[index2];
            itemData[index2] = tempData;

            if (dataList != null && dataList.Count > 0)
            {
                T temp = dataList[index1];
                dataList[index1] = dataList[index2];
                dataList[index2] = temp;
            }
        }
Example #12
0
        public void TestGetCumulativeViewDataWithEmptyBucketBoundaries()
        {
            IAggregation noHistogram =
                Distribution.Create(BucketBoundaries.Create(Enumerable.Empty <double>()));
            IView view = CreateCumulativeView(VIEW_NAME, MEASURE_DOUBLE, noHistogram, new List <TagKey>()
            {
                KEY
            });

            viewManager.RegisterView(view);
            statsRecorder
            .NewMeasureMap()
            .Put(MEASURE_DOUBLE, 1.1)
            .Record(tagger.EmptyBuilder.Put(KEY, VALUE).Build());
            IViewData viewData = viewManager.GetView(VIEW_NAME);
            var       tv       = TagValues.Create(new List <TagValue>()
            {
                VALUE
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(noHistogram, MEASURE_DOUBLE, 1.1) },
            },
                EPSILON);
        }
Example #13
0
        public override IList <Metric> CreateMetrics(IViewData viewData, IAggregationData aggregation, TagValues tagValues, long timeStamp)
        {
            List <Metric> results = new List <Metric>();

            var unit = viewData.View.Measure.Unit;
            var tags = GetTagKeysAndValues(viewData.View.Columns, tagValues.Values);
            var name = viewData.View.Name.AsString;

            aggregation.Match <object>(
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, string.Empty, tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Sum));
                return(null);
            },
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, string.Empty, tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Sum));
                return(null);
            },
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, string.Empty, tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Count));
                return(null);
            },
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, string.Empty, tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Mean));
                return(null);
            },
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, string.Empty, tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Mean));
                results.Add(new Metric(GetMetricName(name, "max", tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Max));
                results.Add(new Metric(GetMetricName(name, "min", tags), MetricType.GAUGE, timeStamp, unit, tags, arg.Min));
                var stdDeviation = Math.Sqrt((arg.SumOfSquaredDeviations / arg.Count) - 1);
                if (double.IsNaN(stdDeviation))
                {
                    stdDeviation = 0.0;
                }

                results.Add(new Metric(GetMetricName(name, "stddev", tags), MetricType.GAUGE, timeStamp, unit, tags, stdDeviation));
                return(null);
            },
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, "value", tags), MetricType.GAUGE, timeStamp, unit, tags, arg.LastValue));
                return(null);
            },
                (arg) =>
            {
                results.Add(new Metric(GetMetricName(name, "value", tags), MetricType.GAUGE, timeStamp, unit, tags, arg.LastValue));
                return(null);
            },
                (arg) =>
            {
                return(null);
            });

            return(results);
        }
Example #14
0
        public void TestRecordWithEmptyStatsContext()
        {
            viewManager.RegisterView(
                CreateCumulativeView(VIEW_NAME, MEASURE_DOUBLE, DISTRIBUTION, new List <ITagKey>()
            {
                KEY
            }));
            // DEFAULT doesn't have tags, but the view has tag key "KEY".
            statsRecorder.NewMeasureMap().Put(MEASURE_DOUBLE, 10.0).Record(tagger.Empty);
            IViewData viewData = viewManager.GetView(VIEW_NAME);
            var       tv       = TagValues.Create(new List <ITagValue>()
            {
                MutableViewData.UnknownTagValue
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                // Tag is missing for associated measureValues, should use default tag value
                // "unknown/not set".
                { tv,
                  // Should Record stats with default tag value: "KEY" : "unknown/not set".
                  StatsTestUtil.CreateAggregationData(DISTRIBUTION, MEASURE_DOUBLE, 10.0) },
            },
                EPSILON);
        }
Example #15
0
        private void TestRecordCumulative(IMeasure measure, IAggregation aggregation, params double[] values)
        {
            IView view = CreateCumulativeView(CreateRandomViewName(), measure, aggregation, new List <string>()
            {
                Key
            });

            viewManager.RegisterView(view);
            ITagContext tags = tagger.EmptyBuilder.Put(Key, Value).Build();

            foreach (double val in values)
            {
                PutToMeasureMap(statsRecorder.NewMeasureMap(), measure, val).Record(tags);
            }
            IViewData viewData = viewManager.GetView(view.Name);

            Assert.Equal(view, viewData.View);

            var tv = TagValues.Create(new List <string>()
            {
                Value
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(aggregation, measure, values) },
            },
                Epsilon);
        }
        public void Record_CurrentContextNotSet()
        {
            Stats.State = StatsCollectionState.ENABLED;

            IViewName viewName = CreateRandomViewName();

            IView view =
                View.Create(
                    viewName,
                    "description",
                    MEASURE_DOUBLE,
                    Sum.Create(),
                    new List <string>()
            {
                KEY
            });

            viewManager.RegisterView(view);
            statsRecorder.NewMeasureMap().Put(MEASURE_DOUBLE, 1.0).Record();
            IViewData viewData = viewManager.GetView(viewName);

            // record() should have used the default TagContext, so the tag value should be null.
            ICollection <TagValues> expected = new List <TagValues>()
            {
                TagValues.Create(new List <string>()
                {
                    null
                })
            };
            ICollection <TagValues> actual = viewData.AggregationMap.Keys.ToList();

            Assert.Equal(expected, actual);
        }
Example #17
0
        public void Render(IController controller, string path)
        {
            //ViewData = new ViewData();

            ViewData = controller.ViewData;

            try
            {
                var html = String.Empty;

                string _path = string.Format("~/View/{0}/{1}.aspx", controller.Name, path);
                //var writer = new StringWriter();
                //controller.Context.Server.Execute(_path, controller.Context.Response.Output, true);
                //BuildManager.CreateInstanceFromVirtualPath(_path, typeof(System.Web.UI.Page));
               // controller.Context.RewritePath(_path,false);
                //var page = BuildManager.CreateInstanceFromVirtualPath(_path, typeof(Page)) as IHttpHandler;

                //PageParser.GetCompiledPageInstance(_path, controller.Context.Server.MapPath(_path), controller.Context);//.ProcessRequest(controller.Context);
                //html = writer.ToString();
                Context.Response.Clear();
                using (HtmlTextWriter htmlw = new HtmlTextWriter(Context.Response.Output))
                {

                   Context.Server.Execute(_path, htmlw, true);

                }
                Context.Response.End();

            }
            catch (System.Exception e)
            {
                controller.Context.Response.Write(e.StackTrace);
                controller.Context.Response.Write(e.ToString());
            }
        }
Example #18
0
        /// <summary>
        /// Create a view.
        /// </summary>
        /// <param name="context">Request and controller information.</param>
        /// <param name="viewData">Information that is used in the view</param>
        /// <param name="writer">Write the view using this writer.</param>
        public void Render(IControllerContext context, IViewData viewData, TextWriter writer)
        {
            string path = context.ViewPath + ".tiny";

            _logger.Trace("Rendering '" + path + "'");

            TinyView view = GetView(path, viewData.GetHashCode());

            if (view == null)
            {
                view = CreateView(context, viewData);
                Add(path, viewData.GetHashCode(), view);
            }

            if (view == null)
            {
                return; //should throw an exception.
            }
            try
            {
                view.Render(writer, viewData);
            }
            catch (Exception err)
            {
                _logger.Error("Failed to call view '" + path + "', reason: " + err);
                throw;
            }
        }
Example #19
0
        private void TestRecordCumulative(IMeasure measure, IAggregation aggregation, params double[] values)
        {
            IView view = CreateCumulativeView(VIEW_NAME, measure, aggregation, new List <ITagKey>()
            {
                KEY
            });

            clock.Time = Timestamp.Create(1, 2);
            viewManager.RegisterView(view);
            ITagContext tags = tagger.EmptyBuilder.Put(KEY, VALUE).Build();

            foreach (double val in values)
            {
                PutToMeasureMap(statsRecorder.NewMeasureMap(), measure, val).Record(tags);
            }
            clock.Time = Timestamp.Create(3, 4);
            IViewData viewData = viewManager.GetView(VIEW_NAME);

            Assert.Equal(view, viewData.View);

            var tv = TagValues.Create(new List <ITagValue>()
            {
                VALUE
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(aggregation, measure, values) },
            },
                EPSILON);
        }
Example #20
0
#pragma warning disable SA1202 // Elements must be ordered by access
        public void TestGetCumulativeViewDataWithEmptyBucketBoundaries()
#pragma warning restore SA1202 // Elements must be ordered by access
        {
            IAggregation noHistogram =
                Distribution.Create(BucketBoundaries.Create(new List <double>()));
            IView view = CreateCumulativeView(VIEW_NAME, MEASURE_DOUBLE, noHistogram, new List <ITagKey>()
            {
                KEY
            });

            clock.Time = Timestamp.Create(1, 0);
            viewManager.RegisterView(view);
            statsRecorder
            .NewMeasureMap()
            .Put(MEASURE_DOUBLE, 1.1)
            .Record(tagger.EmptyBuilder.Put(KEY, VALUE).Build());
            clock.Time = Timestamp.Create(3, 0);
            IViewData viewData = viewManager.GetView(VIEW_NAME);
            var       tv       = TagValues.Create(new List <ITagValue>()
            {
                VALUE
            });

            StatsTestUtil.AssertAggregationMapEquals(
                viewData.AggregationMap,
                new Dictionary <TagValues, IAggregationData>()
            {
                { tv, StatsTestUtil.CreateAggregationData(noHistogram, MEASURE_DOUBLE, 1.1) }
            },
                EPSILON);
        }
 /// <summary>
 /// Render a view.
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="context"></param>
 /// <param name="viewData"></param>
 public void Render(TextWriter writer, ControllerContext context, IViewData viewData)
 {
     foreach (IViewEngine engine in _viewEngines.Values)
     {
         engine.Render(context, viewData, writer);
         writer.Flush();
     }
 }
 public Controller(IView view, IDiskOperations diskOperation)
 {
     _view             = view;
     _viewData         = new ViewData();
     _diskOperations   = diskOperation;
     _currentDirectory = _diskOperations.GetCurDir();
     _pageSize         = 15;
 }
 public static void DeregisterViewData(string uniqueID, IViewData data)
 {
     _deregisterDataEvent.Publish(
         null,
         uniqueID,
         data
         );
 }
Example #24
0
 public BluetoothListenerManager(IViewData data, CoreDispatcher dispatcher)
 {
     _data            = data;
     _dispatcher      = dispatcher;
     _bluetoothDevice = new BluetoothReceiver();
     //_bluetoothDevice.AdvertisementReceived += PackageReceived;
     _isActive = false;
 }
Example #25
0
 /// <summary>
 /// Render a view.
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="context"></param>
 /// <param name="viewData"></param>
 public void Render(TextWriter writer, ControllerContext context, IViewData viewData)
 {
     foreach (IViewEngine engine in _viewEngines.Values)
     {
         engine.Render(context, viewData, writer);
         writer.Flush();
     }
 }
Example #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private TinyView CreateView(IControllerContext context, IViewData data)
        {
            string   templateName = context.ViewPath + ".tiny";
            Resource resource     = _provider.Get(templateName);

            if (resource == null)
            {
                _logger.Warning("Failed to load " + templateName);
                return(null);
            }

            // Add all namespaces and assemblies needed.
            var compiler = new Compiler();

            compiler.Add(typeof(IView));
            compiler.Add(typeof(string));
            compiler.Add(typeof(TextWriter));
            foreach (var parameter in data)
            {
                compiler.Add(parameter.Value.GetType());
            }

            using (resource.Stream)
            {
                var buffer = new byte[resource.Stream.Length];
                resource.Stream.Read(buffer, 0, buffer.Length);

                TextReader reader = new StreamReader(resource.Stream);
                var        sb     = new StringBuilder();

                // parse
                Parse(reader, sb);

                // and add it in the type.
                string code = ClassContents;
                code = code.Replace("{body}", sb.ToString());

                // add view data types.
                string types = string.Empty;
                foreach (var parameter in data)
                {
                    types = Compiler.GetTypeName(parameter.Value.GetType()) + " " + parameter.Key + " = (" +
                            Compiler.GetTypeName(parameter.Value.GetType()) + ")viewData[\"" + parameter.Key + "\"];";
                }
                code = code.Replace("{viewDataTypes}", types);

                try
                {
                    compiler.Compile(code);
                }
                catch (Exception err)
                {
                    _logger.Error("Failed to compile template " + templateName + ", reason: " + err);
                }
                return(compiler.CreateInstance <TinyView>());
            }
        }
        public void TestCumulativeViewData()
        {
            IView     view     = View.Create(NAME, DESCRIPTION, MEASURE_DOUBLE, DISTRIBUTION, TAG_KEYS);
            var       start    = DateTimeOffset.FromUnixTimeMilliseconds(1000);
            var       end      = DateTimeOffset.FromUnixTimeMilliseconds(2000);
            IViewData viewData = ViewData.Create(view, ENTRIES, start, end);

            Assert.Equal(view, viewData.View);
            Assert.Equal(ENTRIES, viewData.AggregationMap);
        }
        public void TestRegisterAndGetView()
        {
            MeasureToViewMap measureToViewMap = new MeasureToViewMap();

            measureToViewMap.RegisterView(VIEW);
            IViewData viewData = measureToViewMap.GetView(VIEW_NAME, StatsCollectionState.ENABLED);

            Assert.Equal(VIEW, viewData.View);
            Assert.Empty(viewData.AggregationMap);
        }
Example #29
0
        public void TestCumulativeViewData()
        {
            IView      view     = View.Create(NAME, DESCRIPTION, MEASURE_DOUBLE, DISTRIBUTION, TAG_KEYS);
            ITimestamp start    = Timestamp.FromMillis(1000);
            ITimestamp end      = Timestamp.FromMillis(2000);
            IViewData  viewData = ViewData.Create(view, ENTRIES, start, end);

            Assert.Equal(view, viewData.View);
            Assert.Equal(ENTRIES, viewData.AggregationMap);
        }
Example #30
0
        public string ViewDataToString(IViewData viewData)
        {
            var str = string.Empty;

            foreach (var data in viewData)
            {
                str += string.Format("{0} = {1}, ", data.Key, data.Value ?? "NULL!");
            }

            return(str.Length > 0 ? str.Remove(str.Length - 2, 2) : str);
        }
Example #31
0
        private void RenderView(ControllerContext controllerContext, IViewData viewData)
        {
            //ViewProvider.Get(controllerContext.ViewPath + ".*");


            // do not dispose writer, since it will close the stream.
            TextWriter bodyWriter = new StreamWriter(controllerContext.RequestContext.Response.Body);


            _viewEngines.Render(bodyWriter, controllerContext, viewData);
            bodyWriter.Flush();
        }
        public void TestRegisterAndGetView()
        {
            MeasureToViewMap measureToViewMap = new MeasureToViewMap();
            TestClock        clock            = TestClock.Create(Timestamp.Create(10, 20));

            measureToViewMap.RegisterView(VIEW, clock);
            clock.Time = Timestamp.Create(30, 40);
            IViewData viewData = measureToViewMap.GetView(VIEW_NAME, clock, StatsCollectionState.ENABLED);

            Assert.Equal(VIEW, viewData.View);
            Assert.Empty(viewData.AggregationMap);
        }
        protected internal IList <Metric> CreateMetricsFromViewData(IViewData viewData, long timeStamp)
        {
            List <Metric> result = new List <Metric>();

            foreach (var entry in viewData.AggregationMap)
            {
                IList <Metric> metrics = metricFormatWriter.CreateMetrics(viewData, entry.Value, entry.Key, timeStamp);
                result.AddRange(metrics);
            }

            return(result);
        }
Example #34
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private TinyView CreateView(IControllerContext context, IViewData data)
        {
            string templateName = context.ViewPath + ".tiny";
            Resource resource = _provider.Get(templateName);
            if (resource == null)
            {
                _logger.Warning("Failed to load " + templateName);
                return null;
            }

            // Add all namespaces and assemblies needed.
            var compiler = new Compiler();
            compiler.Add(typeof (IView));
            compiler.Add(typeof (string));
            compiler.Add(typeof (TextWriter));
            foreach (var parameter in data)
                compiler.Add(parameter.Value.GetType());

            using (resource.Stream)
            {
                var buffer = new byte[resource.Stream.Length];
                resource.Stream.Read(buffer, 0, buffer.Length);

                TextReader reader = new StreamReader(resource.Stream);
                var sb = new StringBuilder();

                // parse
                Parse(reader, sb);

                // and add it in the type.
                string code = ClassContents;
                code = code.Replace("{body}", sb.ToString());

                // add view data types.
                string types = string.Empty;
                foreach (var parameter in data)
                {
                    types = Compiler.GetTypeName(parameter.Value.GetType()) + " " + parameter.Key + " = (" +
                            Compiler.GetTypeName(parameter.Value.GetType()) + ")viewData[\"" + parameter.Key + "\"];";
                }
                code = code.Replace("{viewDataTypes}", types);

                try
                {
                    compiler.Compile(code);
                }
                catch (Exception err)
                {
                    _logger.Error("Failed to compile template " + templateName + ", reason: " + err);
                }
                return compiler.CreateInstance<TinyView>();
            }
        }
Example #35
0
        private void RenderView(ControllerContext controllerContext, IViewData viewData)
        {
            //ViewProvider.Get(controllerContext.ViewPath + ".*");


            // do not dispose writer, since it will close the stream.
            TextWriter bodyWriter = new StreamWriter(controllerContext.RequestContext.Response.Body);


            _viewEngines.Render(bodyWriter, controllerContext, viewData);
            bodyWriter.Flush();
        }
Example #36
0
 /// <summary>
 /// Render view into the supplied text writer.
 /// </summary>
 /// <param name="writer">Text writer to render in.</param>
 /// <param name="viewData">Supplied view data</param>
 public abstract void Render(TextWriter writer, IViewData viewData);
Example #37
0
 public override void Display(IViewData data)
 {
     Console.WriteLine("this is second view");
     base.Display(data);
 }
Example #38
0
        /// <summary>
        /// Create a view.
        /// </summary>
        /// <param name="context">Request and controller information.</param>
        /// <param name="viewData">Information that is used in the view</param>
        /// <param name="writer">Write the view using this writer.</param>
        public void Render(IControllerContext context, IViewData viewData, TextWriter writer)
        {
            string path = context.ViewPath + ".tiny";
            _logger.Trace("Rendering '" + path + "'");

            TinyView view = GetView(path, viewData.GetHashCode());
            if (view == null)
            {
                view = CreateView(context, viewData);
                Add(path, viewData.GetHashCode(), view);
            }

            if (view == null)
                return; //should throw an exception.

            try
            {
                view.Render(writer, viewData);
            }
            catch (Exception err)
            {
                _logger.Error("Failed to call view '" + path + "', reason: " + err);
                throw;
            }
        }
Example #39
0
 /// <summary>
 /// Create a view.
 /// </summary>
 /// <param name="context">Context to render</param>
 public void Render(ControllerContext context, IViewData viewData, TextWriter writer)
 {
     _spark.
     throw new NotImplementedException();
 }
Example #40
0
 public virtual void Display(IViewData data)
 {
     foreach(IModel model in data.ModelList)
     {
         Console.WriteLine(model.GetStringData());
     }
 }
Example #41
0
 public TokenEngine(string content, IViewData tokens)
 {
     Content = content;
     Tokens = tokens;
     Default = string.Empty;
 }
Example #42
0
        /// <summary>
        /// Create view
        /// </summary>
        /// <param name="context">Context used creating view</param>
        /// <param name="viewUri">Path to view being created.</param>
        /// <param name="data">Data used.</param>
        /// <returns>Created view.</returns>
        /// <exception cref="ViewNotFoundException">Failed to find spark view.</exception>
        private SparkView GenerateView(IControllerContext context, string viewUri, IViewData data)
        {
            var descriptor = new SparkViewDescriptor();
            descriptor.AddTemplate(viewUri);

            // Let's not include layouts for ajax requests.
            if (!context.RequestContext.Request.IsAjax)
            {
                string layoutUri = SelectLayoutName(context.LayoutName);
                descriptor.Templates.Add(layoutUri);
            }

            if (!MvcServer.CurrentMvc.ViewProvider.Exists(viewUri))
            {
                _logger.Info("Failed to find " + viewUri);
                throw new ViewNotFoundException(viewUri, "Failed to find spark view '" + viewUri + "'.");
            }


            /* Disabled since types can be null.
             * 
            // since we use strongly typed accessors, we need to loop through view data.
            // and add direct accessors.
            foreach (var viewData in data)
            {
                string typeName = GetTypeName(viewData.Value.GetType(), true);
                descriptor.AddAccessor(typeName + " " + viewData.Key,
                                       "(" + typeName + ")ViewData[\"" + viewData.Key + "\"]");
            }
            */

            ISparkViewEntry entry;
            try
            {
                entry = _engine.CreateEntry(descriptor);
            }
            catch(Exception err)
            {
                _logger.Warning("Failed to compile view.", err);
                throw new InternalServerException("Failed to compile view '" + viewUri + "'.", err);
            }

            // only lock when adding, to avoid duplicates.
            if (context.RequestContext.Request.IsAjax)
            {
                lock (_ajaxMappings)
                {
                    Mapping mapping;
                    if (!_ajaxMappings.TryGetValue(viewUri, out mapping))
                    {
                        mapping = new Mapping(data.GetHashCode(), entry);
                        _ajaxMappings.Add(viewUri, mapping);
                    }
                    else
                        mapping.Add(data.GetHashCode(), entry);
                }
            }
            else
            {
                lock (_mappings)
                {
                    Mapping mapping;
                    if (!_mappings.TryGetValue(viewUri, out mapping))
                    {
                        mapping = new Mapping(data.GetHashCode(), entry);
                        _mappings.Add(viewUri, mapping);
                    }
                    else
                        mapping.Add(data.GetHashCode(), entry);
                }
            }

            return (SparkView) entry.CreateInstance();
        }
Example #43
0
        /// <summary>
        /// Create a view.
        /// </summary>
        /// <param name="context">Request and controller information.</param>
        /// <param name="viewData">Information that is used in the view</param>
        /// <param name="writer">Write the view using this writer.</param>
        public void Render(IControllerContext context, IViewData viewData, TextWriter writer)
        {
            _currentEngine = this;

            string viewUri = context.ViewPath + ".spark";

            try
            {
                // try to find our view, or create it if it do not exist.
                SparkView view = GenerateView(context, viewUri, viewData);

                // attach view data and render it.
                view.ViewData = viewData;
                view.Uri = context.RequestContext.Request.Uri;
                view.ControllerName = context.ControllerName;
                view.ControllerUri = context.ControllerUri;
                view.Title = context.Title;
                view.ActionName = context.ActionName;

                // Using custom view, let the implementor have a chance to init it.
                if (_handler != null)
                    _handler(view, context);

                view.RenderView(writer);

                // release it.
                _engine.ReleaseInstance(view);

                writer.Flush();
            }
            catch(Exception err)
            {
                _logger.Error("Failed to render " + viewUri + " using viewdata " + ViewDataToString(viewData));
                throw new InvalidOperationException("Failed to render " + viewUri, err);
            }
        }
Example #44
0
        public string ViewDataToString(IViewData viewData)
        {
            var str = string.Empty;
            foreach (var data in viewData)
                str += string.Format("{0} = {1}, ", data.Key, data.Value ?? "NULL!");

            return str.Length > 0 ? str.Remove(str.Length - 2, 2) : str;
        }
Example #45
0
 /// <summary>
 /// Render view into the supplied text writer.
 /// </summary>
 /// <param name="writer">Text writer to render in.</param>
 /// <param name="viewData">Supplied view data</param>
 public override void Render(TextWriter writer, IViewData viewData)
 {
 }