public void ShouldGetClientOperations() { // Arrange int testClientId = 2; int number = 4; reportsService = new ReportsService( operationTableRepository: this.operationTableRepository, sharesNumberTableRepository: this.sharesNumberTableRepository, balanceTableRepository: this.balanceTableRepository, shareTableRepository: this.shareTableRepository, clientTableRepository: this.clientTableRepository); // Act List <OperationEntity> operationsOfClient = new List <OperationEntity>(); operationsOfClient.AddRange(reportsService.GetOperationByClient(testClientId, number)); // Assert this.operationTableRepository.Received(1).GetByClient(testClientId, number); for (int i = 0; i < number; i++) { if (operationsOfClient[i].Customer.Id != testClientId) { throw new ArgumentException("Wrong Id in result item"); } } }
protected void Page_Load(object sender, EventArgs e) { presenter = new CustomerWatchPresenter(this, ReportsService.Create(), ReportManagerFactory.Create(this.CurrentScope(), Context.User as CffPrincipal)); ICffClient xClient = (SessionWrapper.Instance.Get != null) ? SessionWrapper.Instance.Get.ClientFromQueryString : (!string.IsNullOrEmpty(QueryString.ViewIDValue)) ? SessionWrapper.Instance.GetSession(QueryString.ViewIDValue).ClientFromQueryString : null; if (xClient != null) { targetName = ": " + xClient.Name; } ICffCustomer xCustomer = (SessionWrapper.Instance.Get != null) ? SessionWrapper.Instance.Get.CustomerFromQueryString : (!string.IsNullOrEmpty(QueryString.ViewIDValue)) ? SessionWrapper.Instance.GetSession(QueryString.ViewIDValue).CustomerFromQueryString : null; if (xCustomer != null) { if (targetName != null || !targetName.Equals("")) { targetName += " / "; targetName = string.Concat(targetName, xCustomer.Name); } else { targetName = ": " + xCustomer.Name; } } if (!IsPostBack) { presenter.ConfigureView(this.CurrentScope()); presenter.ShowReport(this.CurrentScope(), true); } }
public IHttpActionResult Comment(string id, [FromBody]Comment comment) { Comment result; if (comment == null || string.IsNullOrWhiteSpace(comment._userId) || string.IsNullOrWhiteSpace(comment.content)) { throw new Exception("Information incompleted"); } using (var reportsService = new ReportsService()) { result = reportsService.Comment(id, comment); comment.date = DateTime.UtcNow; } //Perform push call string deviceId = ConfigurationManager.AppSettings.Get("GCMApi"); if (string.IsNullOrEmpty(deviceId)) { return InternalServerError(new Exception("No GCMApi configured")); } var data = new { registration_ids = new string[] { "001122334455" }, data = result }; string response = new PushServiceHelper().SendGCMNotification(deviceId, Newtonsoft.Json.JsonConvert.SerializeObject(data)); return Ok(result); }
/// <summary> /// Retrieves a list of activities for a specific customer and application. /// Documentation https://developers.google.com/reports/reports_v1/reference/activities/list /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Reports service.</param> /// <param name="userKey">Represents the profile id or the user email for which the data should be filtered. When 'all' is specified as the userKey, it returns usageReports for all users.</param> /// <param name="applicationName">Application name for which the events are to be retrieved.</param> /// <param name="optional">Optional paramaters.</param> /// <returns>ActivitiesResponse</returns> public static Activities List(ReportsService service, string userKey, string applicationName, ActivitiesListOptionalParms optional = null) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (userKey == null) { throw new ArgumentNullException(userKey); } if (applicationName == null) { throw new ArgumentNullException(applicationName); } // Building the initial request. var request = service.Activities.List(userKey, applicationName); // Applying optional parameters to the request. request = (ActivitiesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional); // Requesting data. return(request.Execute()); } catch (Exception ex) { throw new Exception("Request Activities.List failed.", ex); } }
public async Task GetReportsShouldGetOne() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()); var context = new ApplicationDbContext(options.Options); var guideRepository = new EfDeletableEntityRepository <Guide>(context); var guideService = new GuidesService(guideRepository); var guideModel = new CreateGuideInputModel() { Category = "Action", Description = "someDesc", GameId = "1", ImageUrl = "google", Title = "test", }; var guideId = await guideService.CreateAsync(guideModel, "1"); var repository = new EfRepository <Report>(context); var service = new ReportsService(repository); var model = new AddReportToGuideInputModel() { UserId = "1", GuideId = guideId, Reason = "tupooooo", }; await service.AddReportToGuideAsync(model); var actual = await service.GetByGuideAsync <ReportForGuideViewModel>(model.GuideId); Assert.Single(actual); }
public void GetAllRegisteredUsersCount() { IReportsService rs = new ReportsService(); Result <List <ReportModel> > result = rs.GetAllRegisteredUsersCount(); Console.WriteLine(result.message); }
public void ShouldGetSharesNumbersByShare() { // Arrange reportsService = new ReportsService( operationTableRepository: this.operationTableRepository, sharesNumberTableRepository: this.sharesNumberTableRepository, balanceTableRepository: this.balanceTableRepository, shareTableRepository: this.shareTableRepository, clientTableRepository: this.clientTableRepository); int testShareId = 3; // Act var sharesNumbersByShare = reportsService.GetSharesNumberByShare(testShareId); // Assert var testOperations = this.sharesNumberTableRepository.Received(1).GetByShare(testShareId); foreach (var sharesNumber in sharesNumbersByShare) { if (sharesNumber.Share.Id != testShareId) { throw new ArgumentException("Wrong Id in result item"); } } }
public void GetTopRatedCoursesOfAllTime() { IReportsService rs = new ReportsService(); Result <List <ReportModel> > result = rs.GetTopRatedCoursesOfAllTime(10); Console.WriteLine(result.message); }
public void TestingOrderEntryWhenCheckReportById() { //Arange var reportService = new ReportsService(db); var firstOrder = new Order { Id = "0", Name = "Fun0" }; var secondOrder = new Order { Id = "1", Name = "Fun1" }; this.db.Report.Add(new Report { Id = "0", ReportText = "FunTesting0", OrderId = firstOrder.Id, Order = firstOrder }); this.db.Report.Add(new Report { Id = "1", ReportText = "FunTesting1", OrderId = secondOrder.Id, Order = secondOrder }); this.db.SaveChanges(); //Act var asd = this.db.Report.First(); var result = reportService.ReportById("0"); //Assert var ReportTextExpected = "FunTesting0"; var OrderIdExpected = "0"; Assert.Equal(ReportTextExpected, result.ReportText); Assert.Equal(OrderIdExpected, result.OderId); }
public void WhenExecute_IncludingParameters_ShouldReturnNotNullResult() { var service = new ReportsService(); var request = new ReportsRequest() { IncludeParameters = true }; var response = service.OnGet(request) as ReportsResponse; Assert.NotNull(response); }
/// <summary> /// Retrieves a report which is a collection of properties / statistics for a specific customer. /// Documentation https://developers.google.com/reports/reports_v1/reference/customerUsageReports/get /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Reports service.</param> /// <param name="date">Represents the date in yyyy-mm-dd format for which the data is to be fetched.</param> /// <param name="optional">Optional paramaters.</param> /// <returns>UsageReportsResponse</returns> public static UsageReports Get(ReportsService service, string date, CustomerUsageReportsGetOptionalParms optional = null) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (date == null) { throw new ArgumentNullException(date); } // Building the initial request. var request = service.CustomerUsageReports.Get(date); // Applying optional parameters to the request. request = (CustomerUsageReportsResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional); // Requesting data. return(request.Execute()); } catch (Exception ex) { throw new Exception("Request CustomerUsageReports.Get failed.", ex); } }
public void ShouldGetZeroBalances() { // Arrange reportsService = new ReportsService( operationTableRepository: this.operationTableRepository, sharesNumberTableRepository: this.sharesNumberTableRepository, balanceTableRepository: this.balanceTableRepository, shareTableRepository: this.shareTableRepository, clientTableRepository: this.clientTableRepository); // Act var zeroBalances = reportsService.GetZeroBalances(); // Assert var zeroBalancesFromTable = this.balanceTableRepository.Received(1).GetZeroBalances(); foreach (var zeroBalance in zeroBalances) { if (zeroBalance.GetType().Name != "String") { throw new ArgumentException("Result item is not a string type"); } } //foreach (var zeroBalance in zeroBalancesFromTable) //{ // if (zeroBalance.Amount != 0) throw new ArgumentException("Amount in result item is not zero"); //} }
public CoinbaseProClient( IAuthenticator authenticator, IHttpClient httpClient, bool sandBox = false) { var clock = new Clock(); var httpRequestMessageService = new HttpRequestMessageService(authenticator, clock, sandBox); var createWebSocketFeed = (Func <IWebSocketFeed>)(() => new WebSocketFeed(sandBox)); var queryBuilder = new QueryBuilder(); AccountsService = new AccountsService(httpClient, httpRequestMessageService); CoinbaseAccountsService = new CoinbaseAccountsService(httpClient, httpRequestMessageService); OrdersService = new OrdersService(httpClient, httpRequestMessageService, queryBuilder); PaymentsService = new PaymentsService(httpClient, httpRequestMessageService); WithdrawalsService = new WithdrawalsService(httpClient, httpRequestMessageService); DepositsService = new DepositsService(httpClient, httpRequestMessageService); ProductsService = new ProductsService(httpClient, httpRequestMessageService, queryBuilder); CurrenciesService = new CurrenciesService(httpClient, httpRequestMessageService); FillsService = new FillsService(httpClient, httpRequestMessageService); FundingsService = new FundingsService(httpClient, httpRequestMessageService, queryBuilder); ReportsService = new ReportsService(httpClient, httpRequestMessageService); UserAccountService = new UserAccountService(httpClient, httpRequestMessageService); StablecoinConversionsService = new StablecoinConversionsService(httpClient, httpRequestMessageService); FeesService = new FeesService(httpClient, httpRequestMessageService); ProfilesService = new ProfilesService(httpClient, httpRequestMessageService); WebSocket = new WebSocket.WebSocket(createWebSocketFeed, authenticator, clock); Log.Information("CoinbaseProClient constructed"); }
public void ShouldGetFirstClients() { // Arrange reportsService = new ReportsService( operationTableRepository: this.operationTableRepository, sharesNumberTableRepository: this.sharesNumberTableRepository, balanceTableRepository: this.balanceTableRepository, shareTableRepository: this.shareTableRepository, clientTableRepository: this.clientTableRepository); // Act List <ClientEntity> clients = new List <ClientEntity>(); clients.AddRange(reportsService.GetFirstClients(5, 1)); // Assert this.clientTableRepository.Received(1).Take(5, 1); for (int i = 0; i < 5; i++) { if (clients[i].Id != i + 1) { throw new ArgumentException("Wrong id in list of clients."); } } }
public void GetAllSessionsBreakDown() { IReportsService rs = new ReportsService(); Result <List <ReportModel> > result = rs.GetAllSessionsBreakDown(); Console.WriteLine(result.message); }
public async Task GetAvilableYears() { ReportsService service = new ReportsService(timeRepo, reportMapper); var result = await service.GetAvilableYears(); result.ShouldNotBeEmpty(); }
public ClientsController(ClientsService clientsService, BalancesService balancesService, SalesService salesService, ReportsService reportsService) { this.clientsService = clientsService; this.balancesService = balancesService; this.salesService = salesService; this.reportsService = reportsService; }
public void GetReportsShouldReturnAllReports() { var reportRepo = new Mock <IRepository <Report> >(); reportRepo.Setup(r => r.All()).Returns(new List <Report> { new Report { Reporter = new User(), ReportedUser = new User(), }, new Report { Reporter = new User(), ReportedUser = new User(), }, new Report { Reporter = new User() { UserName = "******" }, ReportedUser = new User(), }, }.AsQueryable()); var service = new ReportsService(reportRepo.Object, null); var reports = service.GetReports(); Assert.Equal(3, reports.Count); reportRepo.Verify(r => r.All(), Times.Once); }
public async Task SubmitReportShouldThrowErrorForNonExistingUser() { var reportRepo = new Mock <IRepository <Report> >(); var usersRepo = new Mock <IRepository <User> >(); usersRepo.Setup(u => u.All()).Returns(new List <User> { new User { UserName = "******" }, new User { UserName = "******" }, }.AsQueryable()); var service = new ReportsService(reportRepo.Object, usersRepo.Object); var report = new Report { Reporter = new User(), ReportedUser = new User(), DateOfCreation = DateTime.Now.AddDays(3), Details = "1" }; await Assert.ThrowsAsync <NullReferenceException>(async() => await service.SubmitReport(report, "pesho")); reportRepo.Verify(r => r.AddAsync(report), Times.Never); }
private readonly Period[] implementedBySplitter = new Period[] { Period.Day }; //TODO remove when all splitters will be done public StatisticsController(IQueryBus queryBus, ICommandBus commandBus, MessagesServiceFactory messagesServiceFactory, ReportsService reportsService, ChartsService chartsService) { this._queryBus = queryBus; this._commandBus = commandBus; this._messagesServiceFactory = messagesServiceFactory; this._reportsService = reportsService; this._chartsService = chartsService; }
public async Task <IActionResult> DownloadExcel() { ReportsService rs = new ReportsService(); var pdf = rs.GetExcel(); string fileName = Guid.NewGuid() + ".xlsx"; pdf.Save(fileName, Aspose.Cells.SaveFormat.Xlsx); return(GetFile(fileName)); }
public async Task <IActionResult> DownloadPdf() { ReportsService rs = new ReportsService(); var pdf = rs.GetPDF(); string fileName = Guid.NewGuid() + ".pdf"; pdf.Save(fileName, Aspose.Pdf.SaveFormat.Pdf); return(GetPdfFile(fileName)); }
internal async Task Initilize() { try { UserDialogs.Instance.ShowLoading(); var result = await NewsServices.GetAllNews(); var list = new List <NewsModel>(); if (result.Success) { int i = 2; foreach (var item in result.data) { item.IssueDate = String.IsNullOrEmpty(item.IssueDate) ? "" : Convert.ToDateTime(item.IssueDate).ToString("dd MMM, yyyy"); //item.ImageURL = (ApiBase.HttpClientBase.BaseUrl + "NewsImages/" + item.ImageURL); //var response = await ReportsService.Download(ApiBase.HttpClientBase.BaseUrl + "NewsImages/" + item.ImageURL); var response = await ReportsService.DownloadFileBytes(ApiBase.HttpClientBase.BaseUrl + "api/News/GetNewsImage?newsimage=" + item.ImageURL); if (response.FileContents.Length > 1) { item.ImageData = ImageSource.FromStream(() => new MemoryStream(response.FileContents)); } item.IssueDate = "Published on " + item.IssueDate; if (item.IsApproved) { //Background color scheme - even odd. if ((i % 2) == 0) { item.BackgroundColor = "#6CAAD3"; } else { item.BackgroundColor = "#D3C1A0"; } i++; list.Add(item); } } NewsList = new ObservableCollection <NewsModel>(list); } else { await UserDialogs.Instance.AlertAsync(result.Message); } } catch (Exception ex) { UserDialogs.Instance.HideLoading(); } UserDialogs.Instance.HideLoading(); }
public ReportsTests() { ReportsSetUp setUp = new ReportsSetUp(); var reportsRepository = new Mock <IReportsRepository>(); reportsRepository.Setup(x => x.GetReports("")).Returns(Task.FromResult(setUp.reportResult)); _reportsService = new ReportsService(reportsRepository.Object); }
public IHttpActionResult Delete(string id) { bool succeed; using (var reportsService = new ReportsService()) { succeed = reportsService.Delete(id); } return Ok(succeed); }
public StockExchange(Container traidingRegistryContainer) { this.traidingRegistryContainer = traidingRegistryContainer; this.balancesService = traidingRegistryContainer.GetInstance <BalancesService>(); this.clientsService = traidingRegistryContainer.GetInstance <ClientsService>(); this.reportsService = traidingRegistryContainer.GetInstance <ReportsService>(); this.salesService = traidingRegistryContainer.GetInstance <SalesService>(); this.sharesService = traidingRegistryContainer.GetInstance <SharesService>(); this.shareTypesService = traidingRegistryContainer.GetInstance <ShareTypesService>(); }
public void Should_Get_Suspicious_Hotspots_List_With_No_Nulls() { //Arrange var reports = new ReportsService(); //Act var sut = reports.GetSuspiciousHotSpotsList(); //Assert sut.Should().NotContainNulls(); }
public ReportsTui(ReportsService service) { _service = service; Initialize("Reports TUI", new Dictionary <string, Action> { { "Student averages", ReportStudentAverages }, { "Punctual students", ReportPunctualStudents }, { "Most difficult task", ReportTheMostDifficultTask }, { "Students qualified for exam", ReportStudentsQualifiedForExam } }); }
static void Main(string[] args) { Parser.Default.ParseArguments <Options>(args).WithParsed(options => { using (ReportsService reportService = GetReportsService()) { var activities = GetMoveActivities(reportService, options.DriveId, options.MoveStart, options.MoveEnd, options.IpAddress); var moveInfoList = activities.Select(a => new MoveInfo(a)).ToList(); List <IGrouping <string, MoveInfo> > folderGroups = moveInfoList.GroupBy(mi => mi.OriginalFolderId).ToList(); using (DriveService driveService = GetDriveService()) { var totalMovedFiles = moveInfoList.Count; Console.WriteLine($"Found {totalMovedFiles} files that were moved to the drive root between {options.MoveStart} and {options.MoveEnd}{(options.IpAddress != null ? $" by {options.IpAddress}" : null)}."); Console.WriteLine($"Would you like to move them back to their original folders?{(options.IsDryRun ? " (DRY RUN - no files will actually be moved)" : null)} [y/n] "); if (Console.ReadKey(true).Key != ConsoleKey.Y) { return; } var filesMovedBack = 0; for (int i = 0; i < folderGroups.Count; i++) { var folderGroup = folderGroups[i]; Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: Folder '{folderGroup.First().OriginalFolderName}' ({folderGroup.Key}) used to contain {folderGroup.Count()} orphaned files. ({i + 1}/{folderGroups.Count})."); foreach (MoveInfo moveInfo in folderGroup) { filesMovedBack++; string percentageCompleted = (filesMovedBack / (double)totalMovedFiles * 100).ToString("0.0"); Console.Write($"{DateTime.Now.ToLongTimeString()}: ... Moving {moveInfo.FileName} ({moveInfo.FileId}) to folderId {moveInfo.OriginalFolderId}"); DriveFile file = GetFile(driveService, moveInfo.FileId); if (file.Parents.Count == 1 && file.Parents.Single() == options.DriveId) { if (!options.IsDryRun) { ReverseMove(driveService, file, moveInfo); } else { Console.Write($"[DRY RUN - NOT MOVED]"); } Console.WriteLine($" [Completed {percentageCompleted}%]"); } else { Console.WriteLine($" [SKIPPED - FILE NO LONGER IN ROOT! {percentageCompleted}%]"); } } } } } }); }
public OffensesController(GIBDDContext context, OffenseService offenseService, ReportsService reportsService, ILogger <OffensesController> logger ) { _logger = logger; _context = context; _offenseService = offenseService; _reportsService = reportsService; }
static void Main(string[] args) { try { UserCredential credential; // Load client secrets. using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { /* The file token.json stores the user's access and refresh tokens, and is created * automatically when the authorization flow completes for the first time. */ string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.FromStream(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Reports API service. var service = new ReportsService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = ApplicationName }); // Define parameters of request. ActivitiesResource.ListRequest request = service.Activities .List("all", ActivitiesResource.ListRequest.ApplicationNameEnum.Drive); request.MaxResults = 10; // List activities. IList <Activity> activities = request.Execute().Items; Console.WriteLine("Logins:"); if (activities == null || activities.Count == 0) { Console.WriteLine("No logins found."); return; } foreach (var activityItem in activities) { Console.WriteLine("{0}: {1} {2}", activityItem.Id.Time, activityItem.Actor.Email, activityItem.Events.First().Name); } } catch (FileNotFoundException e) { Console.WriteLine(e.Message); } }
public void AllUsersStatisticTestEmptyPayments() { DateTime startDate = new DateTime(2012, 11, 11); DateTime endDate = new DateTime(2016, 11, 11); int idUser3 = 3; ReportsService reports = new ReportsService(); var usersStatistic = reports.GetAllUsersPaymentStatistic(startDate, endDate); var userStatistic = usersStatistic.FirstOrDefault(t => t.Id == idUser3); Assert.IsNull(userStatistic); }
private void ServiceInstance(string accountId, string certPath) { var auth = new ServiceOAuth(accountId, certPath); DirectoryService = auth.DirectoryService(); GroupSettingsService = auth.GroupSettingsService(); LicensingService = auth.LicensingService(); ReportsService = auth.ReportsService(); CalendarService = auth.CalendarService(); DriveService = auth.DriveService(); AuditService = auth.AuditService(); TasksService = auth.TasksService(); }
private void GetTaskToDosing() { var taskQueueItems = TaskQueueItemsService.ListTaskQueueItems(); if (taskQueueItems.Any()) { var taskQueueItem = taskQueueItems.OrderBy(x => x.Order).First(); var task = TasksReader.GetById(taskQueueItem.Task.Id); var recipe = RecipesReader.GetById(task.Recipe.Id); var containers = CheckMaterials(recipe); if (containers != null) { var parameters = GetValues(task, recipe, containers); if (parameters != null) { var isOk = LoadValues(parameters); if (isOk) { var taskId = new Dictionary <ApiOpcParameter, string> { { CurrentTaskIdParameter, task.Id.ToString() } }; var taskIdLoadOk = LoadValues(taskId); if (taskIdLoadOk) { ReportsService.CreateReport(task); TaskQueueItemsService.Delete(taskQueueItem.Id); } else { Logger.Error("Ошибка записи CurrentTaskId."); } } else { Logger.Error("Ошибка записи параметров."); } } else { Logger.Error("Отсутствуют некоторые параметры."); } } else { Logger.Error("Отсутствуют некоторые материалы в контейнерах."); MessageBox.Show("Отсутствуют некоторые материалы в контейнерах"); } } else { Logger.Error("Отсутствуют задания в очереди."); } }
public LoadTaskHandler(TaskQueueItemsService taskQueueItemsService, Logger logger) { _opcName = NewOpcServer.OpcList.Rbu; TaskQueueItemsService = taskQueueItemsService; Logger = logger; ReportsService = new ReportsService(); TasksReader = new TasksReader(); ContainersReader = new ContainersReader(); BatchersReader = new BatchersReader(); RecipesReader = new RecipesReader(); CommonOpcParametersReader = new CommonOpcParametersReader(); CreateSubscribe(); }
public async Task GetById() { var reportsService = new ReportsService(); HttpResponseMessage result = client.GetAsync("lnf/reports").Result; Assert.IsTrue(result.IsSuccessStatusCode); var reportsString = await result.Content.ReadAsStringAsync(); var reports = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(reportsString, new[] { new { _id = "" } }); string reportId = reports[0]._id; var response = client.GetAsync("lnf/reports/" + reportId).Result; Assert.IsTrue(response.IsSuccessStatusCode); Assert.IsNotNull(response.Content); reportsString = await response.Content.ReadAsStringAsync(); var report = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(reportsString, new { _id = "" }); Assert.IsTrue(report != null); Assert.IsTrue(report._id == reportId); }
public IEnumerable<FbaManageInventory> GetDetailedFbaInventory() { var inventory = new List< FbaManageInventory >(); ActionPolicies.AmazonGetPolicy.Do( () => { var client = this._factory.CreateFeedsReportsClient(); var service = new ReportsService( client, this._credentials ); AmazonLogger.Log.Trace( "[amazon] Loading Detailed FBA inventory for seller {0}", this._credentials.SellerId ); inventory.AddRange( service.GetReport< FbaManageInventory >( ReportType.FbaManageInventoryArchived, DateTime.UtcNow.AddDays( -90 ).ToUniversalTime(), DateTime.UtcNow.ToUniversalTime() ) ); AmazonLogger.Log.Trace( "[amazon] Detailed FBA inventiry for seller {0} loaded", this._credentials.SellerId ); } ); return inventory; }
public void AllUsersStatisticTestLimitValuesAll() { DateTime startDate = new DateTime(2012, 11, 11); DateTime endDate = new DateTime(2016, 11, 11); int idUser1 = 1; int idUser2 = 2; ReportsService reports = new ReportsService(); var usersStatistic = reports.GetAllUsersPaymentStatistic(startDate, endDate); decimal user1pays = usersStatistic .FirstOrDefault(t => t.Id == idUser1) .Payments .Sum(t => t.PaySize); Assert.AreEqual(3000, user1pays); decimal user2pays = usersStatistic .FirstOrDefault(t => t.Id == idUser2) .Payments .Sum(t => t.PaySize); Assert.AreEqual(5000, user2pays); }
public IHttpActionResult Get(string id) { using (var reportsService = new ReportsService()) { var report = reportsService.GetById(id); if (report == null) throw new Exception("Report does not exist"); //Verifica que el usuario exista. De ahí toma el userName para armar en el objeto var user = new UsersService().GetById(report._userId); if (user == null) throw new Exception("User report does not exist"); report.userName = user.uname; return Ok(report); } }
public IHttpActionResult Get() { using (var reportsService = new ReportsService()) { var reports = reportsService.Get(null, -1, 0); return Ok(reports); } }
public void GetDogVaccinationStatisticTestShortPeriod() { ReportsService reports = new ReportsService(); DateTime startPeriod = new DateTime(2011, 10, 11); DateTime endPeriod = new DateTime(2011, 10, 12); int idDog = 1; var dogsStat = reports.GetDogVaccinationStatistic(startPeriod, endPeriod, idDog); Assert.IsNotNull(dogsStat); Assert.AreEqual(1, dogsStat.Vaccinations.Count()); }
public async Task _DeleteAll() { var reportsService = new ReportsService(); reportsService.DropCollection(); await _Generate(10); }
public IHttpActionResult SetViewed(string id, [FromBody]string userId) { long result; using (var reportsService = new ReportsService()) { result = reportsService.SetView(id, userId); } return Ok(result); }
public IHttpActionResult SetAlert(string id, [FromBody]UserAlert userAlert) { UserAlert result; using (var reportsService = new ReportsService()) { result = reportsService.SetAlert(id, userAlert); } return Ok(userAlert); }
public IHttpActionResult ReportsType(string type, int pageNumber) { using (var reportsService = new ReportsService()) { //TODO Parametrizar el pageSize var reports = reportsService.Get(type, pageNumber, 20); return Ok(reports); } }
public IHttpActionResult Put(Report value) { Report report; var response = Request.CreateResponse<Report>(HttpStatusCode.Created, value); using (var reportsService = new ReportsService()) { report = reportsService.GetById(value._id); if (report != null) { report = Mapper.Map(value, report); reportsService.Update(report); return Ok(report); } else { return BadRequest("Report could not be found"); } } }
public IHttpActionResult Post([FromBody] Report value) { if (value.detail == null) { return BadRequest("Report Detail not supplied"); } using (var reportsService = new ReportsService()) { value._id = null; reportsService.Save((Report)value); } return Ok((Report)value); }
public IHttpActionResult GetByUserId(string id, int pageNumber = 1) { IEnumerable<Report> reports; using (var reportsService = new ReportsService()) { reports = reportsService.GetByUserId(id, pageNumber); } return Ok(reports); }
public IHttpActionResult Get(int pageNumber) { IEnumerable<Report> reports = null; using (var reportsService = new ReportsService()) { //TODO parametrizar el pageSize reports = reportsService.Get(null, pageNumber, 20); } return Ok(reports); }
public void OneUserStatisticTestZeroValues() { DateTime startDate = new DateTime(1991, 10, 11); DateTime endDate = new DateTime(1995, 11, 11); int idUser = 1; ReportsService reports = new ReportsService(); var userStatistic = reports.GetUserPaymentStatistic(startDate, endDate, 1); decimal paymentSum = userStatistic .Payments .Sum(t => t.PaySize); Assert.AreEqual(0, paymentSum); }
public async Task<HttpResponseMessage> Post(string type, string id) { string imageId = null; string temPath = null; //Checks if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); //Checks if the type is valid PicType picType; if (!Enum.TryParse<PicType>(type, out picType)) throw new HttpResponseException(HttpStatusCode.InternalServerError); string path = HttpContext.Current.Server.MapPath("~/data/pics"); string tempPath = path + "\\temp"; try { using (var picturesService = new PicturesService()) { picturesService.EnsureDirectory(path + "\\temp"); var provider = new MultipartFormDataStreamProvider(tempPath); MultipartFileData fileData = null; // Read the form data and save in the path. await Request.Content.ReadAsMultipartAsync(provider); if (provider.FileData.Count <= 0) { throw new HttpResponseException(HttpStatusCode.NoContent); } fileData = provider.FileData.First(); if (!fileData.Headers.ContentType.Equals(MediaTypeHeaderValue.Parse("image/jpeg")) && !fileData.Headers.ContentType.Equals(MediaTypeHeaderValue.Parse("image/png")) && !fileData.Headers.ContentType.Equals(MediaTypeHeaderValue.Parse("image/gif"))) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //var fileContent = provider.GetStream(provider.Contents.First(), provider.Contents.First().Headers); temPath = fileData.LocalFileName; imageId = picturesService.Save(picType, id, fileData.LocalFileName, path); //Adds the image to the corresponding document switch (picType) { //TODO:Implementar el codigo para los demás tipos case PicType.reports: using (var reportsService = new ReportsService()) { var report = reportsService.GetById(id); if(string.IsNullOrEmpty(report.picture)){ report.picture = imageId; }else{ report.detail.pics.Add(imageId); } reportsService.Update(report); }; break; case PicType.users: break; } } } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } finally { //deletes the temp file if (temPath != null && File.Exists(temPath)) { using (var picturesService = new PicturesService()) { picturesService.DeleteFile(temPath); } } } if (!string.IsNullOrEmpty(imageId)) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); imageId = Newtonsoft.Json.JsonConvert.SerializeObject(new { id = imageId }); result.Content = new ObjectContent(imageId.GetType(), imageId, GlobalConfiguration.Configuration.Formatters.JsonFormatter); return result; //return Request.CreateResponse(HttpStatusCode.OK); } else { return Request.CreateResponse(HttpStatusCode.InternalServerError); } }
public void GetAllDogsVaccinationStatisticTest() { ReportsService reports = new ReportsService(); DateTime startPeriod = new DateTime(2011, 10, 11); DateTime endPeriod = new DateTime(2014, 10, 11); int idDog1 = 1; int idDog2 = 2; var dogsStat = reports.GetAllDogVaccinationsStatistic(startPeriod, endPeriod).ToList(); Assert.AreEqual(2, dogsStat.Count); var firstDogVaccinations = dogsStat.FirstOrDefault(t => t.IdDog == idDog1); Assert.AreEqual(2, firstDogVaccinations.Vaccinations.Count()); var secondDogVaccinations = dogsStat.FirstOrDefault(t => t.IdDog == idDog2); Assert.AreEqual(1, secondDogVaccinations.Vaccinations.Count()); }