public async Task AddTrace(string userId, TraceViewModel trace)
        {
            // ID
            // locomotion = move
            // isaidriven = trackingMode (manual)
            // id_ref_user_fk
            // riverside = bank - virrer le bank de "leftBank"
            // remark = ???
            // createdon = date

            // TODO: Create Trace object
            Trace dbTrace = new Trace();

            dbTrace.Id         = Guid.Parse(trace.id);
            dbTrace.Locomotion = trace.move;
            dbTrace.IsAiDriven = trace.trackingMode.ToLower() != "manual";
            dbTrace.UserId     = Guid.Parse(userId);
            dbTrace.Riverside  = trace.bank.ToLower().Replace("bank", "");
            dbTrace.CapturedOn = trace.date;
            dbTrace.Remark     = trace.comment;

            // Save to DB
            await _traceStore.CreateCampaign(dbTrace);

            // Upload to blob storage
        }
Beispiel #2
0
        public ActionResult Index(String id, Pager pager)
        {
            if (id.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(id));
            }

            var list = Search(id, pager);

            if (list.Count > 0)
            {
                var appId = list[0].AppId;
                var ar    = AppTracer.FindByID(appId);
                if (ar != null)
                {
                    ViewBag.Title = $"{ar}调用链";
                }
            }

            var model = new TraceViewModel
            {
                Page = pager,
                Data = list
            };

            return(View("Index", model));
        }
Beispiel #3
0
 public TraceView(TraceViewModel viewModel)
 {
     InitializeComponent();
     if (!DesignerProperties.GetIsInDesignMode(this))
     {
         DataContext = viewModel;
     }
 }
        public async Task AddTrajectoryPoints(TraceViewModel trace)
        {
            List <Position> positions = trace.positions.Select(p => new Position(p)).ToList();

            positions.ForEach(p =>
            {
                p.Id          = Guid.NewGuid();
                p.RefCampaign = Guid.Parse(trace.id);
                p.Createdon   = DateTime.Now;
            });
            // Save to DB
            await _traceStore.CreateTrajectoryPoints(positions);

            // Upload to blob storage
        }
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            this.EnsureBindingContextIsSet(savedInstanceState);
            var ignored = base.OnCreateView(inflater, container, savedInstanceState);
            var view    = this.BindingInflate(Resource.Layout.ReferralView, null);

            ViewModel.ChangedDate += ViewModel_ChangedDate;

            var vm = new TraceViewModel();;

            vm.Parent = ViewModel;

            ViewModel.AddTraceCommandAction = () =>
            {
                vm.EditMode = false;

                var dialogFragment = new TraceFragment()
                {
                    DataContext = vm
                };

                dialogFragment.Show(FragmentManager, "Trace01");
            };

            ViewModel.CloseTestCommandAction = () =>
            {
                var frag = FragmentManager.FindFragmentByTag("Trace01");
                if (null != frag)
                {
                    ((TraceFragment)frag).Dismiss();
                }
            };

            ViewModel.EditTestCommandAction = () =>
            {
                vm.EditMode = true;
                var dialogFragment = new TraceFragment()
                {
                    DataContext = vm
                };

                dialogFragment.Show(FragmentManager, "Trace01");
            };

            return(view);
        }
Beispiel #6
0
        public async Task <IActionResult> RunUploadTrace(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "trace")] HttpRequest req,
            [Blob("trace", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainer,
            [Blob("trace-attachments", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerAttachments,
            [AccessToken] AccessTokenResult accessTokenResult,
            ILogger log
            )
        {
            log.LogInformation("Trace file");
            if (accessTokenResult.Status != AccessTokenStatus.Valid)
            {
                return(new UnauthorizedResult());
            }

            var            body    = await new StreamReader(req.Body).ReadToEndAsync();
            TraceViewModel traceVm = JsonSerializer.Deserialize <TraceViewModel>(body);

            /// Backup trace to storage account
            string name = $"{DateTime.UtcNow.Year}/{DateTime.Now.Month}/{DateTime.UtcNow.Day}/{traceVm.id}.json";

            var traceAttachmentBlob = blobContainer.GetBlockBlobReference(name);

            traceAttachmentBlob.Properties.ContentType = "application/json";
            traceAttachmentBlob.Metadata.Add("uid", accessTokenResult.User.Id);
            await traceAttachmentBlob.UploadTextAsync(body);

            // Insert it into PGSQL

            await _traceService.AddTrace(accessTokenResult.User.Id, traceVm);

            string attachmentPath = $"{accessTokenResult.User.Id}/{traceVm.id}/{{fileName}}";

            var sas = blobContainerAttachments.GetSharedAccessSignature(new SharedAccessBlobPolicy()
            {
                Permissions = SharedAccessBlobPermissions.Add | SharedAccessBlobPermissions.Create |
                              SharedAccessBlobPermissions.Write,
                SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(20)
            });

            return(new OkObjectResult(new
            {
                traceId = traceVm.id,
                uploadUri = $"{blobContainerAttachments.Uri.AbsoluteUri}/{attachmentPath}{sas}"
            }));
        }
        public Fast99EffectsViewModel()
        {
            var lowryViewModel = new LowryViewModel();

            lowryViewModel.PlotParameterData(LowryPlotDataFrom4DPieCharts);
            lowryViewModel.Width  = 222;
            lowryViewModel.Height = 444;
            LowryViewModel        = lowryViewModel;

            var traceViewModel = new TraceViewModel();

            traceViewModel.PlotTraceData(
                new NumDataColumn("time", new[] { 0.0, 1.0, 2.0, 3.0 }),
                new NumDataColumn("output", new[] { 0.0, 4.0, 8.0, 12.0 })
                );
            traceViewModel.SelectedX = 2.0;
            TraceViewModel           = traceViewModel;
        }
        public MorrisEffectsViewModel()
        {
            var muStarSigmaViewModel = new MuStarSigmaViewModel();

            muStarSigmaViewModel.SetBounds(-2, 15, -2, 15);
            muStarSigmaViewModel.Plot(
                Range(1, 10)
                .Map(i => new MuStarSigmaParameterMeasure($"{i}", i * 1d, i * 1d))
                .ToArr()
                );
            MuStarSigmaViewModel = muStarSigmaViewModel;

            var traceViewModel = new TraceViewModel();

            traceViewModel.PlotTraceData(
                new NumDataColumn("time", new[] { 0.0, 1.0, 2.0, 3.0 }),
                new NumDataColumn("output", new[] { 0.0, 4.0, 8.0, 12.0 })
                );
            traceViewModel.SelectedX = 2.0;
            TraceViewModel           = traceViewModel;
        }
Beispiel #9
0
        public JsonResult GetTracesPaged(int offset, int limit, string search, string sort, string order)
        {
            // get logs newer than 7 days
            var nowUtc = _now.UtcNow;

            var traces =
                _context.AsQueryable <LogEntry>().Include(x => x.Steps)
                .Where(x => DbFunctions.AddHours(x.Timestamp, LogLimit) > nowUtc)
                .AsQueryable();

            IOrderedQueryable <LogEntry> pagedTraces;

            switch (order)
            {
            case LogsSortAscendingKey:
                pagedTraces = traces.OrderAscending(sort);
                break;

            case LogsSortDescendingKey:
                pagedTraces = traces.OrderDescending(sort);
                break;

            default:
                pagedTraces = traces.OrderDescending(sort);
                break;
            }

            List <LogEntry> pagedTracesList;

            if (string.IsNullOrEmpty(search))
            {
                pagedTracesList = pagedTraces
                                  .Skip((offset / limit) * limit)
                                  .Take(limit).ToList();
            }
            else
            {
                string searchLikeExpression = string.Format("%{0}%", search);
                Expression <Func <LogEntry, bool> > searchExpression =
                    entry => SqlFunctions.PatIndex(searchLikeExpression, entry.RequestUri) > 0 ||
                    entry.Steps.Any(x => SqlFunctions.PatIndex(searchLikeExpression, x.Frame) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Message) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Name) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Metadata) > 0);

                pagedTracesList = pagedTraces.AsExpandable().Where(searchExpression).Skip((offset / limit) * limit).Take(limit).ToList();
            }

            var tracesVms = new List <TraceViewModel>();

            foreach (var trace in pagedTracesList)
            {
                var traceSteps = trace.Steps.OrderBy(x => x.Index).ToList();

                var builder = new StringBuilder();
                builder.Append("<p style=\"white-space: nowrap;\">Start request </p>");

                foreach (var tracestep in traceSteps)
                {
                    builder.Append(string.Format("<p style=\"white-space: nowrap;\">{0}</p>", string.Format("From {0} method located in frame {1} {2} {3} \r\n", tracestep.Source,
                                                                                                            string.Format("<pre class=\"prettyprint lang-cs\">{0}</pre>", tracestep.Frame),
                                                                                                            (!string.IsNullOrEmpty(tracestep.Name) ? string.Format(" (which processes {0}) ", tracestep.Name) : ""),
                                                                                                            (!string.IsNullOrEmpty(tracestep.Message) ? string.Format(" (with message {0}) ", tracestep.Message) : ""))));

                    if (string.IsNullOrEmpty(tracestep.Metadata))
                    {
                        continue;
                    }

                    builder.Append("<p style=\"white-space: nowrap;\">With metadata: </p>");

                    string beautified;
                    if (XmlUtils.IsValidXml(tracestep.Metadata))
                    {
                        // xml
                        // operation metadata is xml in our case
                        beautified = XmlPrettifyHelper.Prettify(tracestep.Metadata.Replace(XmlHeader8, "").Replace(XmlHeader16, ""));
                    }
                    else if (JsonUtils.IsValidJson(tracestep.Metadata))
                    {
                        beautified = string.Format("<pre class=\"prettyprint lang-json\">{0}</pre>",
                                                   JsonPrettifier.BeautifyJson(tracestep.Metadata));
                    }
                    else
                    {
                        beautified = tracestep.Metadata;
                    }

                    builder.Append(beautified);
                }

                builder.Append("<p style=\"white-space: nowrap;\">End request </p>");

                var traceString = HttpUtility.HtmlEncode(builder.ToString());

                var captureDuration = trace.ResponseTimestamp.HasValue && trace.RequestTimestamp.HasValue;

                var item = new TraceViewModel
                {
                    Duration = captureDuration ? string.Format("{0} seconds",
                                                               (trace.ResponseTimestamp.Value - trace.RequestTimestamp.Value).TotalSeconds.ToString("#.##")) : "Duration not captured",
                    Timestamp = trace.Timestamp.ToString(CultureInfo.InvariantCulture),
                    Uri       = trace.RequestUri,
                    Workflow  = new HtmlString(HttpUtility.HtmlDecode(traceString)).ToHtmlString()
                };

                tracesVms.Add(item);
            }

            var model = new
            {
                total = traces.Count(),
                rows  = tracesVms
            };

            return(Json(model, JsonRequestBehavior.AllowGet));
        }
        public async Task <IActionResult> RunUploadTraceAttachment(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "trace/{traceId}/attachments/{fileName}")] HttpRequest req,
            [Blob("images2label", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerImageToLabel,
            [Blob("mobile", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerMobile,
            [Blob("gopro", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerGoPro,
            [AccessToken] AccessTokenResult accessTokenResult,
            string traceId,
            string fileName,
            ILogger log,
            [Blob("manual/{traceId}.json", FileAccess.Read, Connection = "TraceStorage")] Stream traceManualIdJsonFile = null,
            [Blob("mobile/{traceId}.json", FileAccess.Read, Connection = "TraceStorage")] Stream traceMobileIdJsonFile = null,
            [Blob("gopro/{traceId}.json", FileAccess.Read, Connection = "TraceStorage")] Stream traceGoProIdJsonFile   = null
            )
        {
            log.LogInformation("Trace Attachment file");

            if (accessTokenResult.Status != AccessTokenStatus.Valid)
            {
                return(new UnauthorizedResult());
            }

            Stream jsonStream;

            if (traceManualIdJsonFile != null)
            {
                jsonStream = traceManualIdJsonFile;
            }
            else
            {
                if (traceMobileIdJsonFile != null)
                {
                    jsonStream = traceMobileIdJsonFile;
                }
                else
                {
                    if (traceGoProIdJsonFile != null)
                    {
                        jsonStream = traceGoProIdJsonFile;
                    }
                    else
                    {
                        return(new UnauthorizedResult());
                    }
                }
            }
            var            trace   = await new StreamReader(jsonStream).ReadToEndAsync();
            TraceViewModel traceVm = JsonSerializer.Deserialize <TraceViewModel>(trace);

            //ecrire dans le bon blob
            string         name                = string.Empty;
            Guid           mediaId             = Guid.NewGuid();
            CloudBlockBlob traceAttachmentBlob = null;
            string         extension           = Path.GetExtension(fileName);

            if (traceVm.trackingMode.ToLower() == "manual")
            {
                name = await GetNextFileName(blobContainerImageToLabel, traceId, extension);

                traceAttachmentBlob = blobContainerImageToLabel.GetBlockBlobReference(name);
            }
            if (traceVm.trackingMode.ToLower() == "automatic")
            {
                name = await GetNextFileName(blobContainerMobile, traceId, extension);

                traceAttachmentBlob = blobContainerMobile.GetBlockBlobReference(name);
            }
            if (traceVm.trackingMode.ToLower() == "gopro")
            {
                name = await GetNextFileName(blobContainerGoPro, traceId, extension);

                traceAttachmentBlob = blobContainerGoPro.GetBlockBlobReference(name);
            }

            traceAttachmentBlob.Properties.ContentType = req.ContentType;
            traceAttachmentBlob.Metadata.Add("uid", accessTokenResult.User.Id);
            traceAttachmentBlob.Metadata.Add("mediaId", mediaId.ToString());
            await traceAttachmentBlob.UploadFromStreamAsync(req.Body);

            // Add to Media
            try
            {
                await _mediaStore.AddMedia(mediaId, name, accessTokenResult.User.Id, traceId, DateTime.UtcNow, traceAttachmentBlob.Uri);

                ImageLabel imageToInsert = new ImageLabel(Guid.NewGuid(), Guid.Parse(accessTokenResult.User.Id), DateTime.Now, name, string.Empty, string.Empty, string.Empty, traceAttachmentBlob.Uri.AbsoluteUri);
                if (traceVm.trackingMode.ToLower() == "manual")
                {
                    await _imageService.InsertImageData(imageToInsert);
                }
            }
            catch (Exception e)
            {
                log.LogError(e, "Unable to store media to DB");
            }

            return(new StatusCodeResult(200));
        }
        public async Task <IActionResult> RunUploadTrace(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "trace")] HttpRequest req,
            [Blob("manual", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerManual,
            [Blob("mobile", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerMobile,
            [Blob("gopro", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainerGoPro,
            [AccessToken] AccessTokenResult accessTokenResult,
            ILogger log
            )
        {
            log.LogInformation("Trace file");
            if (accessTokenResult.Status != AccessTokenStatus.Valid)
            {
                return(new UnauthorizedResult());
            }
            var            body    = await new StreamReader(req.Body).ReadToEndAsync();
            TraceViewModel traceVm = JsonSerializer.Deserialize <TraceViewModel>(body);

            /// Backup trace to storage account
            string name = $"{traceVm.id}.json";

            CloudBlockBlob         traceAttachmentBlob = blobContainerManual.GetBlockBlobReference(name);
            SharedAccessBlobPolicy sharedAccessPolicy  = new SharedAccessBlobPolicy()
            {
                Permissions = SharedAccessBlobPermissions.Add | SharedAccessBlobPermissions.Create |
                              SharedAccessBlobPermissions.Write,
                SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(20)
            };
            string sas = blobContainerManual.GetSharedAccessSignature(sharedAccessPolicy);

            if (traceVm.trackingMode.ToLower() == "automatic")
            {
                traceAttachmentBlob = blobContainerMobile.GetBlockBlobReference(name);
                sas = blobContainerMobile.GetSharedAccessSignature(sharedAccessPolicy);
            }
            if (traceVm.trackingMode.ToLower() == "gopro")
            {
                traceAttachmentBlob = blobContainerGoPro.GetBlockBlobReference(name);
                sas = blobContainerMobile.GetSharedAccessSignature(sharedAccessPolicy);
            }

            traceAttachmentBlob.Properties.ContentType = "application/json";
            traceAttachmentBlob.Metadata.Add("uid", accessTokenResult.User.Id);
            await traceAttachmentBlob.UploadTextAsync(body);

            // Insert it into PGSQL
            try
            {
                await _traceService.AddTrace(accessTokenResult.User.Id, traceVm);

                await _traceService.AddTrajectoryPoints(traceVm);
            }
            catch (Exception e)
            {
                log.LogError(e, "Unable to store media to DB");
            }

            return(new OkObjectResult(new
            {
                traceId = traceVm.id,
                uploadUri = $"{traceAttachmentBlob.Uri.AbsoluteUri}{sas}"
            }));
        }