System.TimeSpan.FromDays(double)

Here are the examples of the csharp api System.TimeSpan.FromDays(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1480 Examples 7

19 Source : ApiTokenCacheService.cs
with MIT License
from bradwellsb

private void AddToCache(string key, AccessTokenItem accessTokenItem)
        {
            var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(cacheExpirationInDays));

            lock (_lock)
            {
                _cache.SetString(key, JsonSerializer.Serialize(accessTokenItem), options);
            }
        }

19 Source : Startup.cs
with MIT License
from bradymholt

public void ConfigureServices(IServiceCollection services)
        {
            services.AddEnreplacedyFrameworkNpgsql().AddDbContext<DefaultDbContext>(options =>
            {
                options.UseNpgsql(Configuration.GetConnectionString("defaultConnection"));
                options.UseOpenIddict();
            });

            // Configure Enreplacedy Framework Initializer for seeding
            services.AddTransient<IDefaultDbContextInitializer, DefaultDbContextInitializer>();

            // Configure Enreplacedy Framework Idenreplacedy for Auth
            services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>(o =>
            {
                // Do not 302 redirect when Unauthorized; just return 401 status code (ref: http://stackoverflow.com/a/38801130/626911)
                o.Cookies.ApplicationCookie.AutomaticChallenge = false;
            })
            .AddEnreplacedyFrameworkStores<DefaultDbContext>()
            .AddDefaultTokenProviders();

            // Configure Idenreplacedy to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure<IdenreplacedyOptions>(options =>
            {
                options.ClaimsIdenreplacedy.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdenreplacedy.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdenreplacedy.RoleClaimType = OpenIdConnectConstants.Claims.Role;
                options.SignIn.RequireConfirmedEmail = true;
            });

            // Configure OpenIddict for JSON Web Token (JWT) generation (Ref: http://capesean.co.za/blog/asp-net-5-jwt-tokens/)
            // Register the OpenIddict services.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict enreplacedies.
            services.AddOpenIddict(options =>
            {
                // Register the Enreplacedy Framework stores.
                options.AddEnreplacedyFrameworkCoreStores<DefaultDbContext>();

                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.AddMvcBinders();

                // Enable the token endpoint (required to use the preplacedword flow).
                options.EnableTokenEndpoint("/api/auth/login");

                // Allow client applications to use the grant_type=preplacedword flow.
                options.AllowPreplacedwordFlow();

                // During development, you can disable the HTTPS requirement.
                options.DisableHttpsRequirement();

                options.AllowRefreshTokenFlow();
                options.UseJsonWebTokens();
                options.AddEphemeralSigningKey();
                options.SetAccessTokenLifetime(TimeSpan.FromDays(1));
            });

            services.AddTransient<IEmailSender, EmailSender>();
            services.Configure<EmailSenderOptions>(Configuration.GetSection("email"));

            // Add framework services
            services.AddMvc().AddJsonOptions(options =>
               {
                   options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
               });
        }

19 Source : Connection.cs
with MIT License
from BrammyS

public async Task ConnectAsync()
        {
            // Start the connection to discord
            await _client.LoginAsync(TokenType.Bot, ConfigData.Data.Token).ConfigureAwait(false);
            await _client.StartAsync().ConfigureAwait(false);

            // Initialize all the client logging
            _clientLogHandler.Initialize();

            // Load all the custom prefixes
            await _prefixService.LoadAllPrefixes().ConfigureAwait(false);

            await _commandHandler.InitializeAsync().ConfigureAwait(false);

            // Wait the thread so the console application doesn't close.
            await Task.Delay(TimeSpan.FromDays(ConfigData.Data.RestartTime)).ConfigureAwait(false);
            await _client.StopAsync().ConfigureAwait(false);
            await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
        }

19 Source : FullNodeTrustedBroadcastService.cs
with MIT License
from BreezeHub

public void Broadcast(int cycleStart, TransactionType transactionType, CorrelationId correlation, TrustedBroadcastRequest broadcast)
        {
            if (broadcast == null)
                throw new ArgumentNullException(nameof(broadcast));
            if (broadcast.Key != null && !broadcast.Transaction.Inputs.Any(i => i.PrevOut.IsNull))
                throw new InvalidOperationException("One of the input should be null");

            var address = broadcast.PreviousScriptPubKey?.GetDestinationAddress(TumblingState.TumblerNetwork);
            if (address != null && TrackPreviousScriptPubKey)
                TumblingState.WatchOnlyWalletManager.WatchAddress(address.ToString());

            var height = TumblingState.Chain.Height;
            var record = new Record();
            //3 days expiration after now or broadcast date
            var expirationBase = Math.Max(height, broadcast.BroadcastableHeight);
            record.Expiration = expirationBase + (int)(TimeSpan.FromDays(3).Ticks / TumblingState.TumblerNetwork.Consensus.PowTargetSpacing.Ticks);

            record.Request = broadcast;
            record.TransactionType = transactionType;
            record.Cycle = cycleStart;
            record.Correlation = correlation;
            Logs.Broadcasters.LogInformation($"Planning to broadcast {record.TransactionType} of cycle {record.Cycle} on block {record.Request.BroadcastableHeight}");
            AddBroadcast(record);
        }

19 Source : FullNodeBroadcastService.cs
with MIT License
from BreezeHub

public Task<bool> BroadcastAsync(Transaction transaction)
        {
            var record = new Record
            {
                Transaction = transaction
            };
            var height = TumblingState.Chain.Height;
            //3 days expiration
            record.Expiration = height + (int)(TimeSpan.FromDays(3).Ticks / Network.Main.Consensus.PowTargetSpacing.Ticks);
            Repository.UpdateOrInsert<Record>("Broadcasts", transaction.GetHash().ToString(), record, (o, n) => o);
            return TryBroadcastCoreAsync(record, height);
        }

19 Source : RPCTrustedBroadcastRequest.cs
with MIT License
from BreezeHub

public void Broadcast(int cycleStart, TransactionType transactionType, CorrelationId correlation, TrustedBroadcastRequest broadcast)
		{
			if(broadcast == null)
				throw new ArgumentNullException(nameof(broadcast));
			if(broadcast.Key != null && !broadcast.Transaction.Inputs.Any(i => i.PrevOut.IsNull))
				throw new InvalidOperationException("One of the input should be null");

			var address = broadcast.PreviousScriptPubKey?.GetDestinationAddress(RPCClient.Network);
			if(address != null && TrackPreviousScriptPubKey)
				RPCClient.ImportAddress(address, "", false);

			var height = _Cache.BlockCount;
			var record = new Record();
			//3 days expiration after now or broadcast date
			var expirationBase = Math.Max(height, broadcast.BroadcastableHeight);
			record.Expiration = expirationBase + (int)(TimeSpan.FromDays(3).Ticks / RPCClient.Network.Consensus.PowTargetSpacing.Ticks);

			record.Request = broadcast;
			record.TransactionType = transactionType;
			record.Cycle = cycleStart;
			record.Correlation = correlation;
			Logs.Broadcasters.LogInformation($"Planning to broadcast {record.TransactionType} of cycle {record.Cycle} on block {record.Request.BroadcastableHeight}");
			AddBroadcast(record);
		}

19 Source : RPCBroadcastService.cs
with MIT License
from BreezeHub

public Task<bool> BroadcastAsync(Transaction transaction)
		{
			var record = new Record();
			record.Transaction = transaction;
			var height = _Cache.BlockCount;
			//3 days expiration
			record.Expiration = height + (int)(TimeSpan.FromDays(3).Ticks / Network.Main.Consensus.PowTargetSpacing.Ticks);
			Repository.UpdateOrInsert<Record>("Broadcasts", transaction.GetHash().ToString(), record, (o, n) => o);
			return TryBroadcastCoreAsync(record, height);
		}

19 Source : StockList.cs
with MIT License
from brianlagunas

public void Generate(DateTime start, DateTime end, TimeSpan? interval = null,
            double? price = null, double? volume = null,
            bool includeWeekends = false)
        {
            this.Clear();

            if (interval == null)
                interval = TimeSpan.FromDays(1);

            this.TimeInterval = interval.Value;

            var priceStart = 200.0;
            if (price != null)
                priceStart = price.Value; ;

            var priceRange = 10.0;
            var volumeStart = 10000.0;
            if (volume != null)
                volumeStart = volume.Value; ;

            var date = start;

            var v = volumeStart;
            var o = priceStart;
            var h = o + (rand.NextDouble() * 10);
            var l = o - (rand.NextDouble() * 10);
            var c = l + (rand.NextDouble() * (h - l));

            var values = new List<StockItem>();
            while (date.Ticks < end.Ticks)
            {
                if (includeWeekends && values.Count > 0 &&
                   (date.DayOfWeek == DayOfWeek.Sunday ||
                    date.DayOfWeek == DayOfWeek.Saturday))
                {
                    var previous = values[values.Count - 1];
                    var stock = previous.Clone();
                    stock.Time = date;

                    values.Add(stock);
                }
                else
                {
                    var stock = new StockItem();
                    stock.Time = date;
                    stock.Open = o;
                    stock.High = h;
                    stock.Low = l;
                    stock.Close = c;
                    stock.Volume = v;

                    values.Add(stock);

                    o = c + ((rand.NextDouble() - 0.5) * priceRange);
                    h = o + (rand.NextDouble() * 1.001 * priceRange);
                    l = o - (rand.NextDouble() * priceRange);
                    c = l + (rand.NextDouble() * (h - l));
                    v = v + ((rand.NextDouble() - 0.5) * 300);
                }
                date = date.Add(interval.Value);
            }

            this.AddRange(values);
        }

19 Source : GitHubApiRepositoriesService.cs
with MIT License
from brminnick

public async IAsyncEnumerable<MobileReferringSiteModel> GetMobileReferringSites(IEnumerable<ReferringSiteModel> referringSites, string repositoryUrl, [EnumeratorCancellation] CancellationToken cancellationToken)
		{
			var favIconTaskList = referringSites.Select(x => setFavIcon(_referringSitesDatabase, x, repositoryUrl, cancellationToken)).ToList();

			while (favIconTaskList.Any())
			{
				var completedFavIconTask = await Task.WhenAny(favIconTaskList).ConfigureAwait(false);
				favIconTaskList.Remove(completedFavIconTask);

				var mobileReferringSiteModel = await completedFavIconTask.ConfigureAwait(false);
				yield return mobileReferringSiteModel;
			}

			async Task<MobileReferringSiteModel> setFavIcon(ReferringSitesDatabase referringSitesDatabase, ReferringSiteModel referringSiteModel, string repositoryUrl, CancellationToken cancellationToken)
			{
				var mobileReferringSiteFromDatabase = await referringSitesDatabase.GetReferringSite(repositoryUrl, referringSiteModel.ReferrerUri).ConfigureAwait(false);

				if (mobileReferringSiteFromDatabase != null && isFavIconValid(mobileReferringSiteFromDatabase))
					return mobileReferringSiteFromDatabase;

				if (referringSiteModel.ReferrerUri != null && referringSiteModel.IsReferrerUriValid)
				{
					var favIcon = await _favIconService.GetFavIconImageSource(referringSiteModel.ReferrerUri, cancellationToken).ConfigureAwait(false);
					return new MobileReferringSiteModel(referringSiteModel, favIcon);
				}
				else
				{
					return new MobileReferringSiteModel(referringSiteModel, FavIconService.DefaultFavIcon);
				}

				static bool isFavIconValid(MobileReferringSiteModel mobileReferringSiteModel) => !string.IsNullOrWhiteSpace(mobileReferringSiteModel.FavIconImageUrl) && mobileReferringSiteModel.DownloadedAt.CompareTo(DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(30))) > 0;
			}
		}

19 Source : GitHubApiV3Service.cs
with MIT License
from brminnick

public async Task<RepositoryClonesResponseModel> GetRepositoryCloneStatistics(string owner, string repo, CancellationToken cancellationToken)
		{
			if (_gitHubUserService.IsDemoUser)
			{
				//Yield off of the main thread to generate dailyViewsModelList
				await Task.Yield();

				var dailyViewsModelList = new List<DailyClonesModel>();

				for (int i = 0; i < 14; i++)
				{
					var count = DemoDataConstants.GetRandomNumber() / 2; //Ensures the average clone count is smaller than the average view count
					var uniqeCount = count / 2; //Ensures uniqueCount is always less than count

					dailyViewsModelList.Add(new DailyClonesModel(DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(i)), count, uniqeCount));
				}

				return new RepositoryClonesResponseModel(dailyViewsModelList.Sum(x => x.TotalClones), dailyViewsModelList.Sum(x => x.TotalUniqueClones), dailyViewsModelList, repo, owner);
			}
			else
			{
				var token = await _gitHubUserService.GetGitHubToken().ConfigureAwait(false);
				var response = await AttemptAndRetry_Mobile(() => _githubApiClient.GetRepositoryCloneStatistics(owner, repo, GetGitHubBearerTokenHeader(token)), cancellationToken).ConfigureAwait(false);

				return new RepositoryClonesResponseModel(response.TotalCount, response.TotalUniqueCount, response.DailyClonesList, repo, owner);
			}
		}

19 Source : ReviewService.cs
with MIT License
from brminnick

bool ShouldDisplayReviewRequest()
		{
			return ReviewRequests >= MinimumReviewRequests
					&& MostRecentReviewedBuildString != _appInfo.BuildString
					&& DateTime.Compare(AppInstallDate.Add(TimeSpan.FromDays(MinimumAppInstallDays)), DateTime.UtcNow) < 1
					&& DateTime.Compare(MostRecentRequestDate.Add(TimeSpan.FromDays(MinimumMostRecentRequestDays)), DateTime.UtcNow) < 1;
		}

19 Source : StarsChart.cs
with MIT License
from brminnick

async Task ZoomStarsChart(IReadOnlyList<DailyStarsModel> dailyStarsList)
			{
				if (dailyStarsList.Any())
				{
					var mostRecentDailyStarsModel = dailyStarsList[^1];

					var maximumDaysDateTime = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(_maximumDays));

					//Zoom to Maximum Stars
					if (dailyStarsList.Count >= _maximumStarCount)
					{
						var maximumStarsDailyStarsModel = dailyStarsList[^_maximumStarCount];

						await SetZoom(maximumStarsDailyStarsModel.LocalDay.ToOADate(),
										mostRecentDailyStarsModel.LocalDay.ToOADate(),
										maximumStarsDailyStarsModel.TotalStars,
										mostRecentDailyStarsModel.TotalStars);
					}
					//Zoom to Maximum Days when Minimum Star Count has been met
					else if (dailyStarsList[0].Day <= maximumDaysDateTime)
					{
						var nearestDailyStarsModel = getNearestDailyStarsModelToTimeStamp(dailyStarsList, maximumDaysDateTime);

						if (mostRecentDailyStarsModel.TotalStars - nearestDailyStarsModel.TotalStars > _minimumStarCount)
						{

							await SetZoom(maximumDaysDateTime.LocalDateTime.ToOADate(),
											mostRecentDailyStarsModel.LocalDay.ToOADate(),
											nearestDailyStarsModel.TotalStars,
											mostRecentDailyStarsModel.TotalStars);
						}
					}
				}

				//https://stackoverflow.com/a/1757221/5953643
				static DailyStarsModel getNearestDailyStarsModelToTimeStamp(in IReadOnlyList<DailyStarsModel> dailyStarsList, DateTimeOffset timeStamp)
				{
					var starsListOrderedByProximityToTimeStamp = dailyStarsList.OrderBy(t => Math.Abs((t.Day - timeStamp).Ticks));

					foreach (var dailyStarsModel in starsListOrderedByProximityToTimeStamp)
					{
						//Get the nearest DailyStarsModel before timeStamp
						if (dailyStarsModel.Day < timeStamp)
							return dailyStarsModel;
					}

					return starsListOrderedByProximityToTimeStamp.First();
				}
			}

19 Source : Repository.cs
with MIT License
from brminnick

static IReadOnlyList<DailyClonesModel> AddMissingDates(in IEnumerable<DailyClonesModel> dailyClones)
		{
			var dailyClonesList = new List<DailyClonesModel>(dailyClones);

			var day = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(13));
			var maximumDay = DateTimeOffset.UtcNow;

			var daysList = dailyClones.Select(x => x.Day.Day).ToList();

			while (day.Day != maximumDay.AddDays(1).Day)
			{
				if (!daysList.Contains(day.Day))
					dailyClonesList.Add(new DailyClonesModel(RemoveHourMinuteSecond(day), 0, 0));

				day = day.AddDays(1);
			}

			return dailyClonesList;
		}

19 Source : DateTimeService.cs
with MIT License
from brminnick

public static DateTimeOffset GetMinimumDateTimeOffset<T>(in IEnumerable<T>? dailyList) where T : BaseDailyModel =>
			dailyList?.Any() is true ? dailyList.Min(x => x.Day) : DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(13));

19 Source : RepositoryDatabase.cs
with MIT License
from brminnick

static bool IsWithin14Days(DateTimeOffset dataDate, DateTimeOffset mostRecentDate) => dataDate.CompareTo(mostRecentDate.Subtract(TimeSpan.FromDays(13)).ToLocalTime()) >= 0;

19 Source : GitHubApiV3Service.cs
with MIT License
from brminnick

public async Task<RepositoryViewsResponseModel> GetRepositoryViewStatistics(string owner, string repo, CancellationToken cancellationToken)
		{
			if (_gitHubUserService.IsDemoUser)
			{
				//Yield off of the main thread to generate dailyViewsModelList
				await Task.Yield();

				var dailyViewsModelList = new List<DailyViewsModel>();

				for (int i = 0; i < 14; i++)
				{
					var count = DemoDataConstants.GetRandomNumber();
					var uniqeCount = count / 2; //Ensures uniqueCount is always less than count

					//Ensures one Demo repo is Trending
					if (i is 13 && new Random().Next(0, DemoDataConstants.RepoCount) is DemoDataConstants.RepoCount - 1 or DemoDataConstants.RepoCount - 2)
						dailyViewsModelList.Add(new DailyViewsModel(DateTimeOffset.UtcNow, DemoDataConstants.MaximumRandomNumber * 4, DemoDataConstants.MaximumRandomNumber / 2));
					else
						dailyViewsModelList.Add(new DailyViewsModel(DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(i)), count, uniqeCount));
				}

				return new RepositoryViewsResponseModel(dailyViewsModelList.Sum(x => x.TotalViews), dailyViewsModelList.Sum(x => x.TotalUniqueViews), dailyViewsModelList, repo, owner);
			}

19 Source : Repository.cs
with MIT License
from brminnick

static IReadOnlyList<DailyViewsModel> AddMissingDates(in IEnumerable<DailyViewsModel> dailyViews)
		{
			var dailyViewsList = new List<DailyViewsModel>(dailyViews);

			var day = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(13));
			var maximumDay = DateTimeOffset.UtcNow;

			var daysList = dailyViews.Select(x => x.Day.Day).ToList();

			while (day.Day != maximumDay.AddDays(1).Day)
			{
				if (!daysList.Contains(day.Day))
					dailyViewsList.Add(new DailyViewsModel(RemoveHourMinuteSecond(day), 0, 0));

				day = day.AddDays(1);
			}

			return dailyViewsList;
		}

19 Source : BaseTest.cs
with MIT License
from brminnick

protected static Repository CreateRepository(bool createViewsAndClones = true)
		{
			const string gitTrendsAvatarUrl = "https://avatars3.githubusercontent.com/u/61480020?s=400&u=b1a900b5fa1ede22af9d2d9bfd6c49a072e659ba&v=4";
			var downloadedAt = DateTimeOffset.UtcNow;

			var dailyViewsList = new List<DailyViewsModel>();
			var dailyClonesList = new List<DailyClonesModel>();

			for (int i = 0; i < 14 && createViewsAndClones; i++)
			{
				var count = DemoDataConstants.GetRandomNumber();
				var uniqeCount = count / 2; //Ensures uniqueCount is always less than count

				dailyViewsList.Add(new DailyViewsModel(downloadedAt.Subtract(TimeSpan.FromDays(i)), count, uniqeCount));
				dailyClonesList.Add(new DailyClonesModel(downloadedAt.Subtract(TimeSpan.FromDays(i)), count, uniqeCount));
			}

			return new Repository($"Repository " + DemoDataConstants.GetRandomText(), DemoDataConstants.GetRandomText(), DemoDataConstants.GetRandomNumber(),
														DemoUserConstants.Alias, gitTrendsAvatarUrl,
														DemoDataConstants.GetRandomNumber(), DemoDataConstants.GetRandomNumber(),
														gitTrendsAvatarUrl, false, downloadedAt, RepositoryPermission.ADMIN, false, dailyViewsList, dailyClonesList, DemoDataConstants.GenerateStarredAtDates(DemoDataConstants.GetRandomNumber()));
		}

19 Source : BackgroundFetchServiceTests.cs
with MIT License
from brminnick

static Repository CreateRepository(DateTimeOffset downloadedAt, string repositoryUrl)
		{
			var starredAtList = new List<DateTimeOffset>();
			var dailyViewsList = new List<DailyViewsModel>();
			var dailyClonesList = new List<DailyClonesModel>();

			for (int i = 0; i < 14; i++)
			{
				var count = DemoDataConstants.GetRandomNumber();
				var uniqeCount = count / 2; //Ensures uniqueCount is always less than count

				starredAtList.Add(DemoDataConstants.GetRandomDate());
				dailyViewsList.Add(new DailyViewsModel(downloadedAt.Subtract(TimeSpan.FromDays(i)), count, uniqeCount));
				dailyClonesList.Add(new DailyClonesModel(downloadedAt.Subtract(TimeSpan.FromDays(i)), count, uniqeCount));
			}

			return new Repository($"Repository " + DemoDataConstants.GetRandomText(), DemoDataConstants.GetRandomText(), DemoDataConstants.GetRandomNumber(),
														DemoUserConstants.Alias, GitHubConstants.GitTrendsAvatarUrl, DemoDataConstants.GetRandomNumber(), DemoDataConstants.GetRandomNumber(),
														repositoryUrl, false, downloadedAt, RepositoryPermission.ADMIN, true, dailyViewsList, dailyClonesList, starredAtList);
		}

19 Source : ReviewServiceTests.cs
with MIT License
from brminnick

[Test]
		public async Task TryRequestReviewPromptTest_Valid()
		{
			//Arrange
			bool didReviewRequestedFire_ReviewService = false;
			bool didReviewRequestedFire_StoreReview = false;

			var reviewRequestedTCS_ReviewService = new TaskCompletionSource<object?>();
			var reviewRequestedTCS_StoreReview = new TaskCompletionSource<bool>();

			MockStoreReview.ReviewRequested += HandleReviewRequested_StoreReview;
			ReviewService.ReviewRequested += HandleReviewRequested_ReviewService;

			var reviewService = ServiceCollection.ServiceProvider.GetRequiredService<ReviewService>();

			var preferences = ServiceCollection.ServiceProvider.GetRequiredService<IPreferences>();
			preferences.Set("AppInstallDate", DateTime.UtcNow.Subtract(TimeSpan.FromDays(ReviewService.MinimumAppInstallDays)));

			//Act
			for (int i = 0; i < ReviewService.MinimumReviewRequests; i++)
			{
				await reviewService.TryRequestReviewPrompt().ConfigureAwait(false);
				replacedert.IsFalse(didReviewRequestedFire_ReviewService);
			}

			await reviewService.TryRequestReviewPrompt().ConfigureAwait(false);
			await reviewRequestedTCS_ReviewService.Task.ConfigureAwait(false);
			var storeReviewResult = await reviewRequestedTCS_StoreReview.Task.ConfigureAwait(false);

			//replacedert
			replacedert.IsTrue(didReviewRequestedFire_ReviewService);
			replacedert.IsTrue(didReviewRequestedFire_StoreReview);
			replacedert.IsTrue(storeReviewResult);
			replacedert.AreNotEqual(preferences.Get("MostRecentRequestDate", default(DateTime)), default);
			replacedert.AreNotEqual(preferences.Get("MostRecentReviewedBuildString", default(string)), default);

			void HandleReviewRequested_ReviewService(object? sender, EventArgs e)
			{
				ReviewService.ReviewRequested -= HandleReviewRequested_ReviewService;

				didReviewRequestedFire_ReviewService = true;
				reviewRequestedTCS_ReviewService.SetResult(null);
			}

			void HandleReviewRequested_StoreReview(object? sender, bool e)
			{
				MockStoreReview.ReviewRequested -= HandleReviewRequested_StoreReview;

				didReviewRequestedFire_StoreReview = true;
				reviewRequestedTCS_StoreReview.SetResult(e);
			}
		}

19 Source : TrendsViewModelTests.cs
with MIT License
from brminnick

[TestCase(true)]
		[TestCase(false)]
		public async Task FetchDataCommandTest_AuthenticatedUser(bool shouldIncludeViewsClonesData)
		{
			//Arrange
			Repository repository;

			double dailyViewsClonesMinValue_Initial, dailyViewsClonesMinValue_Final;
			double dailyViewsClonesMaxValue_Initial, dailyViewsClonesMaxValue_Final;

			double minDailyStarsValue_Initial, minDailyStarsValue_Final;
			double maxDailyStarsValue_Initial, maxDailyStarsValue_Final;

			string viewsClonesEmptyDataViewreplacedleText_Initial, viewsClonesEmptyDataViewreplacedleText_Final;
			string starsEmptyDataViewreplacedleText_Initial, starsEmptyDataViewreplacedleText_Final;

			bool isViewsClonesChartVisible_Initial, isViewsClonesChartVisible_DuringFetchDataCommand, isViewsClonesChartVisible_Final;
			bool isStarsChartVisible_Initial, isStarsChartVisible_DuringFetchDataCommand, isStarsChartVisible_Final;

			bool isFetchingData_Initial, isFetchingData_DuringFetchDataCommand, isFetchingData_Final;

			bool isViewsClonesEmptyDataViewVisible_Initial, isViewsClonesEmptyDataViewVisible_DuringFetchDataCommand, isViewsClonesEmptyDataViewVisible_Final;
			bool isStarsEmptyDataViewVisible_Initial, isStarsEmptyDataViewVisible_DuringFetchDataCommand, isStarsEmptyDataViewVisible_Final;

			DateTime minViewsClonesDate_Initial, minViewsClonesDate_Final;
			DateTime maxViewsClonesDate_Initial, maxViewsClonesDate_Final;

			DateTime minDailyStarsDate_Initial, minDailyStarsDate_Final;
			DateTime maxDailyStarsDate_Initial, maxDailyStarsDate_Final;

			IReadOnlyList<DailyStarsModel> dailyStarsList_Initial, dailyStarsList_Final;
			IReadOnlyList<DailyViewsModel> dailyViewsList_Initial, dailyViewsList_Final;
			IReadOnlyList<DailyClonesModel> dailyClonesList_Initial, dailyClonesList_Final;

			var trendsViewModel = ServiceCollection.ServiceProvider.GetRequiredService<TrendsViewModel>();

			var gitHubUserService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubUserService>();
			var gitHubGraphQLApiService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubGraphQLApiService>();
			var gitHubApiRepositoriesService = ServiceCollection.ServiceProvider.GetRequiredService<GitHubApiRepositoriesService>();


			await AuthenticateUser(gitHubUserService, gitHubGraphQLApiService).ConfigureAwait(false);

			repository = await gitHubGraphQLApiService.GetRepository(GitHubConstants.GitTrendsRepoOwner, GitHubConstants.GitTrendsRepoName, CancellationToken.None);

			if (shouldIncludeViewsClonesData)
			{
				await foreach (var completedReposiory in gitHubApiRepositoriesService.UpdateRepositoriesWithViewsClonesAndStarsData(new[] { repository }, CancellationToken.None).ConfigureAwait(false))
				{
					repository = completedReposiory;
				}
			}

			//Act
			isFetchingData_Initial = trendsViewModel.IsFetchingData;
			dailyStarsList_Initial = trendsViewModel.DailyStarsList;
			dailyViewsList_Initial = trendsViewModel.DailyViewsList;
			dailyClonesList_Initial = trendsViewModel.DailyClonesList;
			maxDailyStarsDate_Initial = trendsViewModel.MaxDailyStarsDate;
			minDailyStarsDate_Initial = trendsViewModel.MinDailyStarsDate;
			minDailyStarsValue_Initial = trendsViewModel.MinDailyStarsValue;
			maxDailyStarsValue_Initial = trendsViewModel.MaxDailyStarsValue;
			minViewsClonesDate_Initial = trendsViewModel.MinViewsClonesDate;
			maxViewsClonesDate_Initial = trendsViewModel.MaxViewsClonesDate;
			isStarsChartVisible_Initial = trendsViewModel.IsStarsChartVisible;
			dailyViewsClonesMinValue_Initial = trendsViewModel.DailyViewsClonesMinValue;
			dailyViewsClonesMaxValue_Initial = trendsViewModel.DailyViewsClonesMaxValue;
			isViewsClonesChartVisible_Initial = trendsViewModel.IsViewsClonesChartVisible;
			starsEmptyDataViewreplacedleText_Initial = trendsViewModel.StarsEmptyDataViewreplacedleText;
			isStarsEmptyDataViewVisible_Initial = trendsViewModel.IsStarsEmptyDataViewVisible;
			viewsClonesEmptyDataViewreplacedleText_Initial = trendsViewModel.ViewsClonesEmptyDataViewreplacedleText;
			isViewsClonesEmptyDataViewVisible_Initial = trendsViewModel.IsViewsClonesEmptyDataViewVisible;

			var fetchDataCommandTask = trendsViewModel.FetchDataCommand.ExecuteAsync((repository, CancellationToken.None));

			isFetchingData_DuringFetchDataCommand = trendsViewModel.IsFetchingData;
			isStarsChartVisible_DuringFetchDataCommand = trendsViewModel.IsStarsChartVisible;
			isViewsClonesChartVisible_DuringFetchDataCommand = trendsViewModel.IsViewsClonesChartVisible;
			isStarsEmptyDataViewVisible_DuringFetchDataCommand = trendsViewModel.IsStarsEmptyDataViewVisible;
			isViewsClonesEmptyDataViewVisible_DuringFetchDataCommand = trendsViewModel.IsViewsClonesEmptyDataViewVisible;

			await fetchDataCommandTask.ConfigureAwait(false);

			isFetchingData_Final = trendsViewModel.IsFetchingData;
			dailyStarsList_Final = trendsViewModel.DailyStarsList;
			dailyViewsList_Final = trendsViewModel.DailyViewsList;
			dailyClonesList_Final = trendsViewModel.DailyClonesList;
			maxDailyStarsDate_Final = trendsViewModel.MaxDailyStarsDate;
			minDailyStarsDate_Final = trendsViewModel.MinDailyStarsDate;
			minDailyStarsValue_Final = trendsViewModel.MinDailyStarsValue;
			maxDailyStarsValue_Final = trendsViewModel.MaxDailyStarsValue;
			isStarsChartVisible_Final = trendsViewModel.IsStarsChartVisible;
			minViewsClonesDate_Final = trendsViewModel.MinViewsClonesDate;
			maxViewsClonesDate_Final = trendsViewModel.MaxViewsClonesDate;
			dailyViewsClonesMinValue_Final = trendsViewModel.DailyViewsClonesMinValue;
			dailyViewsClonesMaxValue_Final = trendsViewModel.DailyViewsClonesMaxValue;
			isViewsClonesChartVisible_Final = trendsViewModel.IsViewsClonesChartVisible;
			starsEmptyDataViewreplacedleText_Final = trendsViewModel.StarsEmptyDataViewreplacedleText;
			isStarsEmptyDataViewVisible_Final = trendsViewModel.IsStarsEmptyDataViewVisible;
			viewsClonesEmptyDataViewreplacedleText_Final = trendsViewModel.ViewsClonesEmptyDataViewreplacedleText;
			isViewsClonesEmptyDataViewVisible_Final = trendsViewModel.IsViewsClonesEmptyDataViewVisible;

			//replacedert
			replacedert.IsEmpty(dailyViewsList_Initial);
			replacedert.IsEmpty(dailyClonesList_Initial);
			replacedert.IsEmpty(dailyStarsList_Initial);

			replacedert.IsNotEmpty(dailyViewsList_Final);
			replacedert.IsNotEmpty(dailyClonesList_Final);
			replacedert.IsNotEmpty(dailyStarsList_Final);

			replacedert.IsTrue(isFetchingData_Initial);
			replacedert.IsTrue(isFetchingData_DuringFetchDataCommand);
			replacedert.IsFalse(isFetchingData_Final);

			replacedert.IsFalse(isViewsClonesEmptyDataViewVisible_Initial);
			replacedert.IsFalse(isViewsClonesEmptyDataViewVisible_DuringFetchDataCommand);
			replacedert.IsFalse(isViewsClonesEmptyDataViewVisible_Final);

			replacedert.IsFalse(isStarsEmptyDataViewVisible_Initial);
			replacedert.IsFalse(isStarsEmptyDataViewVisible_DuringFetchDataCommand);
			replacedert.IsFalse(isStarsEmptyDataViewVisible_Final);

			replacedert.IsFalse(isViewsClonesChartVisible_Initial);
			replacedert.IsFalse(isViewsClonesChartVisible_DuringFetchDataCommand);
			replacedert.True(isViewsClonesChartVisible_Final);

			replacedert.IsFalse(isStarsChartVisible_Initial);
			replacedert.IsFalse(isStarsChartVisible_DuringFetchDataCommand);
			replacedert.True(isStarsChartVisible_Final);

			replacedert.AreEqual(TrendsViewModel.MinimumChartHeight, dailyViewsClonesMaxValue_Initial);
			replacedert.GreaterOrEqual(dailyViewsClonesMaxValue_Final, dailyViewsClonesMaxValue_Initial);

			replacedert.AreEqual(TrendsViewModel.MinimumChartHeight, maxDailyStarsValue_Initial);
			replacedert.GreaterOrEqual(maxDailyStarsValue_Final, maxDailyStarsValue_Initial);

			replacedert.AreEqual(0, dailyViewsClonesMinValue_Initial);
			replacedert.AreEqual(dailyViewsClonesMinValue_Final, dailyViewsClonesMinValue_Initial);

			replacedert.AreEqual(0, minDailyStarsValue_Initial);
			replacedert.AreEqual(minDailyStarsValue_Final, minDailyStarsValue_Initial);

			replacedert.AreEqual(DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(13)).Date, minViewsClonesDate_Initial.Date);
			replacedert.LessOrEqual(minViewsClonesDate_Final.Date, minViewsClonesDate_Initial.Date);

			replacedert.AreEqual(DateTimeOffset.UtcNow.Date, maxViewsClonesDate_Initial.Date);
			replacedert.LessOrEqual(maxViewsClonesDate_Final.Date, maxViewsClonesDate_Initial.Date);

			replacedert.LessOrEqual(minDailyStarsDate_Final.Date, minDailyStarsDate_Initial.Date);
			replacedert.LessOrEqual(maxDailyStarsDate_Final.Date, maxDailyStarsDate_Initial.Date);

			replacedert.AreEqual(EmptyDataViewService.GetViewsClonesreplacedleText(RefreshState.Uninitialized), viewsClonesEmptyDataViewreplacedleText_Initial);
			replacedert.AreEqual(EmptyDataViewService.GetViewsClonesreplacedleText(RefreshState.Succeeded), viewsClonesEmptyDataViewreplacedleText_Final);

			replacedert.AreEqual(EmptyDataViewService.GetStarsreplacedleText(RefreshState.Uninitialized, trendsViewModel.TotalStars), starsEmptyDataViewreplacedleText_Initial);
			replacedert.AreEqual(EmptyDataViewService.GetStarsreplacedleText(RefreshState.Succeeded, trendsViewModel.TotalStars), starsEmptyDataViewreplacedleText_Final);
		}

19 Source : GithubUserService.cs
with MIT License
from brunohbrito

public async Task<UserStats> GetUserStats(string username)
        {
            var stats = _memoryCache.Get<UserStats>(username);
            if (stats != null)
                return stats;

            stats = await GetStatsFromGithub(username);

            _memoryCache.Set(username, stats, TimeSpan.FromDays(1));

            return stats;
        }

19 Source : SvgService.cs
with MIT License
from brunohbrito

private async Task<CardStyles> GetStyle(string theme)
        {
            if (!File.Exists(ThemeFile))
                return new CardStyles();

            var styles = _cacheService.Get<IEnumerable<CardStyles>>(CacheKeys.StyleKey);
            if (styles != null)
                return styles.Theme(theme) with { }; // Prevent changes at Memory version of CardStyle

            var jsonContent = await File.ReadAllTextAsync(ThemeFile);
            styles = JsonSerializer.Deserialize<IEnumerable<CardStyles>>(jsonContent);

            _cacheService.Set(CacheKeys.StyleKey, styles, TimeSpan.FromDays(30));

            return styles.Theme(theme) with { };
        }

19 Source : SvgService.cs
with MIT License
from brunohbrito

private async Task<CardTranslations> GetTranslations(string language)
        {
            if (!File.Exists(TranslationFile))
                return new CardTranslations();

            var translations = _cacheService.Get<IEnumerable<CardTranslations>>(CacheKeys.TranslationKey);
            if (translations != null)
                return translations.Language(language);

            var jsonContent = await File.ReadAllTextAsync(TranslationFile);
            translations = JsonSerializer.Deserialize<IEnumerable<CardTranslations>>(jsonContent);

            _cacheService.Set(CacheKeys.TranslationKey, translations, TimeSpan.FromDays(30));

            return translations.Language(language);
        }

19 Source : SvgService.cs
with MIT License
from brunohbrito

private async Task<string> GetSvgFile(string file)
        {
            var svgContent = _cacheService.Get<string>(CacheKeys.SvgKey(file));
            if (!string.IsNullOrEmpty(svgContent))
                return svgContent;

            svgContent = await File.ReadAllTextAsync(Path.Combine(SvgFolder, file));

            _cacheService.Set(CacheKeys.SvgKey(file), svgContent, TimeSpan.FromDays(30));

            return svgContent;
        }

19 Source : NewVersionCheckerHostedService.cs
with MIT License
from btcpayserver

protected async Task LoopVersionCheck()
        {
            try
            {
                await ProcessVersionCheck();
            }
            catch (Exception ex)
            {
                Logs.Events.LogError(ex, "Error while performing new version check");
            }
            await Task.Delay(TimeSpan.FromDays(1), Cancellation);
        }

19 Source : InvoiceController.API.cs
with MIT License
from btcpayserver

[HttpGet]
        [Route("invoices")]
        public async Task<IActionResult> GetInvoices(
            string token,
            DateTimeOffset? dateStart = null,
            DateTimeOffset? dateEnd = null,
            string orderId = null,
            string itemCode = null,
            string status = null,
            int? limit = null,
            int? offset = null)
        {
            if (User.Idenreplacedy.AuthenticationType == Security.Bitpay.BitpayAuthenticationTypes.Anonymous)
                return Forbid(Security.Bitpay.BitpayAuthenticationTypes.Anonymous);
            if (dateEnd != null)
                dateEnd = dateEnd.Value + TimeSpan.FromDays(1); //Should include the end day

            var query = new InvoiceQuery()
            {
                Take = limit,
                Skip = offset,
                EndDate = dateEnd,
                StartDate = dateStart,
                OrderId = orderId == null ? null : new[] { orderId },
                ItemCode = itemCode == null ? null : new[] { itemCode },
                Status = status == null ? null : new[] { status },
                StoreId = new[] { this.HttpContext.GetStoreData().Id }
            };

            var enreplacedies = (await _InvoiceRepository.GetInvoices(query))
                            .Select((o) => o.EnreplacedyToDTO()).ToArray();

            return Json(DataWrapper.Create(enreplacedies));
        }

19 Source : RatesHostedService.cs
with MIT License
from btcpayserver

bool IsStillUsed(BackgroundFetcherRateProvider fetcher)
        {
            return fetcher.LastRequested is DateTimeOffset v &&
                   DateTimeOffset.UtcNow - v < TimeSpan.FromDays(1.0);
        }

19 Source : KrakenExchangeRateProvider.cs
with MIT License
from btcpayserver

private async Task<string[]> GetSymbolsAsync(CancellationToken cancellationToken)
        {
            if (_LastSymbolUpdate != null && DateTimeOffset.UtcNow - _LastSymbolUpdate.Value < TimeSpan.FromDays(0.5))
            {
                return _Symbols;
            }
            else
            {
                JToken json = await MakeJsonRequestAsync<JToken>("/0/public/replacedetPairs", cancellationToken: cancellationToken);
                var symbols = (from prop in json.Children<JProperty>() where !prop.Name.Contains(".d", StringComparison.OrdinalIgnoreCase) select prop.Name).ToArray();
                _Symbols = symbols;
                _LastSymbolUpdate = DateTimeOffset.UtcNow;
                return symbols;
            }
        }

19 Source : PaymentRequestTests.cs
with MIT License
from btcpayserver

[Fact(Timeout = 60 * 2 * 1000)]
        [Trait("Integration", "Integration")]
        public async Task CanPayPaymentRequestWhenPossible()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();
                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");

                var paymentRequestController = user.GetController<PaymentRequestController>();

                replacedert.IsType<NotFoundResult>(
                    await paymentRequestController.PayPaymentRequest(Guid.NewGuid().ToString()));


                var request = new UpdatePaymentRequestViewModel()
                {
                    replacedle = "original juice",
                    Currency = "BTC",
                    Amount = 1,
                    StoreId = user.StoreId,
                    Description = "description"
                };
                var response = replacedert
                    .IsType<RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result)
                    .RouteValues.First();

                var invoiceId = replacedert
                    .IsType<OkObjectResult>(
                        await paymentRequestController.PayPaymentRequest(response.Value.ToString(), false)).Value
                    .ToString();

                var actionResult = replacedert
                    .IsType<RedirectToActionResult>(
                        await paymentRequestController.PayPaymentRequest(response.Value.ToString()));

                replacedert.Equal("Checkout", actionResult.ActionName);
                replacedert.Equal("Invoice", actionResult.ControllerName);
                replacedert.Contains(actionResult.RouteValues,
                    pair => pair.Key == "Id" && pair.Value.ToString() == invoiceId);

                var invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);
                replacedert.Equal(1, invoice.Price);

                request = new UpdatePaymentRequestViewModel()
                {
                    replacedle = "original juice with expiry",
                    Currency = "BTC",
                    Amount = 1,
                    ExpiryDate = DateTime.Today.Subtract(TimeSpan.FromDays(2)),
                    StoreId = user.StoreId,
                    Description = "description"
                };

                response = replacedert
                    .IsType<RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result)
                    .RouteValues.First();

                replacedert
                    .IsType<BadRequestObjectResult>(
                        await paymentRequestController.PayPaymentRequest(response.Value.ToString(), false));
            }
        }

19 Source : CreateAssetTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Create replacedet: Can Create (Receipt Version)")]
        public async Task CanCreateAreplacedetWithReceipt()
        {
            await using var fxTreasury = await TestAccount.CreateAsync(_network);
            await using var fxRenew = await TestAccount.CreateAsync(_network);
            await using var client = _network.NewClient();
            var createParams = new CreatereplacedetParams
            {
                Name = Generator.Code(50),
                Symbol = Generator.UppercaseAlphaCode(20),
                Ceiling = (long)(Generator.Integer(10, 20) * 100000),
                Treasury = fxTreasury.Record.Address,
                Administrator = fxTreasury.PublicKey,
                GrantKycEndorsement = fxTreasury.PublicKey,
                SuspendEndorsement = fxTreasury.PublicKey,
                PauseEndorsement = fxTreasury.PublicKey,
                ConfiscateEndorsement = fxTreasury.PublicKey,
                SupplyEndorsement = fxTreasury.PublicKey,
                InitializeSuspended = false,
                Expiration = Generator.TruncatedFutureDate(2000, 3000),
                RenewAccount = fxRenew.Record.Address,
                RenewPeriod = TimeSpan.FromDays(90),
                Signatory = new Signatory(fxTreasury.PrivateKey, fxRenew.PrivateKey),
                Memo = Generator.Code(20)
            };
            var receipt = await client.CreateTokenAsync(createParams);
            replacedert.Equal(ResponseCode.Success, receipt.Status);

            var info = await client.GetTokenInfoAsync(receipt.Token);
            replacedert.Equal(receipt.Token, info.Token);
            replacedert.Equal(createParams.Symbol, info.Symbol);
            replacedert.Equal(createParams.Name, info.Name);
            replacedert.Equal(fxTreasury.Record.Address, info.Treasury);
            replacedert.Equal(0UL, info.Circulation);
            replacedert.Equal(0U, info.Decimals);
            replacedert.Equal(createParams.Administrator, info.Administrator);
            replacedert.Equal(createParams.GrantKycEndorsement, info.GrantKycEndorsement);
            replacedert.Equal(createParams.SuspendEndorsement, info.SuspendEndorsement);
            replacedert.Equal(createParams.PauseEndorsement, info.PauseEndorsement);
            replacedert.Equal(createParams.ConfiscateEndorsement, info.ConfiscateEndorsement);
            replacedert.Equal(createParams.SupplyEndorsement, info.SupplyEndorsement);
            replacedert.Equal(createParams.RoyaltiesEndorsement, info.RoyaltiesEndorsement);
            replacedert.Equal(TokenTradableStatus.Tradable, info.TradableStatus);
            replacedert.Equal(TokenTradableStatus.Tradable, info.PauseStatus);
            replacedert.Equal(TokenKycStatus.Revoked, info.KycStatus);
            replacedert.False(info.Deleted);
            replacedert.Equal(createParams.Memo, info.Memo);
        }

19 Source : UpdateTopicTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Update Topic: Update Renew Period to Invlid Raises Error")]
        public async Task CanUpdateRenewPeriod()
        {
            await using var fx = await TestTopic.CreateAsync(_network);

            var tex = await replacedert.ThrowsAsync<TransactionException>(async () =>
            {
                await fx.Client.UpdateTopicAsync(new UpdateTopicParams
                {
                    Topic = fx.Record.Topic,
                    Signatory = fx.AdminPrivateKey,
                    RenewPeriod = TimeSpan.FromDays(1)
                });
            });
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, tex.Status);
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, tex.Receipt.Status);
            replacedert.StartsWith("Unable to update Topic, status: AutorenewDurationNotInRange", tex.Message);
        }

19 Source : UpdateContractTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Contract Update: Can't update properties when Renewal Period is not 7890000 seconds.")]
        public async Task CanUpdateMultiplePropertiesInOneCallButNotRenewalPeriod()
        {
            await using var fx = await GreetingContract.CreateAsync(_network);
            var originalInfo = await fx.Client.GetContractInfoAsync(fx.ContractRecord.Contract);
            var (newPublicKey, newPrivateKey) = Generator.KeyPair();
            var newExpiration = Generator.TruncatedFutureDate(2400, 4800);
            var newEndorsement = new Endorsement(newPublicKey);
            var updatedSignatory = new Signatory(_network.Signatory, newPrivateKey);
            var newRenewPeriod = TimeSpan.FromDays(Generator.Integer(180, 365));
            var newMemo = Generator.Code(50);
            fx.Client.Configure(ctx => ctx.Signatory = updatedSignatory);
            var pex = await replacedert.ThrowsAsync<PrecheckException>(async () =>
            {
                var record = await fx.Client.UpdateContractWithRecordAsync(new UpdateContractParams
                {
                    Contract = fx.ContractRecord.Contract,
                    Expiration = newExpiration,
                    Administrator = newEndorsement,
                    RenewPeriod = newRenewPeriod,
                    Memo = newMemo
                });
            });
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, pex.Status);
            replacedert.StartsWith("Transaction Failed Pre-Check: AutorenewDurationNotInRange", pex.Message);

            var info = await fx.Client.GetContractInfoAsync(fx.ContractRecord.Contract);
            replacedert.NotNull(info);
            replacedert.Equal(fx.ContractRecord.Contract, info.Contract);
            replacedert.Equal(fx.ContractRecord.Contract, info.Address);
            replacedert.Equal(originalInfo.Expiration, info.Expiration);
            replacedert.Equal(originalInfo.Administrator, info.Administrator);
            replacedert.Equal(originalInfo.RenewPeriod, info.RenewPeriod);
            replacedert.Equal(originalInfo.Memo, info.Memo);
            replacedert.Equal((ulong)fx.ContractParams.InitialBalance, info.Balance);
        }

19 Source : UpdateContractTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Contract Update: Can't Update Renew Period other than 7890000 seconds.")]
        public async Task CanUpdateRenewPeriod()
        {
            await using var fx = await GreetingContract.CreateAsync(_network);
            var newRenewal = TimeSpan.FromDays(Generator.Integer(180, 365));
            var pex = await replacedert.ThrowsAsync<PrecheckException>(async () =>
            {
                var record = await fx.Client.UpdateContractWithRecordAsync(new UpdateContractParams
                {
                    Contract = fx.ContractRecord.Contract,
                    RenewPeriod = newRenewal,
                });
            });
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, pex.Status);
            replacedert.StartsWith("Transaction Failed Pre-Check: AutorenewDurationNotInRange", pex.Message);

            var info = await fx.Client.GetContractInfoAsync(fx.ContractRecord.Contract);
            replacedert.NotNull(info);
            replacedert.Equal(fx.ContractRecord.Contract, info.Contract);
            replacedert.Equal(fx.ContractRecord.Contract, info.Address);
            replacedert.Equal(fx.ContractParams.Administrator, info.Administrator);
            replacedert.Equal(fx.ContractParams.RenewPeriod, info.RenewPeriod);
            replacedert.Equal(fx.ContractParams.Memo, info.Memo);
            replacedert.Equal((ulong)fx.ContractParams.InitialBalance, info.Balance);
        }

19 Source : UpdateContractTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Contract Update: Updating negative duration raises error.")]
        public async Task UpdateWithNegativeDurationRaisesError()
        {
            await using var fx = await GreetingContract.CreateAsync(_network);
            var newMemo = Generator.Code(50);
            var tex = await replacedert.ThrowsAsync<PrecheckException>(async () =>
            {
                await fx.Client.UpdateContractWithRecordAsync(new UpdateContractParams
                {
                    Contract = fx.ContractRecord.Contract,
                    RenewPeriod = TimeSpan.FromDays(Generator.Integer(-90, -60))
                }); ;
            });
            replacedert.Equal(ResponseCode.InvalidRenewalPeriod, tex.Status);
            replacedert.StartsWith("Transaction Failed Pre-Check: InvalidRenewalPeriod", tex.Message);
        }

19 Source : CreateAccountTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Create Account: Can't Set Auto Renew Period other than 7890000 seconds")]
        public async Task CanSetAutoRenewPeriod()
        {
            var (publicKey, privateKey) = Generator.KeyPair();
            var expectedValue = TimeSpan.FromDays(Generator.Integer(20, 60));
            await using var client = _network.NewClient();
            var pex = await replacedert.ThrowsAsync<PrecheckException>(async () =>
            {
                var createResult = await client.CreateAccountAsync(new CreateAccountParams
                {
                    InitialBalance = 1,
                    Endorsement = publicKey,
                    AutoRenewPeriod = expectedValue
                });
            });
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, pex.Status);
            replacedert.StartsWith("Transaction Failed Pre-Check: AutorenewDurationNotInRange", pex.Message);
        }

19 Source : UpdateAccountTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Update Account: Can't Update Auto Renew Period to other than 7890000 seconds")]
        public async Task CanUpdateAutoRenewPeriod()
        {
            var (publicKey, privateKey) = Generator.KeyPair();
            var originalValue = TimeSpan.FromSeconds(7890000);
            await using var client = _network.NewClient();
            var createResult = await client.CreateAccountAsync(new CreateAccountParams
            {
                InitialBalance = 1,
                Endorsement = publicKey,
                AutoRenewPeriod = originalValue
            });
            replacedert.Equal(ResponseCode.Success, createResult.Status);

            var originalInfo = await client.GetAccountInfoAsync(createResult.Address);
            replacedert.Equal(originalValue, originalInfo.AutoRenewPeriod);

            var newValue = originalValue.Add(TimeSpan.FromDays(Generator.Integer(10, 20)));

            var pex = await replacedert.ThrowsAsync<PrecheckException>(async () =>
            {
                var updateResult = await client.UpdateAccountAsync(new UpdateAccountParams
                {
                    Address = createResult.Address,
                    Signatory = privateKey,
                    AutoRenewPeriod = newValue
                });
            });
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, pex.Status);
            replacedert.StartsWith("Transaction Failed Pre-Check: AutorenewDurationNotInRange", pex.Message);

            var updatedInfo = await client.GetAccountInfoAsync(createResult.Address);
            replacedert.Equal(originalValue, updatedInfo.AutoRenewPeriod);
        }

19 Source : TestAsset.cs
with Apache License 2.0
from bugbytesinc

public static async Task<Testreplacedet> CreateAsync(NetworkCredentials networkCredentials, Action<Testreplacedet> customize = null, params TestAccount[] replacedociate)
        {
            var maxSupply = (long)(Generator.Integer(10, 20) * 1000);
            var fx = new Testreplacedet
            {
                Network = networkCredentials
            };
            fx.Network.Output?.WriteLine("STARTING SETUP: Test replacedet Instance");
            (fx.AdminPublicKey, fx.AdminPrivateKey) = Generator.KeyPair();
            (fx.GrantPublicKey, fx.GrantPrivateKey) = Generator.KeyPair();
            (fx.SuspendPublicKey, fx.SuspendPrivateKey) = Generator.KeyPair();
            (fx.PausePublicKey, fx.PausePrivateKey) = Generator.KeyPair();
            (fx.ConfiscatePublicKey, fx.ConfiscatePrivateKey) = Generator.KeyPair();
            (fx.SupplyPublicKey, fx.SupplyPrivateKey) = Generator.KeyPair();
            (fx.RoyaltiesPublickKey, fx.RoyaltiesPrivateKey) = Generator.KeyPair();
            fx.Payer = networkCredentials.Payer;
            fx.Client = networkCredentials.NewClient();
            fx.TreasuryAccount = await TestAccount.CreateAsync(networkCredentials);
            fx.RenewAccount = await TestAccount.CreateAsync(networkCredentials);
            fx.Metadata = Enumerable.Range(1, Generator.Integer(3, 9)).Select(_ => Generator.SHA384Hash()).ToArray();
            fx.Params = new CreatereplacedetParams
            {
                Name = Generator.Code(50),
                Symbol = Generator.UppercaseAlphaCode(20),
                Treasury = fx.TreasuryAccount.Record.Address,
                Ceiling = maxSupply,
                Administrator = fx.AdminPublicKey,
                GrantKycEndorsement = fx.GrantPublicKey,
                SuspendEndorsement = fx.SuspendPublicKey,
                PauseEndorsement = fx.PausePublicKey,
                ConfiscateEndorsement = fx.ConfiscatePublicKey,
                SupplyEndorsement = fx.SupplyPublicKey,
                RoyaltiesEndorsement = fx.RoyaltiesPublickKey,
                InitializeSuspended = false,
                Expiration = Generator.TruncatedFutureDate(2000, 3000),
                RenewAccount = fx.RenewAccount.Record.Address,
                RenewPeriod = TimeSpan.FromDays(90),
                Signatory = new Signatory(fx.AdminPrivateKey, fx.RenewAccount.PrivateKey, fx.TreasuryAccount.PrivateKey),
                Memo = "Test replacedet: " + Generator.Code(20)
            };
            customize?.Invoke(fx);
            fx.Record = await fx.Client.RetryKnownNetworkIssues(async client =>
            {
                return await fx.Client.CreateTokenWithRecordAsync(fx.Params, ctx =>
                {
                    ctx.Memo = "Testreplacedet Setup: " + fx.Params.Symbol ?? "(null symbol)";
                });
            });
            replacedert.Equal(ResponseCode.Success, fx.Record.Status);
            await fx.replacedociateAccounts(replacedociate);
            if (fx.Metadata is not null && fx.Metadata.Length > 0)
            {
                fx.MintRecord = await fx.Client.MintreplacedetWithRecordAsync(fx.Record.Token, fx.Metadata, fx.SupplyPrivateKey);
            }
            networkCredentials.Output?.WriteLine("SETUP COMPLETED: Test replacedet Instance");
            return fx;
        }

19 Source : TestToken.cs
with Apache License 2.0
from bugbytesinc

public static async Task<TestToken> CreateAsync(NetworkCredentials networkCredentials, Action<TestToken> customize = null, params TestAccount[] replacedociate)
        {
            var wholeTokens = (ulong)(Generator.Integer(10, 20) * 100000);
            var decimals = (uint)Generator.Integer(2, 5);
            var circulation = wholeTokens * (ulong)Math.Pow(10, decimals);
            var maxSupply = (long)(circulation * Generator.Double(2.1, 2.8));
            var fx = new TestToken
            {
                Network = networkCredentials
            };
            fx.Network.Output?.WriteLine("STARTING SETUP: Test Token Instance");
            (fx.AdminPublicKey, fx.AdminPrivateKey) = Generator.KeyPair();
            (fx.GrantPublicKey, fx.GrantPrivateKey) = Generator.KeyPair();
            (fx.SuspendPublicKey, fx.SuspendPrivateKey) = Generator.KeyPair();
            (fx.PausePublicKey, fx.PausePrivateKey) = Generator.KeyPair();
            (fx.ConfiscatePublicKey, fx.ConfiscatePrivateKey) = Generator.KeyPair();
            (fx.SupplyPublicKey, fx.SupplyPrivateKey) = Generator.KeyPair();
            (fx.RoyaltiesPublicKey, fx.RoyaltiesPrivateKey) = Generator.KeyPair();
            fx.Payer = networkCredentials.Payer;
            fx.Client = networkCredentials.NewClient();
            fx.TreasuryAccount = await TestAccount.CreateAsync(networkCredentials);
            fx.RenewAccount = await TestAccount.CreateAsync(networkCredentials);
            fx.Params = new CreateTokenParams
            {
                Name = Generator.Code(50),
                Symbol = Generator.UppercaseAlphaCode(20),
                Circulation = circulation,
                Decimals = decimals,
                Ceiling = maxSupply,
                Treasury = fx.TreasuryAccount.Record.Address,
                Administrator = fx.AdminPublicKey,
                GrantKycEndorsement = fx.GrantPublicKey,
                SuspendEndorsement = fx.SuspendPublicKey,
                PauseEndorsement = fx.PausePublicKey,
                ConfiscateEndorsement = fx.ConfiscatePublicKey,
                SupplyEndorsement = fx.SupplyPublicKey,
                RoyaltyEndorsement = fx.RoyaltiesPublicKey,
                InitializeSuspended = false,
                Expiration = Generator.TruncatedFutureDate(2000, 3000),
                RenewAccount = fx.RenewAccount.Record.Address,
                RenewPeriod = TimeSpan.FromDays(90),
                Signatory = new Signatory(fx.AdminPrivateKey, fx.RenewAccount.PrivateKey, fx.TreasuryAccount.PrivateKey),
                Memo = "Test Token: " + Generator.Code(20)
            };
            customize?.Invoke(fx);
            fx.Record = await fx.Client.RetryKnownNetworkIssues(async client =>
            {
                return await fx.Client.CreateTokenWithRecordAsync(fx.Params, ctx =>
                {
                    ctx.Memo = "TestToken Setup: " + fx.Params.Symbol ?? "(null symbol)";
                });
            });
            replacedert.Equal(ResponseCode.Success, fx.Record.Status);
            await fx.replacedociateAccounts(replacedociate);
            networkCredentials.Output?.WriteLine("SETUP COMPLETED: Test Token Instance");
            return fx;
        }

19 Source : CreateTopicTests.cs
with Apache License 2.0
from bugbytesinc

[Fact(DisplayName = "Create Topic: Create Topic with no invalid renew period raises error.")]
        public async Task CanCreateATopicWithInvalidRenewPeriodRaisesError()
        {
            var tex = await replacedert.ThrowsAsync<TransactionException>(async () =>
            {
                await TestTopic.CreateAsync(_network, fx =>
                {
                    fx.Params.RenewPeriod = TimeSpan.FromDays(1);
                });
            });
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, tex.Status);
            replacedert.Equal(ResponseCode.AutorenewDurationNotInRange, tex.Receipt.Status);
            replacedert.StartsWith("Unable to create Consensus Topic, status: AutorenewDurationNotInRange", tex.Message);
        }

19 Source : BackendAdminAppHostModule.cs
with Apache License 2.0
from burningmyself

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();

            Configure<AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
            });

            context.Services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies", options =>
                {
                    options.Cookie.Expiration = TimeSpan.FromDays(365);
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                })
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.ClientId = configuration["AuthServer:ClientId"];
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];
                    options.RequireHttpsMetadata = false;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.Scope.Add("role");
                    options.Scope.Add("email");
                    options.Scope.Add("phone");
                    options.Scope.Add("BackendAdminAppGateway");
                    options.Scope.Add("IdenreplacedyService");
                    options.Scope.Add("AuditLogging");
                    options.ClaimActions.MapAbpClaimTypes();
                });

            context.Services.AddSwaggerGen(
                options =>
                {
                    options.SwaggerDoc("v1", new Info { replacedle = "Backend Admin Application API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                });

            context.Services.AddDistributedRedisCache(options =>
            {
                options.Configuration = configuration["Redis:Configuration"];
            });

            var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
            context.Services.AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "Ms-DataProtection-Keys");
        }

19 Source : ApiContextTest.cs
with MIT License
from bunq

[Fact]
        public void TestAutoApiContextReLoad()
        {
            var contextJson = JObject.Parse(apiContext.ToJson());
            var expiredTime = DateTime.Now.Subtract(TimeSpan.FromDays(20));
            contextJson.SelectToken(FIELD_FIELD_SESSION_CONTEXT)[FIELD_FIELD_EXPIRY_TIME] = expiredTime.ToString();

            var expiredApiContext = ApiContext.FromJson(contextJson.ToString());

            replacedert.NotEqual(apiContext, expiredApiContext);

            BunqContext.UpdateApiContext(expiredApiContext);

            replacedert.Equal(expiredApiContext, BunqContext.ApiContext);

            BunqContext.UserContext.RefreshUserContext();

            replacedert.True(BunqContext.ApiContext.IsSessionActive());
        }

19 Source : TimeSpanExtensions.cs
with Apache License 2.0
from busterwood

public static string ToHuman(this TimeSpan time)
        {
            if (time == TimeSpan.Zero)
                return "0 ms";
            if (time < TimeSpan.FromMilliseconds(1))
                return time.TotalMilliseconds.ToString("N1") + " ms";
            if (time < TimeSpan.FromSeconds(1))
                return time.TotalMilliseconds.ToString("N0") + " ms";
            if (time <= TimeSpan.FromSeconds(10))
                return time.TotalSeconds.ToString("N1") + " s";
            if (time < TimeSpan.FromHours(1))
                return time.TotalMinutes.ToString("N1") + " min";
            if (time < TimeSpan.FromDays(1))
                return time.TotalHours.ToString("N1") + " hours";
            if (time < TimeSpan.FromDays(365))
                return time.TotalDays.ToString("N1") + " days";

            return (time.TotalDays / 365.0d).ToString("N1") + " years";
        }

19 Source : BusinessLayer.cs
with GNU General Public License v3.0
from bykovme

public static void SetExpirationSettings(bool addExpiryFolder, int expPeriod) {
            ExpiringSoon = addExpiryFolder;
            DataAccessLayer.GetInstance().ExpiryDate = DateTime.Now + TimeSpan.FromDays(expPeriod);
        }

19 Source : Program.cs
with Apache License 2.0
from bytedreamer

private static async Task Main()
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json", true, true);
            var config = builder.Build();
            var osdpSection = config.GetSection("OSDP");
            string portName = osdpSection["PortName"];
            int baudRate = int.Parse(osdpSection["BaudRate"]);
            byte deviceAddress = byte.Parse(osdpSection["DeviceAddress"]);
            byte readerNumber = byte.Parse(osdpSection["ReaderNumber"]);
            
            var panel = new ControlPanel();
            panel.ConnectionStatusChanged += (_, eventArgs) =>
            {
                Console.WriteLine($"Device is {(eventArgs.IsConnected ? "Online" : "Offline")}");

            };
            panel.NakReplyReceived += (_, args) =>
            {
                Console.WriteLine($"Received NAK {args.Nak}");
            };
            panel.ExtendedReadReplyReceived += (_, eventArgs) =>
            {
                Task.Run(async () =>
                {
                    if (!_readyForSmartCardRead)
                    {
                        return;
                    }

                    try
                    {
                        if (eventArgs.ExtendedRead.Mode == 1 && eventArgs.ExtendedRead.PReply == 1)
                        {
                            _readyForSmartCardRead = false;

                            var response = await panel.ExtendedWriteData(_connectionId, deviceAddress,
                                ExtendedWrite.ModeOneSmartCardScan(readerNumber));
                            if (eventArgs.ExtendedRead.Mode == 1 && response.ReplyData?.PReply == 1)
                            {
                                Console.WriteLine("Card Present");
                                while (true)
                                {
                                    Console.WriteLine("Enter APDU data, leave blank to terminate:");
                                    var data = Console.ReadLine()?.Trim();
                                    if (string.IsNullOrWhiteSpace(data))
                                    {
                                        break;
                                    }

                                    response = await panel.ExtendedWriteData(_connectionId, deviceAddress,
                                        ExtendedWrite.ModeOnePreplacedAPDUCommand(readerNumber, StringToByteArray(data)));
                                    if (response.ReplyData == null)
                                    {
                                        break;
                                    }

                                    Console.WriteLine(
                                        $"Received extended reply {response.ReplyData.Mode}:{response.ReplyData.PReply}:{BitConverter.ToString(response.ReplyData.PData).Replace("-", string.Empty)}");
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                    if (eventArgs.ExtendedRead.Mode == 1)
                    {
                        try
                        {
                            Console.WriteLine("Disconnecting from SmartCard");
                            await panel.ExtendedWriteData(_connectionId, deviceAddress,
                                ExtendedWrite.ModeOneTerminateSmartCardConnection(readerNumber));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                        finally
                        {
                            _readyForSmartCardRead = true;
                        }
                    }
                });
            };
            panel.RawCardDataReplyReceived += (_, eventArgs) => 
            {
                Console.WriteLine($"Raw card read {FormatData(eventArgs.RawCardData.Data)}");
            }; 
            
            _connectionId = panel.StartConnection(new SerialPortOsdpConnection(portName, baudRate));
            panel.AddDevice(_connectionId, 0, true, true);

            Timer timer = new Timer(5000);
            timer.Elapsed += (_, _) =>
            {
                Task.Run(async () =>
                {
                    timer.Stop();
                    try
                    {
                        if (_readyForSmartCardRead && panel.IsOnline(_connectionId, deviceAddress))
                        {
                            Console.WriteLine("Checking SmartCard settings");
                            var response = await panel.ExtendedWriteData(_connectionId, deviceAddress, ExtendedWrite.ReadModeSetting());
                            if (response.ReplyData == null)
                            {
                                panel.ResetDevice(_connectionId, 0);
                            }
                            else if (response.ReplyData.Mode == 0 && response.ReplyData.PReply == 1 && response.ReplyData.PData[0] == 0)
                            {
                                await panel.ExtendedWriteData(_connectionId, 0, ExtendedWrite.ModeOneConfiguration());
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    finally
                    {
                        timer.Start();
                    }
                });
            };
            
            timer.Start();

            await Task.Delay(TimeSpan.FromDays(7));
        }

19 Source : Actions.cs
with MIT License
from cabarius

public static void KingdomTimelineAdvanceDays(int days) {
            var kingdom = KingdomState.Instance;
            var timelineManager = kingdom.TimelineManager;

            // from KingdomState.SkipTime
            foreach (var kingdomTask in kingdom.ActiveTasks) {
                if (!kingdomTask.IsFinished && !kingdomTask.IsStarted && !kingdomTask.NeedsCommit && kingdomTask.HasreplacedignedLeader) {
                    kingdomTask.Start(true);
                }
            }

            // from KingdomTimelineManager.Advance
            if (!KingdomTimelineManager.CanAdvanceTime()) {
                return;
            }
            Game.Instance.AdvanceGameTime(TimeSpan.FromDays(days));
            if (Game.Instance.IsModeActive(GameModeType.Kingdom)) {
                foreach (var unitEnreplacedyData in Game.Instance.Player.AllCharacters) {
                    RestController.ApplyRest(unitEnreplacedyData.Descriptor);
                }
            }

            timelineManager.UpdateTimeline();
        }

19 Source : QCAlgorithm.cs
with Apache License 2.0
from Capnode

public void SetStartDate(DateTime start)
        {
            // no need to set this value in live mode, will be set using the current time.
            if (_liveMode) return;

            //Round down
            start = start.RoundDown(TimeSpan.FromDays(1));

            //Validate the start date:
            //1. Check range;
            if (start < (new DateTime(1900, 01, 01)))
            {
                throw new ArgumentOutOfRangeException(nameof(start), "Please select a start date after January 1st, 1900.");
            }

            //2. Check future date
            var todayInAlgorithmTimeZone = DateTime.UtcNow.ConvertFromUtc(TimeZone).Date;
            if (start > todayInAlgorithmTimeZone)
            {
                throw new ArgumentOutOfRangeException(nameof(start), "Please select start date less than today");
            }

            //3. Check not locked already:
            if (!_locked)
            {
                _startDate = start;
                SetDateTime(_startDate.ConvertToUtc(TimeZone));
            }
            else
            {
                throw new InvalidOperationException("Algorithm.SetStartDate(): Cannot change start date after algorithm initialized.");
            }
        }

19 Source : QCAlgorithm.cs
with Apache License 2.0
from Capnode

public void SetEndDate(DateTime end)
        {
            // no need to set this value in live mode, will be set using the current time.
            if (_liveMode) return;

            //Validate:
            //1. Check Range:
            //if (end > DateTime.Now.Date.AddDays(-1))
            //{
            //    end = DateTime.Now.Date.AddDays(-1);
            //}

            //2. Make this at the very end of the requested date
            end = end.RoundDown(TimeSpan.FromDays(1)).AddDays(1).AddTicks(-1);

            //3. Check not locked already:
            if (!_locked)
            {
                _endDate = end;
            }
            else
            {
                throw new InvalidOperationException("Algorithm.SetEndDate(): Cannot change end date after algorithm initialized.");
            }
        }

19 Source : BasicTemplateFuturesAlgorithm.cs
with Apache License 2.0
from Capnode

public override void Initialize()
        {
            SetStartDate(2013, 10, 08);
            SetEndDate(2013, 10, 10);
            SetCash(1000000);

            var futureSP500 = AddFuture(RootSP500);
            var futureGold = AddFuture(RootGold);

            // set our expiry filter for this futures chain
            // SetFilter method accepts TimeSpan objects or integer for days.
            // The following statements yield the same filtering criteria 
            futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
            futureGold.SetFilter(0, 182);

            var benchmark = AddEquity("SPY");
            SetBenchmark(benchmark.Symbol);
        }

19 Source : BasicTemplateFuturesFrameworkAlgorithm.cs
with Apache License 2.0
from Capnode

public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Minute;

            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);
            SetCash(100000);

            // set framework models
            SetUniverseSelection(new FrontMonthFutureUniverseSelectionModel(SelectFutureChainSymbols));
            SetAlpha(new ConstantFutureContractAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
            SetPortfolioConstruction(new SingleSharePortfolioConstructionModel());
            SetExecution(new ImmediateExecutionModel());
            SetRiskManagement(new NullRiskManagementModel());
        }

See More Examples