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 : Edi.cs
with MIT License
from 0ffffffffh

static void DailyClientInfoWiper(object state)
        {
            if (!ediSvc.WipeClientInfos())
            {
                wipeDelayed = true;

                wipeTimer.Change(
                    (int)TimeSpan.FromMinutes(5).TotalMilliseconds,
                    (int)TimeSpan.FromMinutes(5).TotalMilliseconds
                    );

                Log.Warning("Client state wipe cant be done. Will be trying in 5 minutes again");
            }
            else
            {
                if (wipeDelayed)
                {
                    wipeTimer.Change(GetOccurancePeriodInterval(), (int)TimeSpan.FromDays(1).TotalMilliseconds);
                    wipeDelayed = false;
                }

                Log.Info("Client state list wipe successful.");
            }
        }

19 Source : Edi.cs
with MIT License
from 0ffffffffh

public static bool StartEdi()
        {
            Log.Info("Edi registration handler starting at port 1999");

            GenSessionId();

            ediSvc = new EdisFace(1999);

            if (!ediSvc.IsAlive)
            {
                ediSvc = null;
                return false;
            }

            
            wipeTimer = new Timer(
                new TimerCallback(DailyClientInfoWiper), ediSvc, GetOccurancePeriodInterval(), 
                (int)TimeSpan.FromDays(1).TotalMilliseconds);

            Log.Info("Reginfo housekeeper starting..");

            return true;
        }

19 Source : BookListWebCoreModule.cs
with MIT License
from 52ABP

private void ConfigureTokenAuth()
        {
            IocManager.Register<TokenAuthConfiguration>();
            var tokenAuthConfig = IocManager.Resolve<TokenAuthConfiguration>();

            tokenAuthConfig.SecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appConfiguration["Authentication:JwtBearer:SecurityKey"]));
            tokenAuthConfig.Issuer = _appConfiguration["Authentication:JwtBearer:Issuer"];
            tokenAuthConfig.Audience = _appConfiguration["Authentication:JwtBearer:Audience"];
            tokenAuthConfig.SigningCredentials = new SigningCredentials(tokenAuthConfig.SecurityKey, SecurityAlgorithms.HmacSha256);
            tokenAuthConfig.Expiration = TimeSpan.FromDays(1);
        }

19 Source : EShopOnAbpPublicWebModule.cs
with MIT License
from abpframework

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            Microsoft.IdenreplacedyModel.Logging.IdenreplacedyModelEventSource.ShowPII = true;
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration = context.Services.GetConfiguration();

            Configure<AbpMulreplacedenancyOptions>(options =>
            {
                options.IsEnabled = true;
            });

            Configure<AbpDistributedCacheOptions>(options =>
            {
                options.KeyPrefix = "EShopOnAbp:";
            });

            Configure<AppUrlOptions>(options =>
            {
                options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
            });

            context.Services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies", options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                })
                .AddAbpOpenIdConnect("oidc", options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;

                    options.ClientId = configuration["AuthServer:ClientId"];
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];

                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;

                    options.Scope.Add("role");
                    options.Scope.Add("email");
                    options.Scope.Add("phone");
                    options.Scope.Add("AdministrationService");
                    // options.Scope.Add("ProductService");
                });

            var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
            context.Services
                .AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "EShopOnAbp-Protection-Keys")
                .SetApplicationName("eShopOnAbp-PublicWeb");

            Configure<AbpNavigationOptions>(options =>
            {
                options.MenuContributors.Add(new EShopOnAbpPublicWebMenuContributor(configuration));
            });

            Configure<AbpToolbarOptions>(options =>
            {
                options.Contributors.Add(new EShopOnAbpPublicWebToolbarContributor());
            });
        }

19 Source : FileCacheTest.cs
with Apache License 2.0
from acarteas

[TestMethod]
        public void CleanCacheTest()
        {
            _cache = new FileCache("CleanCacheTest");

            _cache.Add("foo", 1, DateTime.Now); // expires immediately
            _cache.Add("bar", 2, DateTime.Now + TimeSpan.FromDays(1)); // set to expire tomorrow
            _cache.Add("foo", 1, DateTime.Now, "region"); // expires immediately
            _cache.Add("bar", 2, DateTime.Now + TimeSpan.FromDays(1), "region"); // set to expire tomorrow

            var keys = _cache.GetKeys().ToList();
            keys.Should().Contain("foo");
            keys.Should().Contain("bar");
            keys = _cache.GetKeys("region").ToList();
            keys.Should().Contain("foo");
            keys.Should().Contain("bar");

            _cache.CleanCache();

            keys = _cache.GetKeys().ToList();
            keys.Should().NotContain("foo");
            keys.Should().Contain("bar");
            keys = _cache.GetKeys("region").ToList();
            keys.Should().NotContain("foo");
            keys.Should().Contain("bar");
        }

19 Source : MainControl.xaml.cs
with MIT License
from Actipro

private void GenerateItems() {
			var rootModel = new TreeNodeModel();

			var todayGroupModel = new TreeNodeModel();
			todayGroupModel.IsExpanded = true;
			todayGroupModel.Name = "Today";
			rootModel.Children.Add(todayGroupModel);

			var mailModel = new MailTreeNodeModel();
			mailModel.IsFlagged = true;
			mailModel.DateTime = DateTime.Today.Add(TimeSpan.FromMinutes(560));
			mailModel.Author = "Actipro Software Sales";
			mailModel.Name = "TreeListBox Features";
			mailModel.Text = "The TreeListBox has some amazing features.";
			todayGroupModel.Children.Add(mailModel);
			
			var yesterdayGroupModel = new TreeNodeModel();
			yesterdayGroupModel.IsExpanded = true;
			yesterdayGroupModel.Name = "Yesterday";
			rootModel.Children.Add(yesterdayGroupModel);
			
			mailModel = new MailTreeNodeModel();
			mailModel.DateTime = DateTime.Today.Subtract(TimeSpan.FromDays(1)).Add(TimeSpan.FromMinutes(734));
			mailModel.Author = "Bill Lumbergh";
			mailModel.Name = "Milton's Stapler";
			mailModel.Text = "Milton has been looking for his stapler.  It should be downstairs in storage room B.";
			yesterdayGroupModel.Children.Add(mailModel);
			
			mailModel = new MailTreeNodeModel();
			mailModel.DateTime = DateTime.Today.Subtract(TimeSpan.FromDays(1)).Add(TimeSpan.FromMinutes(644));
			mailModel.Author = "Milton Waddams";
			mailModel.Name = "Stapler";
			mailModel.Text = "Excuse me, I believe Bill took my stapler.  Have you seen it?";
			yesterdayGroupModel.Children.Add(mailModel);
			
			var lastWeekGroupModel = new TreeNodeModel();
			lastWeekGroupModel.IsExpanded = true;
			lastWeekGroupModel.Name = "Last Week";
			rootModel.Children.Add(lastWeekGroupModel);
			
			mailModel = new MailTreeNodeModel();
			mailModel.IsFlagged = true;
			mailModel.DateTime = DateTime.Today.Subtract(TimeSpan.FromDays(3)).Add(TimeSpan.FromMinutes(841));
			mailModel.Author = "Actipro Software Sales";
			mailModel.Name = "UI Controls Evaluation";
			mailModel.Text = "How is the evaluation going?  I just wanted to check in.";
			lastWeekGroupModel.Children.Add(mailModel);
			
			mailModel = new MailTreeNodeModel();
			mailModel.DateTime = DateTime.Today.Subtract(TimeSpan.FromDays(5)).Add(TimeSpan.FromMinutes(724));
			mailModel.Author = "Bill Lumbergh";
			mailModel.Name = "Tree Control";
			mailModel.Text = "Yeah, I'm going to need you to find a good tree control.  Maybe that Actipro one.";
			lastWeekGroupModel.Children.Add(mailModel);
			
			treeListBox.Rooreplacedem = rootModel;
			treeListBox.SelectedItem = mailModel;
		}

19 Source : ModifiedOnDateRange.cs
with MIT License
from Adoxio

private static string FromDays(int fromDays)
		{
			return DateTools.DateToString(DateTime.Today.Subtract(TimeSpan.FromDays(fromDays)), DateTools.Resolution.DAY);
		}

19 Source : RoleInstanceEndpointPortalSearchProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().Name;
			}

			base.Initialize(name, config);

			PortalName = config["portalName"];
			BindingConfiguration = config["bindingConfiguration"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"description",
				"portalName",
				"bindingConfiguration"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ProviderException("The search provider {0} does not currently recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			try
			{
				var serviceRoleName = RoleEnvironment.GetConfigurationSettingValue("Adxstudio.Xrm.Search.WindowsAzure.ServiceRole");

				if (string.IsNullOrEmpty(serviceRoleName))
				{
					throw new ProviderException("Configuration value Adxstudio.Xrm.Search.WindowsAzure.ServiceRole cannot be null or empty.");
				}

				Role serviceRole;

				if (!RoleEnvironment.Roles.TryGetValue(serviceRoleName, out serviceRole))
				{
					throw new ProviderException("Unable to retrieve the role {0}.".FormatWith(serviceRoleName));
				}

				var serviceEndpointName = RoleEnvironment.GetConfigurationSettingValue("Adxstudio.Xrm.Search.WindowsAzure.ServiceEndpoint");

				if (string.IsNullOrEmpty(serviceEndpointName))
				{
					throw new ProviderException("Configuration value Adxstudio.Xrm.Search.WindowsAzure.ServiceEndpoint cannot be null or empty.");
				}

				var serviceEndpoint = serviceRole.Instances.Select(instance =>
				{
					RoleInstanceEndpoint endpoint;

					return instance.InstanceEndpoints.TryGetValue(serviceEndpointName, out endpoint) ? endpoint : null;
				}).FirstOrDefault(endpoint => endpoint != null);

				if (serviceEndpoint == null)
				{
					throw new ProviderException("Unable to retrieve the endpoint {0} from role {1}.".FormatWith(serviceEndpointName, serviceRole.Name));
				}

				ServiceEndpointAddress = new EndpointAddress(string.Format(CultureInfo.InvariantCulture, "net.tcp://{0}/search", serviceEndpoint.IPEndpoint));

				var binding = string.IsNullOrEmpty(BindingConfiguration)
					? new NetTcpBinding(SecurityMode.None) { ReceiveTimeout = TimeSpan.FromDays(1), SendTimeout = TimeSpan.FromDays(1) }
					: new NetTcpBinding(BindingConfiguration);

				ServiceChannelFactory = new ChannelFactory<ISearchService>(binding);

				ServiceChannelFactory.Faulted += OnServiceChannelFactoryFaulted;
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Error initializing provider ""{0}"": {1}", name, e.ToString()));

                throw;
			}
		}

19 Source : ChildEvents.aspx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs args)
		{
			var dataAdapter = new WebPageChildEventDataAdapter(Enreplacedy.ToEnreplacedyReference(), new PortalContextDataAdapterDependencies(Portal, PortalName));
			var now = DateTime.UtcNow;

			var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90));
			var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));

			var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray();

			UpcomingEvents.DataSource = occurrences.Where(e => e.Start >= now).OrderBy(e => e.Start);
			UpcomingEvents.DataBind();

			PastEvents.DataSource = occurrences.Where(e => e.Start < now).OrderByDescending(e => e.Start);
			PastEvents.DataBind();
		}

19 Source : Event.aspx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs args)
		{
			var @event = _portal.Value.Enreplacedy;

			if (@event == null || @event.LogicalName != "adx_event")
			{
				return;
			}

			var dataAdapter = new EventDataAdapter(@event, new PortalContextDataAdapterDependencies(_portal.Value, PortalName));
			var now = DateTime.UtcNow;

			var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90));
			var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));

			var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray();

			IEventOccurrence requestOccurrence;

			RequestEventOccurrence = dataAdapter.TryMatchRequestEventOccurrence(Request, occurrences, out requestOccurrence)
				? requestOccurrence
				: occurrences.Length == 1 ? occurrences.Single() : null;

			var user = _portal.Value.User;

			CanRegister = Request.IsAuthenticated && user != null && RequestEventOccurrence != null &&
						RequestEventOccurrence.Start >= now && RequestEventOccurrence.EventSchedule != null &&
						RequestEventOccurrence.Event != null;

			RequiresRegistration = @event.GetAttributeValue<bool?>("adx_requiresregistration").GetValueOrDefault()
				&& RequestEventOccurrence != null
				&& RequestEventOccurrence.Start >= now;

			
			RegistrationRequiresPayment =
				_portal.Value.ServiceContext.CreateQuery("adx_eventproduct")
							.Where(ep => ep.GetAttributeValue<EnreplacedyReference>("adx_event") == @event.ToEnreplacedyReference())
							.ToList()
							.Any();

			if (CanRegister)
			{
				var registration = _portal.Value.ServiceContext.CreateQuery("adx_eventregistration")
					.FirstOrDefault(e => e.GetAttributeValue<EnreplacedyReference>("adx_attendeeid") == user.ToEnreplacedyReference()
						&& e.GetAttributeValue<EnreplacedyReference>("adx_eventscheduleid") == RequestEventOccurrence.EventSchedule.ToEnreplacedyReference()
						&& e.GetAttributeValue<OptionSetValue>("statuscode") != null && e.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)EventStatusCode.Completed);

				if (registration != null)
				{
					IsRegistered = true;
					Unregister.CommandArgument = registration.Id.ToString();
				}
			}

			OtherOccurrences.DataSource = occurrences
				.Where(e => e.Start >= now)
				.Where(e => RequestEventOccurrence == null || !(e.EventSchedule.Id == RequestEventOccurrence.EventSchedule.Id && e.Start == RequestEventOccurrence.Start));

			OtherOccurrences.DataBind();

			var sessionEvent = @event;

			Speakers.DataSource = sessionEvent.GetRelatedEnreplacedies(_portal.Value.ServiceContext, new Relationship("adx_eventspeaker_event"))
				.OrderBy(e => e.GetAttributeValue<string>("adx_name"));

			Speakers.DataBind();
		}

19 Source : Events.aspx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs args)
		{
			var dataAdapter = new WebsiteEventDataAdapter(new PortalContextDataAdapterDependencies(Portal, PortalName));
			var now = DateTime.UtcNow;

			var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90));
			var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));

			var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray();

			UpcomingEvents.DataSource = occurrences.Where(e => e.Start >= now).OrderBy(e => e.Start);
			UpcomingEvents.DataBind();

			PastEvents.DataSource = occurrences.Where(e => e.Start < now).OrderByDescending(e => e.Start);
			PastEvents.DataBind();
		}

19 Source : IdentityConfig.cs
with MIT License
from Adoxio

public static ApplicationUserManager Create(IdenreplacedyFactoryOptions<ApplicationUserManager> options, IOwinContext context)
		{
			var dbContext = context.Get<CrmDbContext>();
			var website = context.Get<CrmWebsite>();

			var manager = new ApplicationUserManager(
				new UserStore(dbContext, website.GetCrmUserStoreSettings(context)),
				website.GetCrmIdenreplacedyErrorDescriber(context));

			// Configure default validation logic for usernames
			var userValidator = manager.UserValidator as UserValidator<ApplicationUser, string>;

			if (userValidator != null)
			{
				userValidator.AllowOnlyAlphanumericUserNames = false;
				userValidator.RequireUniqueEmail = true;
			}

			// Configure default validation logic for preplacedwords
			var preplacedwordValidator = manager.PreplacedwordValidator as PreplacedwordValidator;

			if (preplacedwordValidator != null)
			{
				preplacedwordValidator.RequiredLength = 8;
				preplacedwordValidator.RequireNonLetterOrDigit = false;
				preplacedwordValidator.RequireDigit = false;
				preplacedwordValidator.RequireLowercase = false;
				preplacedwordValidator.RequireUppercase = false;
			}

			var crmPreplacedwordValidator = manager.PreplacedwordValidator as CrmPreplacedwordValidator;

			if (crmPreplacedwordValidator != null)
			{
				crmPreplacedwordValidator.EnforcePreplacedwordPolicy = true;
			}

			var minimumLengthValidator = manager.PreplacedwordValidator as MinimumLengthValidator;

			if (minimumLengthValidator != null)
			{
				minimumLengthValidator.RequiredLength = 8;
			}

			// Configure user lockout defaults
			manager.UserLockoutEnabledByDefault = true;
			manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromDays(1);
			manager.MaxFailedAccessAttemptsBeforeLockout = 5;

			// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
			// You can write your own provider and plug in here.
			manager.RegisterTwoFactorProvider("PhoneCode", new CrmPhoneNumberTokenProvider<ApplicationUser>(context.Get<ApplicationOrganizationManager>()));
			manager.RegisterTwoFactorProvider("EmailCode", new CrmEmailTokenProvider<ApplicationUser>(context.Get<ApplicationOrganizationManager>()));
			manager.EmailService = new EmailService();
			manager.SmsService = new SmsService();

			var dataProtectionProvider = options.DataProtectionProvider;

			if (dataProtectionProvider != null)
			{
				manager.UserTokenProvider =
					new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Idenreplacedy"));
			}

			var claimsIdenreplacedyFactory = new CrmClaimsIdenreplacedyFactory<ApplicationUser>(context.Authentication)
			{
				KeepExternalLoginClaims = true,
			};

			manager.ClaimsIdenreplacedyFactory = claimsIdenreplacedyFactory;

			manager.Configure(website);

			return manager;
		}

19 Source : EventsPanel.ascx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			var dataAdapter = new WebsiteEventDataAdapter(new Adxstudio.Xrm.Cms.PortalContextDataAdapterDependencies(Portal));
			var now = DateTime.UtcNow;

			var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));

			UpcomingEvents.DataSource = dataAdapter.SelectEventOccurrences(now, now.Add(future)).Take(Html.IntegerSetting("Home Event Count").GetValueOrDefault(3));
			UpcomingEvents.DataBind();
		}

19 Source : AuthorizedToken.razor.cs
with Apache License 2.0
from Aguafrommars

protected override void OnInitialized()
        {
            Localizer.OnResourceReady = () => InvokeAsync(StateHasChanged);
            if (Value != null)
            {
                var timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(Value));
                _token = new Token
                {
                    ValueString = timeSpan.ToString(DISPLAY_FORMAT)
                };
            }
            else
            {
                _token = new Token();
            }

            _token.PropertyChanged += (s, e) =>
            {
                if (_updatingValue)
                {
                    return;
                }

                var match = _regex.Match(_token.ValueString);
                if (!match.Success)
                {
                    return;
                }

                var groups = match.Groups;
                if (groups["DaysTime"].Success || groups["Time"].Success)
                {
                    var newTimeSpan = TimeSpan.Parse(_token.ValueString);
                    SetValue(newTimeSpan);
                }
                else if (groups["MinutesSecondes"].Success)
                {
                    var newTimeSpan = TimeSpan.Parse($"00:{_token.ValueString}");
                    SetValue(newTimeSpan);
                }
                else if (groups["Days"].Success)
                {
                    var newTimeSpan = TimeSpan.FromDays(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (groups["Hours"].Success)
                {
                    var newTimeSpan = TimeSpan.FromHours(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (groups["Minutes"].Success)
                {
                    var newTimeSpan = TimeSpan.FromMinutes(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (_token.ValueString.EndsWith("s"))
                {
                    var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else
                {
                    var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString));
                    SetValue(newTimeSpan);
                }
            };
            base.OnInitialized();
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_NoDefaultKey_CreatesNewKeyWithImmediateActivation()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts1 = new CancellationTokenSource();
            var expirationCts2 = new CancellationTokenSource();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var allKeys1 = new IKey[0];

            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z");
            var allKeys2 = new[] { key1, key2 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts1.Token, expirationCts2.Token },
                getAllKeysReturnValues: new[] { allKeys1, allKeys2 },
                createNewKeyCallbacks: new[] {
                    Tuple.Create((DateTimeOffset)now, (DateTimeOffset)now + TimeSpan.FromDays(90), CreateKey())
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys1, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        }),
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys2, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = false
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key1.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts1.Cancel();
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts2.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy", "CreateNewKey", "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_NoDefaultKey_KeyGenerationDisabled_Fails()
        {
            // Arrange
            var callSequence = new List<string>();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var allKeys = new IKey[0];

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { CancellationToken.None },
                getAllKeysReturnValues: new[] { allKeys },
                createNewKeyCallbacks: new[] {
                    Tuple.Create((DateTimeOffset)now, (DateTimeOffset)now + TimeSpan.FromDays(90), CreateKey())
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        })
                },
                keyManagementOptions: new KeyRotationOptions() { AutoGenerateKeys = false });

            // Act
            replacedert.Throws<InvalidOperationException>(() => keyRingProvider.GetCacheableKeyRing(now));

            // replacedert
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

private static KeyRingProvider CreateKeyRingProvider(ICacheableKeyRingProvider cacheableKeyRingProvider)
        {
            var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
            mockEncryptorFactory.Setup(m => m.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
            var options = new KeyRotationOptions
            {
                KeyPropagationWindow = TimeSpan.FromDays(2)
            };
            options.AuthenticatedEncryptorFactories.Add(mockEncryptorFactory.Object);

            return new KeyRingProvider(
                keyManager: null,
                keyManagementOptions: Options.Create(options),
                defaultKeyResolver: null,
                loggerFactory: NullLoggerFactory.Instance)
            {
                CacheableKeyRingProvider = cacheableKeyRingProvider
            };
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_NoDefaultKey_CreatesNewKeyWithImmediateActivation_StillNoDefaultKey_ReturnsNewlyCreatedKey()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts1 = new CancellationTokenSource();
            var expirationCts2 = new CancellationTokenSource();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var allKeys = new IKey[0];

            var newlyCreatedKey = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts1.Token, expirationCts2.Token },
                getAllKeysReturnValues: new[] { allKeys, allKeys },
                createNewKeyCallbacks: new[] {
                    Tuple.Create((DateTimeOffset)now, (DateTimeOffset)now + TimeSpan.FromDays(90), newlyCreatedKey)
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        }),
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(newlyCreatedKey.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts1.Cancel();
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts2.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy", "CreateNewKey", "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : CreatePersonalAccessTokenService.cs
with Apache License 2.0
from Aguafrommars

public async Task<string> CreatePersonalAccessTokenAsync(HttpContext context,
            bool isRefenceToken,
            int lifetimeDays,
            IEnumerable<string> apis, 
            IEnumerable<string> scopes, 
            IEnumerable<string> claimTypes)
        {
            CheckParams(apis);

            scopes ??= Array.Empty<string>();
            claimTypes ??= Array.Empty<string>();

            claimTypes = claimTypes.Where(c => c != JwtClaimTypes.Name &&
                c != JwtClaimTypes.ClientId &&
                c != JwtClaimTypes.Subject);

            var user = new ClaimsPrincipal(new ClaimsIdenreplacedy(context.User.Claims.Select(c =>
            {
                if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.TryGetValue(c.Type, out string newType))
                {
                    return new Claim(newType, c.Value);
                }
                return c;
            }), "Bearer", JwtClaimTypes.Name, JwtClaimTypes.Role));

            var clientId = user.Claims.First(c => c.Type == JwtClaimTypes.ClientId).Value;
            await ValidateRequestAsync(apis, scopes, user, clientId).ConfigureAwait(false);

            var issuer = context.GetIdenreplacedyServerIssuerUri();
            var sub = user.FindFirstValue(JwtClaimTypes.Subject) ?? user.FindFirstValue("nameid");
            var userName = user.Idenreplacedy.Name;

            return await _tokenService.CreateSecurityTokenAsync(new Token(IdenreplacedyServerConstants.TokenTypes.AccessToken)
            {
                AccessTokenType = isRefenceToken ? AccessTokenType.Reference : AccessTokenType.Jwt,
                Audiences = apis.ToArray(),
                ClientId = clientId,
                Claims = user.Claims.Where(c => claimTypes.Any(t => c.Type == t))
                    .Concat(new[]
                    {
                        new Claim(JwtClaimTypes.Name, userName),
                        new Claim(JwtClaimTypes.ClientId, clientId),
                        new Claim(JwtClaimTypes.Subject, sub)
                    })
                    .Concat(scopes.Select(s => new Claim("scope", s)))
                    .ToArray(),
                CreationTime = DateTime.UtcNow,
                Lifetime = Convert.ToInt32(TimeSpan.FromDays(lifetimeDays).TotalSeconds),
                Issuer = issuer
            });
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_WithDefaultKey_CreatesNewKeyWithDeferredActivationAndExpirationBasedOnActivationDate()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts1 = new CancellationTokenSource();
            var expirationCts2 = new CancellationTokenSource();

            var now = StringToDateTime("2016-02-01 00:00:00Z");
            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var allKeys1 = new[] { key1 };

            var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z");
            var allKeys2 = new[] { key1, key2 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts1.Token, expirationCts2.Token },
                getAllKeysReturnValues: new[] { allKeys1, allKeys2 },
                createNewKeyCallbacks: new[] {
                    Tuple.Create(key1.ExpirationDate, key1.ExpirationDate + TimeSpan.FromDays(90), CreateKey())
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys1, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = true
                        }),
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys2, new DefaultKeyResolution()
                        {
                            DefaultKey = key2,
                            ShouldGenerateNewKey = false
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key2.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts1.Cancel();
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts2.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy", "CreateNewKey", "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : ConfigurationExtensions.cs
with MIT License
from ahydrax

[PublicAPI]
        public static IGlobalConfiguration UseHeartbeatPage(this IGlobalConfiguration config, HeartbeatDashboardOptions heartbeatDashboardOptions)
        {
            DashboardRoutes.Routes.AddRazorPage(OverviewPage.PageRoute, x => new OverviewPage(heartbeatDashboardOptions));
            NavigationMenu.Items.Add(page => new MenuItem(OverviewPage.replacedle, page.Url.To(OverviewPage.PageRoute))
            {
                Active = page.RequestPath.StartsWith(OverviewPage.PageRoute)
            });
            DashboardRoutes.Routes.Add(OverviewPage.StatsRoute, new UtilizationJsonDispatcher());

            DashboardRoutes.Routes.Add(
                "/heartbeat/jsknockout",
                new ContentDispatcher("application/javascript", "Hangfire.Heartbeat.Dashboard.js.knockout-3.4.2.js",
                    TimeSpan.FromDays(30)));

            DashboardRoutes.Routes.Add(
                "/heartbeat/jsknockoutorderables",
                new ContentDispatcher("application/javascript", "Hangfire.Heartbeat.Dashboard.js.knockout.bindings.orderable.js",
                    TimeSpan.FromDays(30)));

            DashboardRoutes.Routes.Add(
                "/heartbeat/jsnumeral",
                new ContentDispatcher("application/javascript", "Hangfire.Heartbeat.Dashboard.js.numeral.min.js", TimeSpan.FromDays(30)));

            DashboardRoutes.Routes.Add(
                "/heartbeat/jspage",
                new ContentDispatcher("application/javascript", "Hangfire.Heartbeat.Dashboard.js.OverviewPage.js", TimeSpan.FromSeconds(1)));

            DashboardRoutes.Routes.Add(
                "/heartbeat/cssstyles",
                new ContentDispatcher("text/css", "Hangfire.Heartbeat.Dashboard.css.styles.css", TimeSpan.FromSeconds(1)));

            return config;
        }

19 Source : MissionControlBootstrapperExtensions.cs
with MIT License
from ahydrax

private static void AddDashboardRouteToEmbeddedResource(string route, string contentType, string resourceName)
            => DashboardRoutes.Routes.Add(route, new ContentDispatcher(contentType, resourceName, TimeSpan.FromDays(1)));

19 Source : TimedCleaner.cs
with MIT License
from AiursoftWeb

public Task StartAsync(CancellationToken cancellationToken)
        {
            if (_env.IsDevelopment() || !EntryExtends.IsProgramEntry())
            {
                _logger.LogInformation("Skip cleaner in development environment.");
                return Task.CompletedTask;
            }
            _logger.LogInformation("Timed Background Service is starting.");
            // Start cleaner after one day.
            // Because when stargate starts, all channels are treated dead.
            _timer = new Timer(DoWork, null, TimeSpan.FromDays(1), TimeSpan.FromMinutes(10));
            return Task.CompletedTask;
        }

19 Source : AbstractTimedBackgroundService.cs
with MIT License
from aishang2015

private TimeSpan GetDelaySpan()
        {
            return TimeSpan.FromDays(_backgroundJob.Days)
                .Add(TimeSpan.FromHours(_backgroundJob.Hours))
                .Add(TimeSpan.FromMinutes(_backgroundJob.Minutes))
                .Add(TimeSpan.FromSeconds(_backgroundJob.Seconds));
        }

19 Source : TimedCleaner.cs
with MIT License
from AiursoftWeb

public Task ClearTimeOutOAuthPack(GatewayDbContext dbContext)
        {
            var outDateTime = DateTime.UtcNow - TimeSpan.FromDays(1);
            var outDateTime2 = DateTime.UtcNow - TimeSpan.FromMinutes(20);
            dbContext.OAuthPack.Delete(t => t.UseTime < outDateTime);
            dbContext.OAuthPack.Delete(t => t.CreateTime < outDateTime2);
            return dbContext.SaveChangesAsync();
        }

19 Source : FileService.cs
with MIT License
from AiursoftWeb

public static IActionResult WebFile(this ControllerBase controller, string path, string extension)
        {
            var (etag, length) = GetFileHTTPProperties(path);
            // Handle etag
            controller.Response.Headers.Add("ETag", '\"' + etag + '\"');
            if (controller.Request.Headers.Keys.Contains("If-None-Match"))
            {
                if (controller.Request.Headers["If-None-Match"].ToString().Trim('\"') == etag)
                {
                    return new StatusCodeResult(304);
                }
            }
            // Return file result.
            controller.Response.Headers.Add("Content-Length", length.ToString());
            // Allow cache
            controller.Response.Headers.Add("Cache-Control", $"public, max-age={TimeSpan.FromDays(7).TotalSeconds}");
            return controller.PhysicalFile(path, MIME.GetContentType(extension), true);
        }

19 Source : BotHost.cs
with MIT License
from AiursoftWeb

public async Task MonitorEvents(string websocketAddress)
        {
            if (_exitEvent != null)
            {
                _botLogger.LogDanger("Bot is trying to establish a new connection while there is already a connection.");
                return;
            }
            _exitEvent = new ManualResetEvent(false);

            // Start websocket.
            var url = new Uri(websocketAddress);
            var client = new WebsocketClient(url)
            {
                ReconnectTimeout = TimeSpan.FromDays(1)
            };
            client.ReconnectionHappened.Subscribe(type => _botLogger.LogVerbose($"WebSocket: {type.Type}"));
            var subscription = client.DisconnectionHappened.Subscribe((t) =>
            {
                _botLogger.LogDanger("Websocket connection dropped!");
                _exitEvent?.Set();
                _exitEvent = null;
            });
            await client.Start();

            // log.
            _botLogger.LogInfo("Listening to your account channel.");
            _botLogger.LogVerbose(websocketAddress + "\n");
            _botLogger.AppendResult(true, 9);

            // Post connect event.
            await _eventSyncer.Init(client);
            await BuildBot.OnBotStarted();

            // Pend.
            _exitEvent?.WaitOne();
            subscription.Dispose();
            await client.Stop(WebSocketCloseStatus.NormalClosure, string.Empty);
            _botLogger.LogVerbose("Websocket connection disconnected.");
        }

19 Source : HangFireExtension.cs
with MIT License
from aishang2015

public static IServiceCollection AddMySQLHangFire(this IServiceCollection services,
            string connectionString)
        {
            services.AddHangfire(configruation =>
            {
                configruation.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                    .UseSimplereplacedemblyNameTypeSerializer()
                    .UseRecommendedSerializerSettings()
                    .UseStorage(new MySqlStorage(connectionString, new MySqlStorageOptions
                    {
                        TransactionIsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,   // 事务隔离级别
                        QueuePollInterval = TimeSpan.FromSeconds(3),                                    // 作业队列轮询间隔
                        JobExpirationCheckInterval = TimeSpan.FromHours(1),                             // 作业过期检查间隔(管理过期记录)
                        CountersAggregateInterval = TimeSpan.FromMinutes(5),                            // 计数器统计间隔
                        PrepareSchemaIfNecessary = true,                                                // 自动创建表
                        DashboardJobListLimit = 50000,                                                  // 仪表盘显示作业限制
                        TransactionTimeout = TimeSpan.FromMinutes(1),                                   // 事务超时时间
                        TablesPrefix = "T_Hangfire",                                                    // hangfire表名前缀
                        InvisibilityTimeout = TimeSpan.FromDays(1)                                      // 弃用属性,设定线程重开间隔
                    })).WithJobExpirationTimeout(TimeSpan.FromHours(24 * 7));         // 作业过期时间,过期任务会被从数据库清理。此值不能小于1小时,否则会引起异常

            }).AddHangfireServer(option =>
            {
                option.SchedulePollingInterval = TimeSpan.FromSeconds(1);
            });

            return services;
        }

19 Source : MiddlewaresExtends.cs
with MIT License
from AiursoftWeb

public static IApplicationBuilder UseAiursoftDefault(
            this IApplicationBuilder app,
            Func<IApplicationBuilder,
            IApplicationBuilder> beforeMvc = null)
        {
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en"),
                SupportedCultures = GetSupportedLanguages(),
                SupportedUICultures = GetSupportedLanguages()
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = options =>
                {
                    options.Context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromDays(14)
                    };
                }
            });
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseAiursoftAPIDefault(false, beforeMvc);
            app.UseMiddleware<SwitchLanguageMiddleware>();

            return app;
        }

19 Source : FilesCleaner.cs
with MIT License
from AiursoftWeb

public async Task AllClean(FoldersService foldersService)
        {
            try
            {
                var deadline = DateTime.UtcNow - TimeSpan.FromDays(100);
                var publicSite = _configuration["UserFilesSiteName"];
                var accessToken = await _appsContainer.AccessToken();
                var rootFolders = await foldersService.ViewContentAsync(accessToken, publicSite, string.Empty);
                foreach (var conversation in rootFolders.Value.SubFolders)
                {
                    var folders = await foldersService.ViewContentAsync(accessToken, publicSite, conversation.FolderName);
                    foreach (var folder in folders.Value.SubFolders)
                    {
                        try
                        {
                            var parts = folder.FolderName.Split('-');
                            var time = new DateTime(
                                Convert.ToInt32(parts[0]),
                                Convert.ToInt32(parts[1]),
                                Convert.ToInt32(parts[2]));
                            if (time < deadline)
                            {
                                await foldersService.DeleteFolderAsync(accessToken, publicSite, $"{conversation.FolderName}/{folder.FolderName}");
                            }
                        }
                        catch
                        {
                            await foldersService.DeleteFolderAsync(accessToken, publicSite, $"{conversation.FolderName}/{folder.FolderName}");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical(e.Message);
            }
        }

19 Source : OAuthController.cs
with MIT License
from AiursoftWeb

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (!_allowRegistering)
            {
                return Unauthorized();
            }
            if (!_captcha.Validate(model.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError(string.Empty, "Invalid captcha code!");
            }
            var app = (await _apiService.AppInfoAsync(model.AppId)).App;
            if (!ModelState.IsValid)
            {
                model.Recover(app.AppName, app.IconPath);
                return View(model);
            }
            bool exists = _dbContext.UserEmails.Any(t => t.EmailAddress == model.Email.ToLower());
            if (exists)
            {
                ModelState.AddModelError(string.Empty, $"An user with email '{model.Email}' already exists!");
                model.Recover(app.AppName, app.IconPath);
                return View(model);
            }
            var countStart = DateTime.UtcNow - TimeSpan.FromDays(1);
            var requestIp = HttpContext.Connection.RemoteIpAddress?.ToString();
            if (await _dbContext.Users
                .Where(t => t.RegisterIPAddress == requestIp)
                .Where(t => t.AccountCreateTime > countStart)
                .CountAsync() > 5)
            {
                ModelState.AddModelError(string.Empty, "You can't create more than 5 accounts in one day!");
                model.Recover(app.AppName, app.IconPath);
                return View(model);
            }
            var user = new GatewayUser
            {
                UserName = model.Email,
                Email = model.Email,
                NickName = model.Email.Split('@')[0],
                PreferedLanguage = model.PreferedLanguage,
                IconFilePath = AuthValues.DefaultImagePath,
                RegisterIPAddress = requestIp
            };
            var result = await _userManager.CreateAsync(user, model.Preplacedword);
            if (result.Succeeded)
            {
                var primaryMail = new UserEmail
                {
                    EmailAddress = model.Email.ToLower(),
                    OwnerId = user.Id,
                    ValidateToken = Guid.NewGuid().ToString("N"),
                    LastSendTime = DateTime.UtcNow
                };
                await _dbContext.UserEmails.AddAsync(primaryMail);
                await _dbContext.SaveChangesAsync();
                // Send him an confirmation email here:
                _cannonService.FireAsync<ConfirmationEmailSender>(async (sender) =>
                {
                    await sender.SendConfirmation(user.Id, primaryMail.EmailAddress, primaryMail.ValidateToken);
                });
                await _authLogger.LogAuthRecord(user.Id, HttpContext, true, app.AppId);
                await _signInManager.SignInAsync(user, isPersistent: true);
                return await _authManager.FinishAuth(user, model, app.ForceConfirmation, app.TrustedApp);
            }
            AddErrors(result);
            model.Recover(app.AppName, app.IconPath);
            return View(model);
        }

19 Source : TimedChecker.cs
with MIT License
from AiursoftWeb

private Task Clean(WWWDbContext dbContext)
        {
            var toDeleteTime = DateTime.UtcNow - TimeSpan.FromDays(90);
            dbContext.SearchHistories.Delete(t => t.SearchTime < toDeleteTime);
            return dbContext.SaveChangesAsync();
        }

19 Source : TimedCleaner.cs
with MIT License
from AiursoftWeb

private async Task AllClean(ObserverDbContext dbContext)
        {
            var oldestRecordTime = DateTime.UtcNow - TimeSpan.FromDays(7);
            var items = await dbContext.ErrorLogs.Where(t => t.LogTime < oldestRecordTime).ToListAsync();
            dbContext.ErrorLogs.RemoveRange(items);
            await dbContext.SaveChangesAsync();
        }

19 Source : EmailUserService.cs
with MIT License
from albyho

private void CacheUser(UserInfo userInfo)
        {
            var cacheKey = UserService.UserCacheKeyFormat.FormatWith(userInfo.UserId);
            _cache.SetJsonAsync(cacheKey, userInfo, new DistributedCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromDays(1)
            }).ContinueWithOnFaultedHandleLog(_logger);
        }

19 Source : WeixinUserService.cs
with MIT License
from albyho

private void Cache(UserInfo userInfo)
        {
            var cacheKey = UserService.UserCacheKeyFormat.FormatWith(userInfo.UserId);
            _cache.SetJsonAsync(cacheKey, userInfo, new DistributedCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromDays(1)
            }).ContinueWithOnFaultedHandleLog(_logger);
        }

19 Source : RegionService.cs
with MIT License
from albyho

private async Task<List<RegionTreeNode>> GetTreeInCacheInternalAsync()
        {
            /*
            var tree = await _distributedCache.GetJsonAsync<List<RegionTreeNode>>(TreeCacheKey);
            if (tree == null)
            {
                var list = await GetListInCacheInternalAsync();
                tree = new List<RegionTreeNode>();
                for (var i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    if (!item.ParentId.HasValue)
                    {
                        var node = RegionTreeNodeFromRegion(item);
                        node.ParentIdPath = null;
                        tree.Add(node);
                        RegionTreeAddChildren(list, node);
                    }
                }
                await _distributedCache.SetJsonAsync<List<RegionTreeNode>>(TreeCacheKey, tree);
            }
            return tree;
            */

            if (!_memoryCache.TryGetValue(TreeCacheKey, out List<RegionTreeNode> tree))
            {
                var list = await GetListInCacheInternalAsync();
                tree = new List<RegionTreeNode>();
                for (var i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    if (!item.ParentId.HasValue)
                    {
                        var node = RegionTreeNodeFromRegion(item);
                        node.ParentIdPath = null;
                        tree.Add(node);
                        RegionTreeAddChildren(list, node);
                    }
                }
                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    // Keep in cache for this time, reset time if accessed.
                    .SetSlidingExpiration(TimeSpan.FromDays(30));

                // Save data in cache.
                _memoryCache.Set(TreeCacheKey, tree, cacheEntryOptions);
            }

            return tree;
        }

19 Source : UserService.cs
with MIT License
from albyho

private void CacheNormalUser(UserInfo userInfo)
        {
            if (userInfo == null || userInfo.Status != UserStatus.Normal) return;
            var cacheKey = UserCacheKeyFormat.FormatWith(userInfo.UserId);
            _cache.SetJsonAsync(cacheKey, userInfo, new DistributedCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromDays(1)
            }).ContinueWithOnFaultedHandleLog(_logger);
        }

19 Source : RegionService.cs
with MIT License
from albyho

private async Task<List<RegionInfo>> GetListInCacheInternalAsync()
        {
            /*
            var list = await _distributedCache.GetJsonAsync<List<RegionInfo>>(ListCacheKey);
            if (list == null)
            {
                list = await _manager.GetRegionInfoListAsync();
                await _distributedCache.SetJsonAsync<List<RegionInfo>>(ListCacheKey, list);
            }
            return list;
            */

            if (!_memoryCache.TryGetValue(ListCacheKey, out List<RegionInfo> list))
            {
                // Key not in cache, so get data.
                list = await _distributedCache.GetJsonAsync<List<RegionInfo>>(ListCacheKey);
                if (list == null)
                {
                    list = await _manager.GetRegionInfoListAsync();
                    Cache(list);
                }

                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    // Keep in cache for this time, reset time if accessed.
                    .SetSlidingExpiration(TimeSpan.FromDays(30));

                // Save data in cache.
                _memoryCache.Set(ListCacheKey, list, cacheEntryOptions);
            }

            return list;
        }

19 Source : PieceManager.cs
with MIT License
from aljazsim

private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime checkoutTime;
            int pieceIndex;
            HashSet<int> checkoutsToRemove = new HashSet<int>();

            Thread.CurrentThread.Name = "piece manager checker";

            this.timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;

            lock (this.locker)
            {
                foreach (var checkOut in this.checkouts)
                {
                    pieceIndex = checkOut.Key;
                    checkoutTime = checkOut.Value;

                    if (DateTime.UtcNow - checkoutTime > this.checkoutTimeout)
                    {
                        checkoutsToRemove.Add(checkOut.Key);
                    }
                }

                foreach (var checkoutToRemove in checkoutsToRemove)
                {
                    this.checkouts.Remove(checkoutToRemove);

                    // checkout timeout -> mark piece as missing, giving other peers a chance to download it
                    this.BitField[checkoutToRemove] = PieceStatus.Missing;
                }
            }

            this.timer.Interval = this.timerTimeout.TotalMilliseconds;
        }

19 Source : Tracker.cs
with MIT License
from aljazsim

private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;

            this.OnAnnounce();

            this.timer.Interval = this.UpdateInterval.TotalMilliseconds;
        }

19 Source : FileLoggerTests.cs
with GNU General Public License v3.0
from Alois-xx

[Test]
        public void Ensure_That_Oldest_Files_Are_Deleted()
        {
            using (var tmp = TempDir.Create())
            {
                var dir = tmp.Name;

                using var logger = new FileLogger(dir, 30, 3);
                var deleted = new List<string>();
                logger.Delete = (path) =>
                {
                    deleted.Add(path);
                    Console.WriteLine($"Delete file {path}");
                };

                string baseName = Path.GetFileName(FileLogger.myFileBaseName);
                string ext = Path.GetExtension(FileLogger.myFileBaseName);
                string[] files = new string[] { ".1", ".2", ".3", ".4" };
                List<string> fullNames = new List<string>();
                for (int i = 0; i < files.Length; i++)
                {
                    string fullName = Path.Combine(dir, $"{baseName}{files[i]}{ext}");
                    fullNames.Add(fullName);
                    File.WriteAllText(fullName, "Hi file");
                    new FileInfo(fullName).LastWriteTime = DateTime.Now - TimeSpan.FromDays(i);
                }

                logger.RollOver();

                replacedert.AreEqual(2, deleted.Count);
                replacedert.AreEqual(fullNames[2], deleted[0]);
                replacedert.AreEqual(fullNames[3], deleted[1]);
            }
        }

19 Source : SyncCloudStatusCheckJob.cs
with GNU General Public License v3.0
from Amazing-Favorites

private async Task RunSyncAsync()
        {
            var userOptions = await _userOptionsService.GetOptionsAsync();
            if (userOptions.CloudBkFeature is
                {
                    Enabled: true,
                })
            {
                var time = TimeSpan.FromDays(1);
                switch (userOptions.CloudBkFeature.CloudBkProviderType)
                {
                    case CloudBkProviderType.GoogleDrive:
                    case CloudBkProviderType.OneDrive:
                        var data = await _simpleDataStorage.GetOrDefaultAsync<CloudBkSyncStatics>();
                        if (data.LastSyncTime != null &&
                            _clock.UtcNow > data.LastSyncTime + time.TotalSeconds)
                        {
                            await _newNotification.SyncDataWithCloudAsync(new SyncDataWithCloudInput
                            {
                                LastSyncTime = data.LastSyncTime.Value
                            });
                        }

                        break;
                }
            }
        }

19 Source : ParticipantTypingTimerTests.cs
with Apache License 2.0
from Anapher

[Fact]
        public void CancelAllTimersOfConference_TimerWreplacedet_CancelTimersOfParticipantsFromConference()
        {
            const string conferenceId2 = "43t525";
            var participantOfConference2 = new Participant(conferenceId2, "4325");

            // arrange
            var trigger = SetupTaskDelayGetTrigger();
            var capturedRequest = _mediator.CaptureRequest<SetParticipantTypingRequest, Unit>();

            var timer = Create();
            timer.RemoveParticipantTypingAfter(_testParticipant, Channel, TimeSpan.FromDays(1));
            timer.RemoveParticipantTypingAfter(participantOfConference2, Channel, TimeSpan.FromDays(1));

            // act
            timer.CancelAllTimersOfConference(ConferenceId);
            trigger();

            // replacedert
            capturedRequest.replacedertReceived();
            var request = capturedRequest.GetRequest();
            replacedert.Equal(participantOfConference2, request.Participant);
        }

19 Source : Formatter.cs
with MIT License
from andersnm

static public string Format(object value, Section node, CultureInfo culture, bool isDate1904)
        {
            switch (node.Type)
            {
                case SectionType.Number:
                    // Hide sign under certain conditions and section index
                    var number = Convert.ToDouble(value, culture);
                    if ((node.SectionIndex == 0 && node.Condition != null) || node.SectionIndex == 1)
                        number = Math.Abs(number);

                    return FormatNumber(number, node.Number, culture);

                case SectionType.Date:
                    if (ExcelDateTime.TryConvert(value, isDate1904, culture, out var excelDateTime))
                    {
                        return FormatDate(excelDateTime, node.GeneralTextDateDurationParts, culture);
                    }
                    else
                    {
                        throw new FormatException("Unexpected date value");
                    }

                case SectionType.Duration:
                    if (value is TimeSpan ts)
                    {
                        return FormatTimeSpan(ts, node.GeneralTextDateDurationParts, culture);
                    }
                    else
                    {
                        var d = Convert.ToDouble(value);
                        return FormatTimeSpan(TimeSpan.FromDays(d), node.GeneralTextDateDurationParts, culture);
                    }

                case SectionType.General:
                case SectionType.Text:
                    return FormatGeneralText(CompatibleConvert.ToString(value, culture), node.GeneralTextDateDurationParts);

                case SectionType.Exponential:
                    return FormatExponential(Convert.ToDouble(value, culture), node, culture);

                case SectionType.Fraction:
                    return FormatFraction(Convert.ToDouble(value, culture), node, culture);

                default:
                    throw new InvalidOperationException("Unknown number format section");
            }
        }

19 Source : TimeSpanExtensionsTests.cs
with MIT License
from AndreyAkinshin

[Fact]
        public void OneDay() => Check("24:00:00 (86400 sec)", TimeSpan.FromDays(1));

19 Source : TimeSpanExtensionsTests.cs
with MIT License
from AndreyAkinshin

[Fact]
        public void TwoDays() => Check("48:00:00 (172800 sec)", TimeSpan.FromDays(2));

19 Source : Startup.Auth.cs
with GNU General Public License v3.0
from andysal

public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }

19 Source : ChartElement.cs
with MIT License
from AngeloCresta

internal static double GetIntervalSize(
			double current, 
			double interval, 
			DateTimeIntervalType type, 
			Series series,
			double intervalOffset, 
			DateTimeIntervalType intervalOffsetType,
			bool forceIntIndex,
			bool forceAbsInterval)
		{
			// AxisName is not date.
			if( type == DateTimeIntervalType.Number || type == DateTimeIntervalType.Auto )
			{
				return interval;
			}

			// Special case for indexed series
			if(series != null && series.IsXValueIndexed)
			{
				// Check point index
				int pointIndex = (int)Math.Ceiling(current - 1);
				if(pointIndex < 0)
				{
					pointIndex = 0;
				}
				if(pointIndex >= series.Points.Count || series.Points.Count <= 1)
				{
					return interval;
				}

				// Get starting and ending values of the closest interval
				double		adjuster = 0;
				double		xValue = series.Points[pointIndex].XValue;
				xValue = AlignIntervalStart(xValue, 1, type, null);
				double		xEndValue = xValue + GetIntervalSize(xValue, interval, type);
				xEndValue += GetIntervalSize(xEndValue, intervalOffset, intervalOffsetType);
				xValue += GetIntervalSize(xValue, intervalOffset, intervalOffsetType);
				if(intervalOffset < 0)
				{
					xValue = xValue + GetIntervalSize(xValue, interval, type);
					xEndValue = xEndValue + GetIntervalSize(xEndValue, interval, type);
				}

				// The first point in the series
				if(pointIndex == 0 && current < 0)
				{
					// Round the first point value depending on the interval type
					DateTime	dateValue = DateTime.FromOADate(series.Points[pointIndex].XValue);
					DateTime	roundedDateValue = dateValue;
					switch(type)
					{
						case(DateTimeIntervalType.Years): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Months): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Days): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Hours): //
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, dateValue.Hour, 
								dateValue.Minute, 0);
							break;

						case(DateTimeIntervalType.Minutes):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, 
								dateValue.Day, 
								dateValue.Hour, 
								dateValue.Minute, 
								dateValue.Second);
							break;

						case(DateTimeIntervalType.Seconds):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, 
								dateValue.Day, 
								dateValue.Hour, 
								dateValue.Minute, 
								dateValue.Second,
								0);
							break;

						case(DateTimeIntervalType.Weeks):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;
					}

					// The first point value is exactly on the interval boundaries
					if(roundedDateValue.ToOADate() == xValue || roundedDateValue.ToOADate() == xEndValue)
					{
						return - current + 1;
					}
				}

				// Adjuster of 0.5 means that position should be between points
				++pointIndex;
				while(pointIndex < series.Points.Count)
				{
					if(series.Points[pointIndex].XValue >= xEndValue)
					{
						if(series.Points[pointIndex].XValue > xEndValue && !forceIntIndex)
						{
							adjuster = -0.5;
						}
						break;
					}

					++pointIndex;
				}

				// If last point outside of the max series index
				if(pointIndex == series.Points.Count)
				{
					pointIndex += series.Points.Count/5 + 1;
				}

				double size = (pointIndex + 1) - current + adjuster;
		
				return (size != 0) ? size : interval;
			}
	
			// Non indexed series
			else
			{
				DateTime	date = DateTime.FromOADate(current);
				TimeSpan	span = new TimeSpan(0);

				if(type == DateTimeIntervalType.Days)
				{
					span = TimeSpan.FromDays(interval);
				}
				else if(type == DateTimeIntervalType.Hours)
				{
					span = TimeSpan.FromHours(interval);
				}
				else if(type == DateTimeIntervalType.Milliseconds)
				{
					span = TimeSpan.FromMilliseconds(interval);
				}
				else if(type == DateTimeIntervalType.Seconds)
				{
					span = TimeSpan.FromSeconds(interval);
				}
				else if(type == DateTimeIntervalType.Minutes)
				{
					span = TimeSpan.FromMinutes(interval);
				}
				else if(type == DateTimeIntervalType.Weeks)
				{
					span = TimeSpan.FromDays(7.0 * interval);
				}
				else if(type == DateTimeIntervalType.Months)
				{
					// Special case handling when current date points 
					// to the last day of the month
					bool lastMonthDay = false;
					if(date.Day == DateTime.DaysInMonth(date.Year, date.Month))
					{
						lastMonthDay = true;
					}

					// Add specified amount of months
					date = date.AddMonths((int)Math.Floor(interval));
					span = TimeSpan.FromDays(30.0 * ( interval - Math.Floor(interval) ));

					// Check if last month of the day was used
					if(lastMonthDay && span.Ticks == 0)
					{
						// Make sure the last day of the month is selected
						int daysInMobth = DateTime.DaysInMonth(date.Year, date.Month);
						date = date.AddDays(daysInMobth - date.Day);
					}
				}
				else if(type == DateTimeIntervalType.Years)
				{
					date = date.AddYears((int)Math.Floor(interval));
					span = TimeSpan.FromDays(365.0 * ( interval - Math.Floor(interval) ));
				}

				// Check if an absolute interval size must be returned
				double result = date.Add(span).ToOADate() - current;
				if(forceAbsInterval)
				{
					result = Math.Abs(result);
				}
				return result;
			}
		}

19 Source : Startup.cs
with MIT License
from anjoy8

public void ConfigureServices(IServiceCollection services)
        {
            //nginx 
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders =
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            services.AddHsts(options =>
            {
                options.Preload = true;
                options.IncludeSubDomains = true;
                options.MaxAge = TimeSpan.FromDays(60);
                options.ExcludedHosts.Add("ddd.neters.com");
            });


            services.AddSameSiteCookiePolicy();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            // IdenreplacedyServer4 注入
            if (Configuration["Authentication:IdenreplacedyServer4:Enabled"].ObjToBool())
            {
                System.Console.WriteLine("当前授权模式是:Ids4");
                services.AddId4OidcSetup(Configuration);
            }
            else
            {
                System.Console.WriteLine("当前授权模式是:Idenreplacedy");
                services.AddIdenreplacedySetup(Configuration);
            }

            // Automapper 注入
            services.AddAutoMapperSetup();

            services.AddControllersWithViews();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("CanWriteStudentData", policy => policy.Requirements.Add(new ClaimRequirement("Students", "Write")));
                options.AddPolicy("CanRemoveStudentData", policy => policy.Requirements.Add(new ClaimRequirement("Students", "Remove")));
                options.AddPolicy("CanWriteOrRemoveStudentData", policy => policy.Requirements.Add(new ClaimRequirement("Students", "WriteOrRemove")));
            });

            // Adding MediatR for Domain Events
            // 领域命令、领域事件等注入
            // 引用包 MediatR.Extensions.Microsoft.DependencyInjection
            services.AddMediatR(typeof(Startup));

            // .NET Core 原生依赖注入
            // 单写一层用来添加依赖项,从展示层 Presentation 中隔离
            NativeInjectorBootStrapper.RegisterServices(services);


        }

19 Source : LocationServiceImplementation.cs
with MIT License
from anjoy8

public Task<Position> GetPositionAsync(TimeSpan? timeout = null, CancellationToken? cancelToken = null)
        {
            var timeoutMilliseconds = timeout.HasValue ? (int)timeout.Value.TotalMilliseconds : eShopOnContainers.Windows.Helpers.Timeout.Infinite;
            if (timeoutMilliseconds < 0 && timeoutMilliseconds != eShopOnContainers.Windows.Helpers.Timeout.Infinite)
                throw new ArgumentOutOfRangeException(nameof(timeout));

            if (!cancelToken.HasValue)
                cancelToken = CancellationToken.None;

            var pos = _locator.GetGeopositionAsync(TimeSpan.FromTicks(0), TimeSpan.FromDays(365));
            cancelToken.Value.Register(o => ((IAsyncOperation<Geoposition>)o).Cancel(), pos);
            var timer = new eShopOnContainers.Windows.Helpers.Timeout(timeoutMilliseconds, pos.Cancel);
            var tcs = new TaskCompletionSource<Position>();

            pos.Completed = (op, s) =>
            {
                timer.Cancel();
                switch (s)
                {
                    case AsyncStatus.Canceled:
                        tcs.SetCanceled();
                        break;
                    case AsyncStatus.Completed:
                        tcs.SetResult(GetPosition(op.GetResults()));
                        break;
                    case AsyncStatus.Error:
                        var ex = op.ErrorCode;
                        if (ex is UnauthorizedAccessException)
                            ex = new GeolocationException(GeolocationError.Unauthorized, ex);

                        tcs.SetException(ex);
                        break;
                }
            };
            return tcs.Task;           
        }

See More Examples