Ejemplo n.º 1
0
        /// <summary>
        /// Get a usage from the cache for given customer and given feature
        ///
        /// Note that this call is lightning-fast and built for massive requesting : it uses an internal cache to avoid calling the API too often
        /// The caching increase the resilience of your integration : in case of a temporary communication problem, an error is returned, but the last known usage will be returned too by this method
        /// </summary>
        /// <param name="usages">The customer usage</param>
        /// <param name="referenceCustomer">(mandatory) the customer reference</param>
        /// <param name="referenceFeature">(mandatory) the feature reference</param>
        public virtual RequestReport FastGetUsage(out Usage usage, object referenceCustomer, object referenceFeature, bool forceReloading)
        {
            usage = null;
            RequestReport result;

            // we need a customer and a feature
            if ((referenceCustomer != null) &&
                referenceFeature != null)
            {
                // get cached usages for customer
                List <Usage> usages;
                result = this.FastListUsages(out usages, referenceCustomer, forceReloading);
                // if any
                if ((usages != null) &&
                    (usages.Count > 0))
                {
                    // find the one for given feature
                    usage = usages.Find(u => u.ReferenceFeature == referenceFeature.ToString());
                }
            }
            // if we miss a mandatory parameter
            else
            {
                // return an error
                result = new RequestReport
                {
                    Code    = "Api.Client.FastGetUsage.MissingParameter",
                    Message = "Missing parameter - FastGetUsage requires a ReferenceCustomer and a ReferenceFeature"
                }
            };

            return(result);
        }
Ejemplo n.º 2
0
        public ActionResult GenerateEmployeeReport(RequestReport requestReport)
        {
            if (requestReport.InitialDate != null && requestReport.EndDate != null)
            {
                var Renderer = new HtmlToPdf();
                Renderer.PrintOptions.MarginTop    = 50;
                Renderer.PrintOptions.MarginBottom = 50;
                Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
                Renderer.PrintOptions.Header       = new SimpleHeaderFooter()
                {
                    CenterText = "Reporte de Empleados del " + requestReport.InitialDate?.ToString("dd/MM/yyyy") + " hasta el " +
                                 requestReport.EndDate?.ToString("dd/MM/yyyy"),
                    DrawDividerLine = true,
                    FontSize        = 14
                };
                Renderer.PrintOptions.Footer = new SimpleHeaderFooter()
                {
                    LeftText        = "{date} {time}",
                    RightText       = "Página {page} de {total-pages}",
                    DrawDividerLine = true,
                    FontSize        = 14
                };
                var PDF = Renderer.RenderHtmlAsPdf(GetHtmlAgencyProducts(requestReport.InitialDate, requestReport.EndDate));

                return(File(PDF.BinaryData, "application/pdf", $"employees_report_{requestReport.InitialDate?.ToString("yyyyMMdd")}_to_{requestReport.EndDate?.ToString("yyyyMMdd")}.pdf"));
            }

            return(View());
        }
Ejemplo n.º 3
0
        static public void SendTestRequests(
            IReadOnlyList <int> sensorIds,
            ISensorService sensorService,
            int requestCount,
            int repeatCount,
            TimeSpan maxStepLength,
            RequestReport report)
        {
            var random = new Random();

            for (int i = 0; i < repeatCount; i++)
            {
                List <GetSensorDataParameters> parameters = Enumerable
                                                            .Repeat(0, requestCount)
                                                            .Select(_ => new GetSensorDataParameters {
                    SensorId = sensorIds[random.Next(sensorIds.Count)]
                })
                                                            .ToList();

                // Debug использован для простоты - чтобы не конфигурировать цвета в NLog.config.
                _logger.Debug($"Trying to send {requestCount} requests simultaneously (attempt #{i + 1} of {repeatCount}).");

                report.Start();

                var tasks = parameters
                            .Select(x => Task.Run(() => sensorService.GetSensorData(x)))
                            .ToArray();

                Task.WaitAll(tasks);
                report.StopAndLog(maxStepLength);
            }
        }
Ejemplo n.º 4
0
        public List <ResponseReport> GetSenzorByName(RequestReport report)
        {
            List <Senzor>    Senzori    = _reportService.GetReportBySenzorName(report);
            List <SenzorDTO> SenzorDTOs = _reportService.GetReportBySenzorNameDTO(Senzori);

            return(_reportService.GenerateMeasurementRepot(SenzorDTOs));
        }
Ejemplo n.º 5
0
        void ShowStimulsoft(RequestReport rep, String repName)
        {
            ReportHelper.SetupLicense();
            try
            {
                rep.CheckPermissions(_baseController.UserStateManager.GetUserPermissions(), _baseController.Host.IsDebugConfiguration);

                MvcHtmlString result = null;
                using (var pr = Profiler.CurrentRequest.Start(ProfileAction.Report, $"render: {repName}"))
                {
                    result = ReportHelper.ShowViewer(this);
                }

                var sb = new StringBuilder(ResourceHelper.StiReportHtml);
                sb.Replace("$(StiReport)", result.ToHtmlString());
                sb.Replace("$(Lang)", _baseController.CurrentLang);
                sb.Replace("$(Title)", _baseController.Localize(rep.name ?? repName));

                Response.Output.Write(sb.ToString());
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                Response.Write(ex.Message);
            }
        }
Ejemplo n.º 6
0
        public List <Senzor> GetReportBySenzorName(RequestReport report)
        {
            List <Senzor> dataBaseResponse = database.Senzori.
                                             Where(x => x.ImeSenzora == report.ImeSenzora && report.MjestoSenzora == x.Uredjaj.Lokacija && x.VrijemeMjerenja >= report.VrijemeOd && x.VrijemeMjerenja <= report.VrijemeDo) /*.Include(x => x.Uredjaj)*/.ToList();

            return(dataBaseResponse);
        }
Ejemplo n.º 7
0
        public static void UpdateRequestReport(this RequestReport requestReport, RequestReportViewModel requestReportVm)
        {
            requestReport.ID          = requestReportVm.ID;
            requestReport.RequestID   = requestReportVm.RequestID;
            requestReport.SupporterID = requestReportVm.SupporterID;
            requestReport.Note        = requestReportVm.Note;

            requestReport.CreatedDate     = requestReportVm.CreatedDate;
            requestReport.CreatedBy       = requestReportVm.CreatedBy;
            requestReport.UpdatedDate     = requestReportVm.UpdatedDate;
            requestReport.UpdatedBy       = requestReportVm.UpdatedBy;
            requestReport.MetaKeyword     = requestReportVm.MetaKeyword;
            requestReport.MetaDescription = requestReportVm.MetaDescription;
            requestReport.Status          = requestReportVm.Status;
        }
Ejemplo n.º 8
0
        private async void frmReportRequests_Load(object sender, EventArgs e)
        {
            var searchRequest = new RequestSearchRequest
            {
                StatusId = (int)EStatus.Finished
            };

            var requestList = await _requestService.GetAll <List <Request> >(searchRequest);

            var sourceList = new List <RequestReport>();

            foreach (var request in requestList)
            {
                var client = await _authService.GetById(request.ClientId);

                var clientAddress = await _addressService.GetById <Address>((int)client.AddressId);

                var requestAddress = await _addressService.GetById <Address>(request.DeliveryAddress);

                var offerRequest = new OfferSearchRequest
                {
                    OfferStatusId = (int)EOfferStatus.Finished,
                    RequestId     = request.RequestId
                };

                var finishedOffer = await _offerService.GetAll <List <Offer> >(offerRequest);

                var companyId = finishedOffer[0].UserId;
                var company   = await _authService.GetById(companyId);

                var requestRow = new RequestReport
                {
                    Client      = $"{client.FirstName} {client.LastName}",
                    AddressFrom = clientAddress.City,
                    AddressTo   = requestAddress.City,
                    Company     = company.Company,
                    Date        = request.Date,
                    Price       = $"{request.Price} $"
                };

                sourceList.Add(requestRow);
            }

            RequestReportBindingSource.DataSource = sourceList;

            this.rvRequests.RefreshReport();
        }
Ejemplo n.º 9
0
        public SensorService(
            TimeSpan refreshInterval,
            IReadOnlyCollection <int> sensorIds,
            ISensorDataProvider sensorDataProvider,
            RequestReport requestReport,
            CancellationToken cancelRefreshSensorsToken)
        {
            var cache = new SensorDataCache(sensorIds);

            _refreshDataModule = new RefreshDataModule(
                refreshInterval,
                sensorDataProvider,
                cache,
                cancelRefreshSensorsToken
                );

            this.Cache  = cache;
            this.Report = requestReport;
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            List <int> sensorIds = Enumerable
                                   .Range(0, Configuration.SensorCount)
                                   .ToList();

            var sensorDataProvider = new RandomSensorDataProvider(
                sensorIds: sensorIds,
                maxExpectedSensorCallbackInterval: Configuration.MaxExpectedSensorCallbackInterval
                );

            var report = new RequestReport();

            using var cancelRefreshSensorsTokenSource = new CancellationTokenSource();
            var sensorService = new SensorService(
                refreshInterval: Configuration.RefreshInterval,
                sensorIds: sensorIds,
                sensorDataProvider: sensorDataProvider,
                requestReport: report,
                cancelRefreshSensorsToken: cancelRefreshSensorsTokenSource.Token
                );

            Task.Delay(Configuration.RefreshInterval).Wait();
            Console.WriteLine("Initialized.");

            for (int requestCount = Configuration.MinRequests; requestCount <= Configuration.MaxRequests; requestCount = Configuration.GetNextStepRequests(requestCount))
            {
                DemoUtils.SendTestRequests(
                    sensorIds: sensorIds,
                    sensorService: sensorService,
                    requestCount: requestCount,
                    repeatCount: Configuration.StepRepeatCount,
                    maxStepLength: Configuration.StepLength,
                    report: report
                    );
            }

            cancelRefreshSensorsTokenSource.Cancel();

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 11
0
        /***************************************************************************************/
        public List <RequestReport> GetRequestsByDepartment(string deptId)
        {
            List <RequestReport> requestReports = new List <RequestReport>();
            SqlDataReader        reader         = null;

            try
            {
                string sql = "Select YEAR(r.DateTime) as DateTime,i.CategoryID,SUM(ir.ActualQty) as ActualQty " +
                             "from Request r,ItemRequest ir, Item as i " +
                             "where r.ID = ir.RequestID and ir.ItemID = i.ID " +
                             "and r.EmployeeID in(select e.ID from Employee as e where e.DeptID=@deptId) " +
                             "group by YEAR(r.DateTime),i.CategoryID,ir.ItemID";

                SqlCommand cmd = new SqlCommand(sql, connection);
                cmd.Parameters.AddWithValue("@deptId", deptId);
                connection.Open();
                reader = cmd.ExecuteReader();
                while (reader != null && reader.Read())
                {
                    RequestReport req = new RequestReport()
                    {
                        ReqYear    = (int)reader["DateTime"],
                        CategoryID = (int)reader["CategoryID"],
                        Qty        = (int)reader["ActualQty"]
                    };
                    requestReports.Add(req);
                }
            }
            catch (Exception e)
            {
                return(null);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                connection.Close();
            }
            return(requestReports);
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> _RequestReport(RequestReport model)
        {
            DateTime startDateTime = model.DateFrom;
            DateTime endDateTime   = model.DateTo.AddDays(1).AddTicks(-1);

            var requests = await _context.Requests.Include(a => a.Vessel)
                           .Where(a => a.DateCreated >= startDateTime && a.DateCreated <= endDateTime).ToListAsync();

            RequestViewModel m = new RequestViewModel();

            m.Requests = new List <Request>(requests);
            m.DateFrom = model.DateFrom;
            m.DateTo   = model.DateTo;

            return(new ViewAsPdf("_RequestReport", m)
            {
                PageOrientation = Orientation.Landscape,
                FileName = "REQUEST_REP_" + DateTime.Now + ".pdf"
            });
        }
Ejemplo n.º 13
0
        private void saveReportRequest(int[] employeesIds, string[] departmentsList
                                       , DateTime fromDate, DateTime toDate, string reportType)
        {
            try
            {
                string filterText = string.Join(',', employeesIds);
                if (departmentsList.Count() > 0)
                {
                    filterText += filterText.Length > 0 ? "," : "";
                    filterText += string.Join(",", departmentsList);
                }

                if (User.Identity.IsAuthenticated)
                {
                    using (var context = new PrincipalContext(ContextType.Domain))
                    {
                        UserPrincipal principal     = UserPrincipal.FindByIdentity(context, User.Identity.Name);
                        string        userName      = principal.Name;
                        var           requestReport = new RequestReport()
                        {
                            ByUserId    = User.Identity.Name,
                            ByUserName  = userName,
                            FilterText  = filterText.Length > 0 ? filterText : "All",
                            FromDate    = fromDate,
                            ToDate      = toDate,
                            ReportType  = reportType,
                            RequestDate = DateTime.Now
                        };

                        _requestsReportsManager.InsertNew(requestReport);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        public async Task <IActionResult> PdfDetailReport([FromBody] RequestReport viewModel)
        {
            var responseModel = new ResponseApi();

            if (!ModelState.IsValid)
            {
                responseModel.IsSuccess = false;
                responseModel.Message   = "Request Invalid";
                return(BadRequest(responseModel));
            }

            var listElementosCables = new ResponseElementoCables();
            //var controller = "";
            var prefix   = "";
            var URL_BASE = "";

            //controller = "odata/datatakedev/";
            //prefix = string.Format("{0}", "odata/datatakedev/Viewfromcablesms?$top=100&$skip=30000&$count=true");
            prefix = string.Format("{0}", viewModel.Url);
            var route = RouteService.GetInstance();

            URL_BASE = route.RouteBaseAddress;

            var response = await ApiService.GetList <ResponseElementoCables>(URL_BASE, prefix);

            if (!response.IsSuccess)
            {
                return(Ok(response));
            }

            var cables         = (ResponseElementoCables)response.Result;
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 6
                },
                DocumentTitle = "Formato General Inventario"
            };


            var templatePdfGeneral = new TemplatePdfDetallado();
            //var template= await templatePdfAutorizacion.GetHTMLString(requestPma,_hostingEnvironment.WebRootPath);

            var objectSettings = new ObjectSettings
            {
                PagesCount = true,
                // Page= "http://interedes.co/",
                HtmlContent = await templatePdfGeneral.GetElementosHTMLString(cables, _hostingEnvironment.WebRootPath, _mapper),
                WebSettings =
                {
                    DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "bootstrap.css")
                },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = false, Spacing = 1 },
                //FooterSettings = { FontName = "Arial", FontSize = 9, Line = false, HtmUrl =Path.Combine(Directory.GetCurrentDirectory(), "assets", "footer/footer.html"), Left = ""  }
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = false, Center = "" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "Formato_Inventario_Detallado.pdf"));
            ///return Ok(response);
        }
Ejemplo n.º 15
0
 public void Update(RequestReport requestReport)
 {
     _requestReportRepository.Update(requestReport);
 }
Ejemplo n.º 16
0
 public RequestReport Add(RequestReport requestReport)
 {
     return(_requestReportRepository.Add(requestReport));
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Check if given request ended with a success
 /// </summary>
 public static bool IsSuccess(this RequestReport report)
 {
     return((report == null) ||
            (report.StatusCode < 300));
 }
Ejemplo n.º 18
0
        /// <summary>
        /// List the usages from the cache for given customer
        ///
        /// Note that this call is lightning-fast and built for massive requesting : it uses an internal cache to avoid calling the API too often
        /// The caching increase the resilience of your integration : in case of a temporary communication problem, an error is returned, but the last known usages will be returned too by this method
        /// </summary>
        /// <param name="usages">The customer usages</param>
        /// <param name="referenceCustomer">(mandatory) the customer reference</param>
        /// <param name="forceReloading">(optional) true to force reloading of the cache</param>
        public virtual RequestReport FastListUsages(out List <Usage> usages, object referenceCustomer, bool forceReloading)
        {
            RequestReport result = null;

            usages = null;

            // if input is valid
            if (referenceCustomer != null)
            {
                // get cached usages for that customer
                CacheUsageByCustomer cache;
                if (!this._UsagesByCustomer.TryGetValue(referenceCustomer, out cache))
                {
                    // lock to prevent multi-threading side-effects
                    lock (this._UsagesByCustomer)
                    {
                        // get cached usages for that customer
                        // yes, we HAVE to do it again at this point (double check pattern)
                        if (!this._UsagesByCustomer.TryGetValue(referenceCustomer, out cache))
                        {
                            // if still not found, create a cache
                            cache = new CacheUsageByCustomer
                            {
                                // set it as expired to have an immediate loading
                                DateCache = DateTime.MinValue,
                                Usages    = new List <Usage>()
                            };
                            // and store it
                            this._UsagesByCustomer.Add(referenceCustomer, cache);
                        }
                    }
                }

                // if we have a cache at this point (and we should)
                if (cache != null)
                {
                    // if reloading is forced
                    if (forceReloading)
                    {
                        // set the date as expired to force a reload
                        cache.DateCache = DateTime.MinValue;
                    }

                    // get current date
                    var now = DateTime.UtcNow;
                    // compute validity date
                    var dateValidity = now.AddMinutes(-CountMinutesCacheExpiration);
                    // if expired
                    if (cache.DateCache < dateValidity)
                    {
                        // lock it
                        lock (cache)
                        {
                            // if still expired
                            // yes, we HAVE to do it again at this point (double check pattern)
                            if (cache.DateCache < dateValidity)
                            {
                                // list customer's usages
                                ListPaginated <Usage> allUsages;
                                result = this.ListUsages(out allUsages, null, null, null, referenceCustomer, null, DoCacheAggregationByDefault, null, 1000);
                                // if any
                                if (allUsages != null)
                                {
                                    // store them
                                    cache.Usages = allUsages.Items;
                                }
                                // if no usages but we had NO error
                                else if (result == null)
                                {
                                    // then clear the cached usages : the customer has no usages anymore
                                    cache.Usages.Clear();
                                }

                                // if an error occured, do not clear the cached usages
                                // as the problem might be a temporary communication problem between the plateforms
                                // and we don't want the user be impacted

                                // finally, update the cache date
                                cache.DateCache = now;
                            }
                        }
                    }

                    // finally, get the usages in the cache
                    usages = cache.Usages;
                }
            }
            // if we miss a mandatory parameter
            else
            {
                // return an error
                result = new RequestReport
                {
                    Code    = "Api.Client.FastListUsages.MissingParameter",
                    Message = "Missing parameter - FastListUsages requires a ReferenceCustomer"
                }
            };

            return(result);
        }