System.TimeSpan.FromMinutes(double)

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

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

public static ViewQueryResult FetchEntriesOfBaslik(string baslik, int baslikId, int pageNumber)
        {
            SqlServerIo sql;
            string query;
            ViewQueryResult resultSet;

            query = BuildEntryFetchSQL(baslik, baslikId, pageNumber);

            
            if (!CacheManager.TryGetCachedQueryResult<ViewQueryResult>(query, out resultSet))
            {
                sql = SqlServerIo.Create();

                if (!sql.Execute(false, query))
                {
                    SqlServerIo.Release(sql);
                    return new ViewQueryResult();
                }

                resultSet = new ViewQueryResult();

                while (sql.Read())
                {
                    if (resultSet.TotalRecordCount == 0)
                    {
                        resultSet.TotalRecordCount = sql.GetValueOfColumn<int>("TotalRecord");
                        resultSet.BaslikId = sql.GetValueOfColumn<int>("Id");
                    }

                    Entry e = new Entry(
                        sql.GetValueOfColumn<string>("Baslik"),
                        sql.GetValueOfColumn<string>("Suser"),
                        sql.GetValueOfColumn<DateTime>("SubmitDate").ToString(),
                        sql.GetValueOfColumn<string>("Entry"));

                    resultSet.Entries.Add(e);
                    resultSet.PhysicalRecordCount++;

                }

                SqlServerIo.Release(sql);

                //Dont cache for empty recordset for baslik
                if (!resultSet.HasEntry)
                    return resultSet;

                resultSet.LogicalRecordCount = resultSet.PhysicalRecordCount;

                CacheManager.CacheObject(KeysetId.Baslik(resultSet.BaslikId), true, query, resultSet);

                BaslikBasicInfo bbi = new BaslikBasicInfo()
                {
                    TotalEntries = resultSet.TotalRecordCount
                };

                CacheManager.CacheObject("BBI_" + resultSet.BaslikId.ToString(),
                    bbi,
                    TimeSpan.FromMinutes(10));


                //if this request initial fetch using the baslik string.
                //rebuild sql with baslikid and cache the result with its hashkey
                if (baslikId == 0)
                {
                    query = BuildEntryFetchSQL(null, resultSet.BaslikId, pageNumber);
                    CacheManager.CacheObject(KeysetId.Baslik(resultSet.BaslikId),true, query, resultSet);
                }
            }

            return resultSet;
        }

19 Source : Program.cs
with MIT License
from 0x727

public static void CreateTask(string randomname, string destinationFile, string min)
        {
            TaskDefinition td = TaskService.Instance.NewTask();
            td.RegistrationInfo.Author = "Microsoft"; //创建者
            td.RegistrationInfo.Description = "UPnPHost Service Settings"; //描述
            //计划任务运行时间 Min/Day
            double time = double.Parse(min);
            TimeTrigger tt = new TimeTrigger();
            tt.StartBoundary = DateTime.Now;
            tt.Repereplacedion.Interval = TimeSpan.FromMinutes(time);

            td.Triggers.Add(tt);
            td.Actions.Add(destinationFile, null, null);
            string taskpath = @"\Microsoft\Windows\UPnP\" + randomname;
            TaskService.Instance.RootFolder.RegisterTaskDefinition(taskpath, definition: td, TaskCreation.CreateOrUpdate, null, null, 0);
            HidXml(taskpath);
            RegistryKeyRule(randomname);
        }

19 Source : FauxDeployCMAgent.cs
with GNU General Public License v3.0
from 1RedOne

public static SmsClientId RegisterClient(string CMServerName, string ClientName, string DomainName, string CertPath, SecureString preplaced, ILog log)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))
            {
                // Create a registration request
                ConfigMgrRegistrationRequest registrationRequest = new ConfigMgrRegistrationRequest();

                // Add our certificate for message signing
                registrationRequest.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                // Set the destination hostname
                registrationRequest.Settings.HostName = CMServerName;

                log.Info($"[{ClientName}] - Running Discovery...");
                // Discover local properties for registration metadata
                registrationRequest.Discover();
                registrationRequest.AgentIdenreplacedy = "MyCustomClient";
                registrationRequest.ClientFqdn = ClientName + "." + DomainName;
                registrationRequest.NetBiosName = ClientName;
                log.Info("About to try to register " + registrationRequest.ClientFqdn);

                // Register client and wait for a confirmation with the SMSID

                registrationRequest.Settings.Compression = MessageCompression.Zlib;
                registrationRequest.Settings.ReplyCompression = MessageCompression.Zlib;
                log.Info($"[{ClientName}] - Message Zipped successfully, registering...");
                SmsClientId clientId = registrationRequest.RegisterClient(Sender, TimeSpan.FromMinutes(5));
                log.Info($"[{ClientName}] - Got SMSID from CM Server for this client of {clientId}...");
                return clientId;
            }
        }

19 Source : BrokerClientExecutionHandler.cs
with MIT License
from 1iveowl

private async Task<IResourcePermissionResponse> GetResourceTokenThroughCache(IUserContext userContext, CancellationToken ct)
        {
            return await _resourceTokenCache.TryGetFromCache(
                userContext.UserIdentifier,
                RenewObjectFunc,
                IsCachedObjectValidFunc);

            // local function fetching a new Resource Permission Response from the Resource Token Broker
            // User the first time and whenever an existing Resource Permission Response object in the cache has expired.
           Task<IResourcePermissionResponse> RenewObjectFunc() => _brokerTransportClient.GetResourceToken(userContext.AccessToken, ct);

            // local function evaluating the validity of the object stored in the cache.
            static Task<bool> IsCachedObjectValidFunc(IResourcePermissionResponse cachedPermissionObj)
            {
                if (cachedPermissionObj is null)
                {
                    return Task.FromResult(false);
                }

                // Get the Permission that is closed to expire.
                var expires = cachedPermissionObj.ResourcePermissions?.OrderBy(resourcePermission => resourcePermission.ExpiresUtc)
                    .FirstOrDefault()
                    ?.ExpiresUtc ?? default;

                // Set expiration permission five minutes before actual expiration to be on safe side. 
                return Task.FromResult(DateTime.UtcNow <= expires - TimeSpan.FromMinutes(5));
            }
        }

19 Source : IdleBus`1.Test.cs
with MIT License
from 2881099

public static void Test()
        {
            //超过1分钟没有使用,连续检测2次都这样,就销毁【实例】
            var ib = new IdleBus<string, IDisposable>(TimeSpan.FromMinutes(1));
            ib.Notice += (_, e) =>
            {
                var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e.Log}";
                //Trace.WriteLine(log);
                Console.WriteLine(log);
            };

            ib.Register("key1", () => new ManualResetEvent(false));
            ib.Register("key2", () => new AutoResetEvent(false));

            var item = ib.Get("key2") as AutoResetEvent;
            //获得 key2 对象,创建

            item = ib.Get("key2") as AutoResetEvent;
            //获得 key2 对象,已创建

            int num1 = ib.UsageQuanreplacedy;
            //【实例】有效数量(即已经创建了的),后台定时清理不活跃的【实例】,此值就会减少

            ib.Dispose();
        }

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

public override void PreInitialize()
        {
            Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30);
            Configuration.UnitOfWork.IsTransactional = false;

            // Disable static mapper usage since it breaks unit tests (see https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2052)
            Configuration.Modules.AbpAutoMapper().UseStaticMapper = false;

            Configuration.BackgroundJobs.IsJobExecutionEnabled = false;

            // Use database for language management
            Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();

            RegisterFakeService<AbpZeroDbMigrator<BookListDbContext>>();

            Configuration.ReplaceService<IEmailSender, NullEmailSender>(DependencyLifeStyle.Transient);
        }

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

public override void PreInitialize()
        {
            Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30);
            Configuration.UnitOfWork.IsTransactional = false;

            // Disable static mapper usage since it breaks unit tests (see https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2052)
            Configuration.Modules.AbpAutoMapper().UseStaticMapper = false;

            Configuration.BackgroundJobs.IsJobExecutionEnabled = false;

            // Use database for language management
            Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();

            RegisterFakeService<AbpZeroDbMigrator<PhoneBookDbContext>>();

            Configuration.ReplaceService<IEmailSender, NullEmailSender>(DependencyLifeStyle.Transient);
        }

19 Source : BaseDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<List<TEnreplacedy>> GetAllFromCache()
        {
            var key = $"{typeof(TEnreplacedy).Name}_List";
            return await _cache.GetOrCreateAsync(key, async p => {
                p.SetAbsoluteExpiration(TimeSpan.FromMinutes(CacheKey.ExpireMinutes));
                return (await _repository.GetAll()).ToList();
            });
        }

19 Source : BaseDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<TEnreplacedy> GetFromCache(int id)
        {
            var key = $"{typeof(TEnreplacedy).Name}_{id}";
            return await _cache.GetOrCreateAsync(key, async p => {
                p.SetAbsoluteExpiration(TimeSpan.FromMinutes(CacheKey.ExpireMinutes));
                return await _repository.Get(id);
            });
        }

19 Source : PlayerQuestDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<List<PlayerQuestEnreplacedy>> GetPlayerQuests(int playerId)
        {
            var key = string.Format(CacheKey.PlayerQuestList, playerId);
            return await _cache.GetOrCreateAsync(key, async p => {
                p.SetAbsoluteExpiration(TimeSpan.FromMinutes(CacheKey.ExpireMinutes));
                return (await _questRepository.GetAll(x => x.PlayerId == playerId)).ToList();
            });
        }

19 Source : SkillDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<List<SkillEnreplacedy>> GetAllBaseSkills()
        {
            var key = CacheKey.BaseSkills;
            return await _cache.GetOrCreateAsync(key, async p => {
                p.SetAbsoluteExpiration(TimeSpan.FromMinutes(CacheKey.ExpireMinutes));
                return (await _skillRepository.GetAll(x => x.IsBase)).ToList();
            });
        }

19 Source : PriceViewActor.cs
with Apache License 2.0
from Aaronontheweb

protected override void PreStart()
        {
            Context.SetReceiveTimeout(TimeSpan.FromSeconds(5.0));
            _priceActorGateway.Tell(new FetchPriceAndVolume(_tickerSymbol));
            _pruneTimer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromMinutes(5),
                TimeSpan.FromMinutes(5), Self, Prune.Instance, ActorRefs.NoSender);
        }

19 Source : RuntimeTests.cs
with MIT License
from abdullin

[Test]
        public void RebootTest() {
            var bootCount = 0;

            var test = new TestDef() {
                MaxTime = 2.Minutes(),
                MaxInactive = 2.Minutes()
            };

            test.AddScript("com:test", async env => {
                bootCount++;
                while (!env.Token.IsCancellationRequested) {
                    await env.SimulateWork(100.Ms());
                }
            });
            
            test.Run(async plan => {
                plan.StartServices();
                await plan.Delay(TimeSpan.FromMinutes(1));
                await plan.StopServices();
                plan.StartServices();
            });

            replacedert.AreEqual(2, bootCount);
        }

19 Source : RuntimeTests.cs
with MIT License
from abdullin

[Test]
        public void NonResponsiveServiceIsKilledWithoutMercy() {
            var test = new TestDef {
                MaxTime = TimeSpan.FromMinutes(1)
            };

            var launched = true;
            var terminated = false;

            test.AddScript("com:test", async env => {
                launched = true;
                try {
                    while (!env.Token.IsCancellationRequested) {
                        await env.SimulateWork(10000.Ms());
                    }
                } finally {
                    // this should never hit
                    terminated = true;
                }
            });
            
            test.Run(async plan => {
                plan.StartServices();
                await plan.Delay(1.Sec());
                await plan.StopServices(grace:1.Sec());
            });
            
            replacedert.IsTrue(launched, nameof(launched));
            replacedert.IsFalse(terminated, nameof(terminated));
        }

19 Source : RuntimeTests.cs
with MIT License
from abdullin

[Test]
        public void StopResponsiveService() {
            var test = new TestDef {
                MaxTime = TimeSpan.FromMinutes(1)
            };

            
            var terminated = TimeSpan.Zero;

            test.AddScript("com:test", async env => {
                try {
                    while (!env.Token.IsCancellationRequested) {
                        await env.SimulateWork(10.Sec(), env.Token);
                    }
                } finally {
                    terminated = env.Time;
                }
            });
            
            test.Run(async plan => {
                plan.StartServices();
                await plan.Delay(TimeSpan.FromSeconds(1));
                await plan.StopServices();
            });
            
            replacedert.AreEqual(TimeSpan.FromSeconds(1), terminated);
        }

19 Source : Moment.cs
with MIT License
from abdullin

public static TimeSpan Minutes(this int min) {
            return TimeSpan.FromMinutes(min);
        }

19 Source : AggregationFiltersViewModel.cs
with MIT License
from ABTSoftware

private void UpdatePriceChart(AggregationPriceChart barStyle)
        {
            switch (barStyle)
            {
                case AggregationPriceChart.Count:
                    PriceSeries = (IOhlcDataSeries<DateTime, double>)_priceData.AggregateByCount(_selectedCount);
                    break;
                
                case AggregationPriceChart.Time:
                    PriceSeries = (IOhlcDataSeries<DateTime, double>)_priceData.AggregateByTime(TimeSpan.FromMinutes(_selectedTimeFrame));
                    break;
                
                case AggregationPriceChart.Volume:
                    PriceSeries = (IOhlcDataSeries<DateTime, double>)_priceData.AggregateByVolume(i =>_ticks[i].Volume.ToDouble(), _selectedVolume);
                    break;
                
                case AggregationPriceChart.Range:
                    PriceSeries = (IOhlcDataSeries<DateTime, double>)_priceData.AggregateByRange(_selectedRange);
                    break;
                
                case AggregationPriceChart.Renko:
                    PriceSeries = (IOhlcDataSeries<DateTime, double>)_priceData.AggregateByRenko(_selectedBrickSize);
                    break;
            }

            // Create a series for the 200 period SMA which will be plotted as a line chart
            Sma200Series = (IXyDataSeries<DateTime, double>)PriceSeries.ToMovingAverage(200);

            // Create a series for the 50 period SMA which will be plotted as a line chart
            Sma50Series = (IXyDataSeries<DateTime, double>)((IXyDataSeries<DateTime, double>)PriceSeries.ToMovingAverage(50)).Scale(1.001);

            _priceSeries.InvalidateParentSurface(RangeMode.ZoomToFit);
        }

19 Source : DocumentExtensions.cs
with Apache License 2.0
from acblog

public static TimeSpan GetReadTime(this Doreplacedent doreplacedent)
        {
            const int WordPerMinute = 500;
            return TimeSpan.FromMinutes(doreplacedent.CountWords() / (double)WordPerMinute);
        }

19 Source : Startup.cs
with Apache License 2.0
from acblog

public void ConfigureServices(IServiceCollection services)
        {
            {
                services.Configure<AppOptions>(Configuration.GetSection("Options"));
            }

            {
                services.AddDbContext<BlogDataContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

                services.AddScoped<IBlogService, AcBlog.Services.SqlServer.SqlServerBlogService>();

                // services.AddScoped<IPostRepository, AcBlog.Data.Repositories.SqlServer.PostRepository>();
            }
            {
                services.AddDbContext<ServiceDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("ServiceConnection")));

                // services.AddScoped<IPostRepository, AcBlog.Data.Repositories.SqlServer.PostRepository>();
            }
            {
                services.AddDbContext<IdenreplacedyDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("IdenreplacedyConnection")));

                services.AddDefaultIdenreplacedy<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
                    .AddEnreplacedyFrameworkStores<IdenreplacedyDbContext>();

                JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // avoid ms-default mapping, it will change sub claim's type name

                services.AddIdenreplacedyServer(Configuration.GetSection("IdenreplacedyServer:Options"))
                    .AddApiAuthorization<ApplicationUser, IdenreplacedyDbContext>();

                services.AddAuthentication()
                    .AddIdenreplacedyServerJwt();
            }

            services.AddHttpClient();

            services.AddDatabaseDeveloperPageExceptionFilter();

            /*{
                services.Configure<LomentServerOptions>(Configuration.GetSection("LomentServer"));
                services.AddHttpClient("loment-client", (sp, client) =>
                {
                    var options = sp.GetService<IOptions<LomentServerOptions>>().Value;
                    if (options.Enable)
                        client.BaseAddress = new Uri(options.Uri);
                });
                services.AddScoped<ILomentService>(sp =>
                {
                    var http = sp.GetRequiredService<IHttpClientFactory>().CreateClient("loment-client");
                    return new LomentService(http);
                });
            }*/

            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { replacedle = "AcBlog API", Version = "v1" });

                var apiKey = new OpenApiSecurityScheme
                {
                    Description = "JWT token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey
                };

                c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                {
                    Description =
                "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey,
                    In = ParameterLocation.Header,
                    Scheme = "Bearer"
                });

                var oar = new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "bearerAuth"
                            }
                        },
                        new List<string>()
                    }
                };
                c.AddSecurityRequirement(oar);
            });

            services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicy,
                    builder =>
                    {
                        builder.AllowAnyMethod();
                        builder.AllowAnyHeader();
                        builder.WithOrigins(Configuration.GetSection("Cors").Get<string[]>());
                    });
            });

            {
                services.AddHangfire(configuration => configuration
                    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                    .UseSimplereplacedemblyNameTypeSerializer()
                    .UseRecommendedSerializerSettings()
                    .UseSqlServerStorage(Configuration.GetConnectionString("ServiceConnection"), new SqlServerStorageOptions
                    {
                        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                        QueuePollInterval = TimeSpan.Zero,
                        UseRecommendedIsolationLevel = true,
                        DisableGlobalLocks = true,
                    }));

                // Add the processing server as IHostedService
                services.AddHangfireServer();
            }
        }

19 Source : UpgradeService.cs
with MIT License
from Accelerider

private async Task RunInternalAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                bool requiredRetry = false;
                try
                {
                    var tasks = _tasks.Values.ToArray();
                    foreach (var task in tasks)
                    {
                        await task.LoadFromLocalAsync();
                    }

                    var upgradeInfos = await _upgradeInfosGetter();

                    foreach (var task in tasks)
                    {
                        var info = upgradeInfos.FirstOrDefault(
                            item => item.Name.Equals(task.Name, StringComparison.InvariantCultureIgnoreCase));

                        if (info == null) continue;

                        await task.LoadFromRemoteAsync(info);
                    }
                }
                catch (Exception)
                {
                    requiredRetry = true;
                }

                try
                {
                    await Task.Delay(TimeSpan.FromMinutes(requiredRetry
                            ? RetryIntervalBaseMinute
                            : UpgradeIntervalBaseMinute),
                        token);
                }
                catch (TaskCanceledException)
                {
                    // Ignore
                }
            }
        }

19 Source : ShardDatabase.cs
with GNU Affero General Public License v3.0
from ACEmulator

public List<(uint start, uint end)> GetSequenceGaps(uint min, uint limitAvailableIDsReturned)
        {
            // References:
            // https://stackoverflow.com/questions/4340793/how-to-find-gaps-in-sequential-numbering-in-mysql/29736658#29736658
            // https://stackoverflow.com/questions/50402015/how-to-execute-sqlquery-with-enreplacedy-framework-core-2-1

            // This query is ugly, but very fast.
            var sql = "SET @available_ids=0, @rownum=0;"                                                + Environment.NewLine +
                      "SELECT"                                                                          + Environment.NewLine +
                      " z.gap_starts_at, z.gap_ends_at_not_inclusive, @available_ids:=@available_ids+(z.gap_ends_at_not_inclusive - z.gap_starts_at) as running_total_available_ids" + Environment.NewLine +
                      "FROM ("                                                                          + Environment.NewLine +
                      " SELECT"                                                                         + Environment.NewLine +
                      "  @rownum:=@rownum+1 AS gap_starts_at,"                                          + Environment.NewLine +
                      "  @available_ids:=0,"                                                            + Environment.NewLine +
                      "  IF(@rownum=id, 0, @rownum:=id) AS gap_ends_at_not_inclusive"                   + Environment.NewLine +
                      " FROM"                                                                           + Environment.NewLine +
                      "  (SELECT @rownum:=(SELECT MIN(id)-1 FROM biota WHERE id > " + min + ")) AS a"   + Environment.NewLine +
                      "  JOIN biota"                                                                    + Environment.NewLine +
                      "  WHERE id > " + min                                                             + Environment.NewLine +
                      "  ORDER BY id"                                                                   + Environment.NewLine +
                      " ) AS z"                                                                         + Environment.NewLine +
                      "WHERE z.gap_ends_at_not_inclusive!=0 AND @available_ids<" + limitAvailableIDsReturned + "; ";

            using (var context = new ShardDbContext())
            {
                context.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));

                var connection = context.Database.GetDbConnection();
                connection.Open();
                var command = connection.CreateCommand();
                command.CommandText = sql;
                var reader = command.ExecuteReader();

                var gaps = new List<(uint start, uint end)>();

                while (reader.Read())
                {
                    var gap_starts_at               = reader.GetFieldValue<long>(0);
                    var gap_ends_at_not_inclusive   = reader.GetFieldValue<decimal>(1);
                    //var running_total_available_ids = reader.GetFieldValue<double>(2);

                    gaps.Add(((uint)gap_starts_at, (uint)gap_ends_at_not_inclusive - 1));
                }

                return gaps;
            }
        }

19 Source : DatabaseManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Initialize(bool autoRetry = true)
        {
            Authentication.Exists(true);

            if (Authentication.GetListofAccountsByAccessLevel(ACE.Enreplacedy.Enum.AccessLevel.Admin).Count == 0)
            {
                log.Warn("Authentication Database does not contain any admin accounts. The next account to be created will automatically be promoted to an Admin account.");
                AutoPromoteNextAccountToAdmin = true;
            }
            else
                AutoPromoteNextAccountToAdmin = false;

            World.Exists(true);

            if (!World.IsWorldDatabaseGuidRangeValid())
            {
                log.Fatal("World Database contains instance GUIDs outside of static range which will prevent GuidManager from properly replacedigning GUIDs and can result in GUID exhaustion prematurely.");
                InitializationFailure = true;
                return;
            }

            var playerWeenieLoadTest = World.GetCachedWeenie("human");
            if (playerWeenieLoadTest == null)
            {
                log.Fatal("World Database does not contain the weenie for human (1). Characters cannot be created or logged into until the missing weenie is restored.");
                InitializationFailure = true;
                return;
            }

            // By default, we hold on to player biotas a little bit longer to help with offline updates like preplaced-up xp, allegiance updates, etc...
            var shardDb = new ShardDatabaseWithCaching(TimeSpan.FromMinutes(Common.ConfigManager.Config.Server.ShardPlayerBiotaCacheTime), TimeSpan.FromMinutes(Common.ConfigManager.Config.Server.ShardNonPlayerBiotaCacheTime));
            serializedShardDb = new SerializedShardDatabase(shardDb);
            Shard = serializedShardDb;

            shardDb.Exists(true);
        }

19 Source : DeveloperDatabaseCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator

[CommandHandler("database-shard-cache-pbrt", AccessLevel.Developer, CommandHandlerFlag.None, 0, "Shard Database, Player Biota Cache - Retention Time (in minutes)")]
        public static void HandleDatabaseShardCachePBRT(Session session, params string[] parameters)
        {
            if (!(DatabaseManager.Shard.BaseDatabase is ShardDatabaseWithCaching shardDatabaseWithCaching))
            {
                CommandHandlerHelper.WriteOutputInfo(session, "DatabaseManager is not using ShardDatabaseWithCaching");

                return;
            }

            if (parameters == null || parameters.Length == 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Player Biota Cache - Retention Time {shardDatabaseWithCaching.PlayerBiotaRetentionTime.TotalMinutes:N0} m");

                return;
            }

            if (!int.TryParse(parameters[0], out var value) || value < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, "Unable to parse argument. Specify retention time in integer minutes.");

                return;
            }

            shardDatabaseWithCaching.PlayerBiotaRetentionTime = TimeSpan.FromMinutes(value);

            CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Player Biota Cache - Retention Time {shardDatabaseWithCaching.PlayerBiotaRetentionTime.TotalMinutes:N0} m");
        }

19 Source : DeveloperDatabaseCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator

[CommandHandler("database-shard-cache-npbrt", AccessLevel.Developer, CommandHandlerFlag.None, 0, "Shard Database, Non-Player Biota Cache - Retention Time (in minutes)")]
        public static void HandleDatabaseShardCacheNPBRT(Session session, params string[] parameters)
        {
            if (!(DatabaseManager.Shard.BaseDatabase is ShardDatabaseWithCaching shardDatabaseWithCaching))
            {
                CommandHandlerHelper.WriteOutputInfo(session, "DatabaseManager is not using ShardDatabaseWithCaching");

                return;
            }

            if (parameters == null || parameters.Length == 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Non-Player Biota Cache - Retention Time {shardDatabaseWithCaching.NonPlayerBiotaRetentionTime.TotalMinutes:N0} m");

                return;
            }

            if (!int.TryParse(parameters[0], out var value) || value < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, "Unable to parse argument. Specify retention time in integer minutes.");

                return;
            }

            shardDatabaseWithCaching.NonPlayerBiotaRetentionTime = TimeSpan.FromMinutes(value);

            CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Non-Player Biota Cache - Retention Time {shardDatabaseWithCaching.NonPlayerBiotaRetentionTime.TotalMinutes:N0} m");
        }

19 Source : PlayerCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator

[CommandHandler("objsend", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, "Force resend of all visible objects known to this player. Can fix rare cases of invisible object bugs. Can only be used once every 5 mins max.")]
        public static void HandleObjSend(Session session, params string[] parameters)
        {
            // a good repro spot for this is the first room after the door in facility hub
            // in the portal drop / staircase room, the VisibleCells do not have the room after the door
            // however, the room after the door *does* have the portal drop / staircase room in its VisibleCells (the inverse relationship is imbalanced)
            // not sure how to fix this atm, seems like it triggers a client bug..

            if (DateTime.UtcNow - session.Player.PrevObjSend < TimeSpan.FromMinutes(5))
            {
                session.Player.SendTransientError("You have used this command too recently!");
                return;
            }

            var creaturesOnly = parameters.Length > 0 && parameters[0].Contains("creature", StringComparison.OrdinalIgnoreCase);

            var knownObjs = session.Player.GetKnownObjects();

            foreach (var knownObj in knownObjs)
            {
                if (creaturesOnly && !(knownObj is Creature))
                    continue;

                session.Player.RemoveTrackedObject(knownObj, false);
                session.Player.TrackObject(knownObj);
            }
            session.Player.PrevObjSend = DateTime.UtcNow;
        }

19 Source : ServerManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void ShutdownServer()
        {
            var shutdownTime = DateTime.UtcNow.AddSeconds(ShutdownInterval);

            ShutdownTime = shutdownTime;

            var lastNoticeTime = DateTime.UtcNow;

            // wait for shutdown interval to expire
            while (shutdownTime != DateTime.MinValue && shutdownTime >= DateTime.UtcNow)
            {
                // this allows the server shutdown to be canceled
                if (!ShutdownInitiated)
                {
                    // reset shutdown details
                    string shutdownText = $"The server has canceled the shutdown procedure @ {DateTime.UtcNow} UTC";
                    log.Info(shutdownText);

                    // special text
                    foreach (var player in PlayerManager.GetAllOnline())
                        player.Session.WorldBroadcast(shutdownText);

                    // break function
                    return;
                }

                lastNoticeTime = NotifyPlayersOfPendingShutdown(lastNoticeTime, shutdownTime.AddSeconds(1));

                Thread.Sleep(10);
            }

            ShutdownInProgress = true;

            PropertyManager.ResyncVariables();
            PropertyManager.StopUpdating();

            WorldManager.EnqueueAction(new ActionEventDelegate(() =>
            {
                log.Debug("Logging off all players...");

                // logout each player
                foreach (var player in PlayerManager.GetAllOnline())
                    player.Session.LogOffPlayer(true);
            }));

            // Wait for all players to log out
            var logUpdateTS = DateTime.MinValue;
            int playerCount;
            var playerLogoffStart = DateTime.UtcNow;
            while ((playerCount = PlayerManager.GetOnlineCount()) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {playerCount} player{(playerCount > 1 ? "s" : "")} to log off...");
                Thread.Sleep(10);
                if (playerCount > 0 && DateTime.UtcNow - playerLogoffStart > TimeSpan.FromMinutes(5))
                {
                    playerLogoffStart = DateTime.UtcNow;
                    log.Warn($"5 minute log off failsafe reached and there are {playerCount} player{(playerCount > 1 ? "s" : "")} still online.");
                    foreach (var player in PlayerManager.GetAllOnline())
                    {
                        log.Warn($"Player {player.Name} (0x{player.Guid}) appears to be stuck in world and unable to log off normally. Requesting Forced Logoff...");
                        player.ForcedLogOffRequested = true;
                        player.ForceLogoff();
                    }    
                }
            }

            WorldManager.EnqueueAction(new ActionEventDelegate(() =>
            {
                log.Debug("Disconnecting all sessions...");

                // disconnect each session
                NetworkManager.DisconnectAllSessionsForShutdown();
            }));

            // Wait for all sessions to drop out
            logUpdateTS = DateTime.MinValue;
            int sessionCount;
            while ((sessionCount = NetworkManager.GetAuthenticatedSessionCount()) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {sessionCount} authenticated session{(sessionCount > 1 ? "s" : "")} to disconnect...");
                Thread.Sleep(10);
            }

            log.Debug("Adding all landblocks to destruction queue...");

            // Queue unloading of all the landblocks
            // The actual unloading will happen in WorldManager.UpdateGameWorld
            LandblockManager.AddAllActiveLandblocksToDestructionQueue();

            // Wait for all landblocks to unload
            logUpdateTS = DateTime.MinValue;
            int landblockCount;
            while ((landblockCount = LandblockManager.GetLoadedLandblocks().Count) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {landblockCount} loaded landblock{(landblockCount > 1 ? "s" : "")} to unload...");
                Thread.Sleep(10);
            }

            log.Debug("Stopping world...");

            // Disabled thread update loop
            WorldManager.StopWorld();

            // Wait for world to end
            logUpdateTS = DateTime.MinValue;
            while (WorldManager.WorldActive)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, "Waiting for world to stop...");
                Thread.Sleep(10);
            }

            log.Info("Saving OfflinePlayers that have unsaved changes...");
            PlayerManager.SaveOfflinePlayersWithChanges();

            // Wait for the database queue to empty
            logUpdateTS = DateTime.MinValue;
            int shardQueueCount;
            while ((shardQueueCount = DatabaseManager.Shard.QueueCount) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for database queue ({shardQueueCount}) to empty...");
                Thread.Sleep(10);
            }

            // Write exit to console/log
            log.Info($"Exiting at {DateTime.UtcNow}");

            // System exit
            Environment.Exit(Environment.ExitCode);
        }

19 Source : MessageListener.cs
with MIT License
from actions

public async Task<TaskAgentMessage> GetNextMessageAsync(CancellationToken token)
        {
            Trace.Entering();
            ArgUtil.NotNull(_session, nameof(_session));
            ArgUtil.NotNull(_settings, nameof(_settings));
            bool encounteringError = false;
            int continuousError = 0;
            string errorMessage = string.Empty;
            Stopwatch heartbeat = new Stopwatch();
            heartbeat.Restart();
            while (true)
            {
                token.ThrowIfCancellationRequested();
                TaskAgentMessage message = null;
                try
                {
                    message = await _runnerServer.GetAgentMessageAsync(_settings.PoolId,
                                                                _session.SessionId,
                                                                _lastMessageId,
                                                                token);

                    // Decrypt the message body if the session is using encryption
                    message = DecryptMessage(message);

                    if (message != null)
                    {
                        _lastMessageId = message.MessageId;
                    }

                    if (encounteringError) //print the message once only if there was an error
                    {
                        _term.WriteLine($"{DateTime.UtcNow:u}: Runner reconnected.");
                        encounteringError = false;
                        continuousError = 0;
                    }
                }
                catch (OperationCanceledException) when (token.IsCancellationRequested)
                {
                    Trace.Info("Get next message has been cancelled.");
                    throw;
                }
                catch (TaskAgentAccessTokenExpiredException)
                {
                    Trace.Info("Runner OAuth token has been revoked. Unable to pull message.");
                    throw;
                }
                catch (Exception ex)
                {
                    Trace.Error("Catch exception during get next message.");
                    Trace.Error(ex);

                    // don't retry if SkipSessionRecover = true, DT service will delete agent session to stop agent from taking more jobs.
                    if (ex is TaskAgentSessionExpiredException && !_settings.SkipSessionRecover && await CreateSessionAsync(token))
                    {
                        Trace.Info($"{nameof(TaskAgentSessionExpiredException)} received, recovered by recreate session.");
                    }
                    else if (!IsGetNextMessageExceptionRetriable(ex))
                    {
                        throw;
                    }
                    else
                    {
                        continuousError++;
                        //retry after a random backoff to avoid service throttling
                        //in case of there is a service error happened and all agents get kicked off of the long poll and all agent try to reconnect back at the same time.
                        if (continuousError <= 5)
                        {
                            // random backoff [15, 30]
                            _getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), _getNextMessageRetryInterval);
                        }
                        else
                        {
                            // more aggressive backoff [30, 60]
                            _getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60), _getNextMessageRetryInterval);
                        }

                        if (!encounteringError)
                        {
                            //print error only on the first consecutive error
                            _term.WriteError($"{DateTime.UtcNow:u}: Runner connect error: {ex.Message}. Retrying until reconnected.");
                            encounteringError = true;
                        }

                        // re-create VssConnection before next retry
                        await _runnerServer.RefreshConnectionAsync(RunnerConnectionType.MessageQueue, TimeSpan.FromSeconds(60));

                        Trace.Info("Sleeping for {0} seconds before retrying.", _getNextMessageRetryInterval.TotalSeconds);
                        await HostContext.Delay(_getNextMessageRetryInterval, token);
                    }
                }

                if (message == null)
                {
                    if (heartbeat.Elapsed > TimeSpan.FromMinutes(30))
                    {
                        Trace.Info($"No message retrieved from session '{_session.SessionId}' within last 30 minutes.");
                        heartbeat.Restart();
                    }
                    else
                    {
                        Trace.Verbose($"No message retrieved from session '{_session.SessionId}'.");
                    }

                    continue;
                }

                Trace.Info($"Message '{message.MessageId}' received from session '{_session.SessionId}'.");
                return message;
            }
        }

19 Source : StepsRunner.cs
with MIT License
from actions

private async Task RunStepAsync(IStep step, CancellationToken jobCancellationToken)
        {
            // Check to see if we can expand the display name
            if (step is IActionRunner actionRunner &&
                actionRunner.Stage == ActionRunStage.Main &&
                actionRunner.TryEvaluateDisplayName(step.ExecutionContext.ExpressionValues, step.ExecutionContext))
            {
                step.ExecutionContext.UpdateTimelineRecordDisplayName(actionRunner.DisplayName);
            }

            // Start the step
            Trace.Info("Starting the step.");
            step.ExecutionContext.Debug($"Starting: {step.DisplayName}");

            // Set the timeout
            var timeoutMinutes = 0;
            var templateEvaluator = step.ExecutionContext.ToPipelineTemplateEvaluator();
            try
            {
                timeoutMinutes = templateEvaluator.EvaluateStepTimeout(step.Timeout, step.ExecutionContext.ExpressionValues, step.ExecutionContext.ExpressionFunctions);
            }
            catch (Exception ex)
            {
                Trace.Info("An error occurred when attempting to determine the step timeout.");
                Trace.Error(ex);
                step.ExecutionContext.Error("An error occurred when attempting to determine the step timeout.");
                step.ExecutionContext.Error(ex);
            }
            if (timeoutMinutes > 0)
            {
                var timeout = TimeSpan.FromMinutes(timeoutMinutes);
                step.ExecutionContext.SetTimeout(timeout);
            }

            await EncodingUtil.SetEncoding(HostContext, Trace, step.ExecutionContext.CancellationToken);

            try
            {
                await step.RunAsync();
            }
            catch (OperationCanceledException ex)
            {
                if (step.ExecutionContext.CancellationToken.IsCancellationRequested &&
                    !jobCancellationToken.IsCancellationRequested)
                {
                    Trace.Error($"Caught timeout exception from step: {ex.Message}");
                    step.ExecutionContext.Error("The action has timed out.");
                    step.ExecutionContext.Result = TaskResult.Failed;
                }
                else
                {
                    // Log the exception and cancel the step
                    Trace.Error($"Caught cancellation exception from step: {ex}");
                    step.ExecutionContext.Error(ex);
                    step.ExecutionContext.Result = TaskResult.Canceled;
                }
            }
            catch (Exception ex)
            {
                // Log the error and fail the step
                Trace.Error($"Caught exception from step: {ex}");
                step.ExecutionContext.Error(ex);
                step.ExecutionContext.Result = TaskResult.Failed;
            }

            // Merge execution context result with command result
            if (step.ExecutionContext.CommandResult != null)
            {
                step.ExecutionContext.Result = TaskResultUtil.MergeTaskResults(step.ExecutionContext.Result, step.ExecutionContext.CommandResult.Value);
            }

            // Fixup the step result if ContinueOnError
            if (step.ExecutionContext.Result == TaskResult.Failed)
            {
                var continueOnError = false;
                try
                {
                    continueOnError = templateEvaluator.EvaluateStepContinueOnError(step.ContinueOnError, step.ExecutionContext.ExpressionValues, step.ExecutionContext.ExpressionFunctions);
                }
                catch (Exception ex)
                {
                    Trace.Info("The step failed and an error occurred when attempting to determine whether to continue on error.");
                    Trace.Error(ex);
                    step.ExecutionContext.Error("The step failed and an error occurred when attempting to determine whether to continue on error.");
                    step.ExecutionContext.Error(ex);
                }

                if (continueOnError)
                {
                    step.ExecutionContext.Outcome = step.ExecutionContext.Result;
                    step.ExecutionContext.Result = TaskResult.Succeeded;
                    Trace.Info($"Updated step result (continue on error)");
                }
            }
            Trace.Info($"Step result: {step.ExecutionContext.Result}");

            // Complete the step context
            step.ExecutionContext.Debug($"Finishing: {step.DisplayName}");
        }

19 Source : JsonWebTokenUtilities.cs
with MIT License
from actions

internal static JWTAlgorithm ValidateSigningCredentials(VssSigningCredentials credentials, bool allowExpiredToken = false)
        {
            if (credentials == null)
            {
                return JWTAlgorithm.None;
            }

            if (!credentials.CanSignData)
            {
                throw new InvalidCredentialsException(JwtResources.SigningTokenNoPrivateKey());
            }

            if (!allowExpiredToken && credentials.ValidTo.ToUniversalTime() < (DateTime.UtcNow - TimeSpan.FromMinutes(5)))
            {
                throw new InvalidCredentialsException(JwtResources.SigningTokenExpired());
            }

            return credentials.SignatureAlgorithm;
        }

19 Source : JobDispatcherL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void DispatcherRenewJobRequestStopOnExpiredRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int poolId = 1;
                Int64 requestId = 1000;
                int count = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnExpiredRequest));
                TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request = new TaskAgentJobRequest();
                PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                replacedert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
                _runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(() =>
                            {
                                count++;
                                if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                                {
                                    trace.Info("First renew happens.");
                                }

                                if (count == 1)
                                {
                                    return Task.FromResult<TaskAgentJobRequest>(request);
                                }
                                else if (count < 5)
                                {
                                    throw new TimeoutException("");
                                }
                                else if (count == 5)
                                {
                                    lockUntilProperty.SetValue(request, DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(11)));
                                    throw new TimeoutException("");
                                }
                                else
                                {
                                    cancellationTokenSource.CancelAfter(10000);
                                    throw new InvalidOperationException("Should not reach here.");
                                }
                            });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);

                replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                replacedert.False(cancellationTokenSource.IsCancellationRequested);
                _runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
                _runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
                _runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Never);
            }
        }

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 : WorldManager.cs
with MIT License
from adamgoodrich

public double GetTimeDecimal()
        {
            return ((double)m_gameTime.Hour) + 
                TimeSpan.FromMinutes(m_gameTime.Minute).TotalHours + 
                TimeSpan.FromSeconds(m_gameTime.Second).TotalHours +
                TimeSpan.FromMilliseconds(m_gameTime.Millisecond).TotalHours;
        }

19 Source : OutputTests.cs
with Apache License 2.0
from adamralph

private static async Task Write(Output output, bool dryRun)
        {
            var badInput = new Target("badInput", "", Enumerable.Empty<string>());
            var badInputDuration = dryRun ? (TimeSpan?)null : TimeSpan.FromMilliseconds(1.234);
            var badInputEx = new InvalidOperationException("badInputEx");
            var badInputId = Guid.ParseExact("AA123".PadRight(32, '0'), "N");

            var badInputsTarget = new Target("badInputsTarget", "", Enumerable.Empty<string>());

            var badTarget = new Target("badTarget", "", Enumerable.Empty<string>());
            var badTargetDuration = dryRun ? (TimeSpan?)null : TimeSpan.FromMilliseconds(3.456);
            var badTargetEx = new InvalidOperationException("badTargetEx");

            var emptyTargets = Enumerable.Empty<Target>();

            var goodInput1 = new Target("goodInput1", "", Enumerable.Empty<string>());
            var goodInput2 = new Target("goodInput2", "", Enumerable.Empty<string>());
            var goodInputDuration1 = dryRun ? (TimeSpan?)null : TimeSpan.FromSeconds(1.234);
            var goodInputDuration2 = dryRun ? (TimeSpan?)null : TimeSpan.FromSeconds(2.345);
            var goodInputId1 = Guid.ParseExact("BB123".PadRight(32, '0'), "N");
            var goodInputId2 = Guid.ParseExact("BB234".PadRight(32, '0'), "N");

            var goodInputsTarget = new Target("goodInputsTarget", "", Enumerable.Empty<string>());

            var goodTarget1 = new Target("goodTarget1", "", Enumerable.Empty<string>());
            var goodTarget2 = new Target("goodTarget2", "", Enumerable.Empty<string>());
            var goodTargetDuration1 = (TimeSpan?)null;
            var goodTargetDuration2 = dryRun ? (TimeSpan?)null : TimeSpan.FromMinutes(1.234);

            var looseInput = new Target("looseInput", "", Enumerable.Empty<string>());
            var looseInputDuration = (TimeSpan?)null;
            var looseInputId = Guid.ParseExact("CC123".PadRight(32, '0'), "N");

            var looseTarget = new Target("looseTarget", "", Enumerable.Empty<string>());

            var looseTargets = new List<Target> { new Target("looseTarget", "", Enumerable.Empty<string>()) };

            var noInputsTarget = new Target("noInputsTarget", "", Enumerable.Empty<string>());

            var targets = new List<Target>
            {
                new Target("target1", "", Enumerable.Empty<string>()),
                new Target("target2", "", Enumerable.Empty<string>()),
                new Target("target3", "", Enumerable.Empty<string>()),
            };

            var verboseTargets = new Queue<Target>(
                new[]
                {
                    new Target("verboseTarget1", "", Enumerable.Empty<string>()),
                    new Target("verboseTarget2", "", Enumerable.Empty<string>()),
                    new Target("verboseTarget3", "", Enumerable.Empty<string>()),
                });

            var version = "version";

            await output.Header(() => version);

            await output.Awaiting(verboseTargets.Last(), verboseTargets);
            await output.WalkingDependencies(verboseTargets.Last(), verboseTargets);

            await output.Succeeded(emptyTargets);

            await output.Succeeded(looseTarget, looseInput, looseInputDuration, looseInputId, verboseTargets);
            await output.Succeeded(looseTargets);

            await output.Starting(targets);
            {
                await output.NoInputs(noInputsTarget, verboseTargets);

                await output.Succeeded(goodTarget1, verboseTargets, goodTargetDuration1);

                await output.Starting(goodTarget2, verboseTargets);
                await output.Succeeded(goodTarget2, verboseTargets, goodTargetDuration2);

                await output.Starting(badTarget, verboseTargets);
                {
                    await output.Error(badTarget, badTargetEx);
                }
                await output.Failed(badTarget, badTargetEx, badTargetDuration, verboseTargets);

                await output.Starting(goodInputsTarget, verboseTargets);
                {
                    await output.Starting(goodInputsTarget, goodInput1, goodInputId1, verboseTargets);
                    await output.Succeeded(goodInputsTarget, goodInput1, goodInputDuration1, goodInputId1, verboseTargets);

                    await output.Starting(goodInputsTarget, goodInput2, goodInputId2, verboseTargets);
                    await output.Succeeded(goodInputsTarget, goodInput2, goodInputDuration2, goodInputId2, verboseTargets);
                }
                await output.Succeeded(goodInputsTarget, verboseTargets);

                await output.Starting(badInputsTarget, verboseTargets);
                {
                    await output.Starting(badInputsTarget, goodInput1, goodInputId1, verboseTargets);
                    await output.Succeeded(badInputsTarget, goodInput1, goodInputDuration1, goodInputId1, verboseTargets);

                    await output.Starting(badInputsTarget, badInput, badInputId, verboseTargets);
                    {
                        await output.Error(badInputsTarget, badInput, badInputEx);
                    }
                    await output.Failed(badInputsTarget, badInput, badInputEx, badInputDuration, badInputId, verboseTargets);
                }
                await output.Failed(badInputsTarget, verboseTargets);
            }
            await output.Succeeded(targets);
            await output.Failed(targets);
        }

19 Source : Startup.cs
with MIT License
from AdemCatamak

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {replacedle = "SampleWebApi", Version = "v1"}); });
            
            services.AddScoped<IEmailSender, ConsoleEmailSender>();

            services.AddSingleton<IConnectionFactory>(provider => new SqlServerConnectionFactory(provider.GetRequiredService<IConfiguration>()
                                                                                                         .GetConnectionString("SqlServerConnectionString")));

            services.AddMessageStorage(configurator =>
                     {
                         configurator.UseSqlServer(provider => provider.GetRequiredService<IConfiguration>()
                                                                       .GetConnectionString("SqlServerConnectionString"),
                                                   "use_transaction_schema");

                         configurator.Register<AccountCreated_SendWelcomeEmail>(metaData =>
                         {
                             metaData.UseRetry(5, TimeSpan.FromMinutes(5));
                             metaData.UseRescue(TimeSpan.FromMinutes(30));
                         });
                     })
                    .AddMessageStoragePrerequisiteExecutor()
                    .AddMessageStorageJobDispatcher(waitAfterJobNotHandled: TimeSpan.FromSeconds(10));
        }

19 Source : JobRescuer_RescueAsync_Test.cs
with MIT License
from AdemCatamak

[Fact]
        public async Task When_ThereIsNoAnyJobToRescue_JobsStatusNotChange()
        {
            _messageHandlerMetadata.UseRescue(TimeSpan.FromMinutes(30));

            var jobList = new List<Job>
            {
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Completed, DateTime.UtcNow, DateTime.UtcNow, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.InProgress, DateTime.UtcNow, DateTime.UtcNow, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Queued, DateTime.UtcNow, DateTime.UtcNow, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Failed, DateTime.UtcNow, DateTime.UtcNow, "", 5, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), "message_handler_other", JobStatus.Failed, new DateTime(2020, 01, 01, 0, 0, 0), DateTime.UtcNow, "", 0, DateTime.UtcNow)
            };
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            foreach (Job job in jobList)
            {
                await jobRepository.AddAsync(job);
            }

            await _sut.RescueAsync(_messageHandlerMetadata.RescueOption ?? throw new ArgumentNullException(nameof(_messageHandlerMetadata.RetryOption)));

            await using NpgsqlConnection connection = new NpgsqlConnection(_repositoryFactory.RepositoryConfiguration.ConnectionString);
            for (int i = 0; i < jobList.Count; i++)
            {
                var job = jobList[i];
                string script = $"SELECT job_status FROM {SCHEMA}.jobs WHERE id = @id";
                var jobStatus = await connection.QueryFirstAsync<int>(script,
                                                                      new
                                                                      {
                                                                          id = job.Id
                                                                      }
                                                                     );
                string message = $"Expected : {(int) job.JobStatus}{Environment.NewLine}" +
                                 $"Actual : {jobStatus}{Environment.NewLine}" +
                                 $"Job Index : {i}";

                _output.WriteLine(message);
                replacedert.Equal((int) job.JobStatus, jobStatus);
            }
        }

19 Source : JobRescuer_RescueAsync_Test.cs
with MIT License
from AdemCatamak

[Fact]
        public async Task When_ThereIsJobToRescue_JobStatusChange()
        {
            TimeSpan timeout = TimeSpan.FromMinutes(60);
            _messageHandlerMetadata.UseRescue(timeout);
            _messageHandlerMetadata.UseRetry(2);

            var lastOperationTime = new DateTime(2020, 06, 10, 20, 10, 15);

            var jobList = new List<Job>()
            {
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.InProgress, DateTime.UtcNow, lastOperationTime, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.InProgress, DateTime.UtcNow, lastOperationTime, "", 5, DateTime.UtcNow),
            };

            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            foreach (Job job in jobList)
            {
                await jobRepository.AddAsync(job);
            }

            await _sut.RescueAsync(_messageHandlerMetadata.RescueOption);

            for (int i = 0; i < jobList.Count; i++)
            {
                Job job = jobList[i];

                await using NpgsqlConnection connection = new NpgsqlConnection(_repositoryFactory.RepositoryConfiguration.ConnectionString);
                string script = $"SELECT job_status FROM {SCHEMA}.jobs WHERE id = @id";
                var jobStatus = await connection.QueryFirstAsync<int>(script,
                                                                      new
                                                                      {
                                                                          id = job.Id
                                                                      }
                                                                     );

                string message = $"Expected : {(int) JobStatus.Queued}{Environment.NewLine}" +
                                 $"Actual : {jobStatus}{Environment.NewLine}" +
                                 $"Job Index : {i}{Environment.NewLine}";
                _output.WriteLine(message);

                replacedert.Equal((int) JobStatus.Queued, jobStatus);
            }
        }

19 Source : JobRetrier_RetryAsync_Test.cs
with MIT License
from AdemCatamak

[Fact]
        public async Task When_ThereIsJobToRetry_JobStatusChange()
        {
            TimeSpan deferTime = TimeSpan.FromMinutes(1);
            _messageHandlerMetadata.UseRetry(3, deferTime);
            var lastOperationTime = new DateTime(2021, 06, 10, 20, 10, 15);

            var job = new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Failed, DateTime.UtcNow, lastOperationTime, "", 0, DateTime.UtcNow);
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            await jobRepository.AddAsync(job);

            await _sut.RetryAsync(_messageHandlerMetadata.RetryOption ?? throw new ArgumentNullException(nameof(_messageHandlerMetadata.RetryOption)));

            await using SqlConnection connection = new SqlConnection(_repositoryFactory.RepositoryConfiguration.ConnectionString);
            string script = $"SELECT JobStatus, ExecuteLaterThan FROM {SCHEMA}.jobs WHERE id = @id";
            var tuple = await connection.QueryFirstAsync<(int, DateTime)>(script,
                                                                          new
                                                                          {
                                                                              id = job.Id
                                                                          }
                                                                         );

            replacedert.Equal((int) JobStatus.Queued, tuple.Item1);
            replacedert.Equal(lastOperationTime.Add(deferTime), tuple.Item2, TimeSpan.FromSeconds(5));
        }

19 Source : JobRetrier_RetryAsync_Test.cs
with MIT License
from AdemCatamak

[Fact]
        public async Task When_ThereIsJobToRetry_JobStatusChange()
        {
            TimeSpan deferTime = TimeSpan.FromMinutes(1);
            _messageHandlerMetadata.UseRetry(3, deferTime);
            var lastOperationTime = new DateTime(2021, 06, 10, 20, 10, 15);

            var job = new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Failed, DateTime.UtcNow, lastOperationTime, "", 0, DateTime.UtcNow);
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            await jobRepository.AddAsync(job);

            await _sut.RetryAsync(_messageHandlerMetadata.RetryOption ?? throw new ArgumentNullException(nameof(_messageHandlerMetadata.RetryOption)));

            await using NpgsqlConnection connection = new NpgsqlConnection(_repositoryFactory.RepositoryConfiguration.ConnectionString);
            string script = $"SELECT job_status, execute_later_than FROM {SCHEMA}.jobs WHERE id = @id";
            var tuple = await connection.QueryFirstAsync<(int, DateTime)>(script,
                                                                          new
                                                                          {
                                                                              id = job.Id
                                                                          }
                                                                         );

            replacedert.Equal((int) JobStatus.Queued, tuple.Item1);
            replacedert.Equal(lastOperationTime.Add(deferTime), tuple.Item2, TimeSpan.FromSeconds(5));
        }

19 Source : JobRescuer_RescueAsync_Test.cs
with MIT License
from AdemCatamak

[Fact]
        public async Task When_ThereIsNoAnyJobToRescue_JobsStatusNotChange()
        {
            _messageHandlerMetadata.UseRescue(TimeSpan.FromMinutes(30));

            var jobList = new List<Job>
            {
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Completed, DateTime.UtcNow, DateTime.UtcNow, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.InProgress, DateTime.UtcNow, DateTime.UtcNow, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Queued, DateTime.UtcNow, DateTime.UtcNow, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.Failed, DateTime.UtcNow, DateTime.UtcNow, "", 5, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), "message_handler_other", JobStatus.Failed, new DateTime(2020, 01, 01, 0, 0, 0), DateTime.UtcNow, "", 0, DateTime.UtcNow)
            };
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            foreach (Job job in jobList)
            {
                await jobRepository.AddAsync(job);
            }

            await _sut.RescueAsync(_messageHandlerMetadata.RescueOption ?? throw new ArgumentNullException(nameof(_messageHandlerMetadata.RetryOption)));

            await using SqlConnection connection = new SqlConnection(_repositoryFactory.RepositoryConfiguration.ConnectionString);
            for (int i = 0; i < jobList.Count; i++)
            {
                var job = jobList[i];

                string script = $"SELECT JobStatus FROM {SCHEMA}.jobs WHERE id = @id";
                var jobStatus = await connection.QueryFirstAsync<int>(script,
                                                                      new
                                                                      {
                                                                          id = job.Id
                                                                      }
                                                                     );

                string message = $"Expected : {(int) job.JobStatus}{Environment.NewLine}" +
                                 $"Actual : {jobStatus}{Environment.NewLine}" +
                                 $"Job Index : {i}";

                _output.WriteLine(message);
                replacedert.Equal((int) job.JobStatus, jobStatus);
            }
        }

19 Source : JobRescuer_RescueAsync_Test.cs
with MIT License
from AdemCatamak

[Fact]
        public async Task When_ThereIsJobToRetry_JobStatusChange()
        {
            TimeSpan timeout = TimeSpan.FromMinutes(60);
            _messageHandlerMetadata.UseRescue(timeout);
            _messageHandlerMetadata.UseRetry(2);

            var lastOperationTime = new DateTime(2020, 06, 10, 20, 10, 15);

            var jobList = new List<Job>()
            {
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.InProgress, DateTime.UtcNow, lastOperationTime, "", 0, DateTime.UtcNow),
                new Job(Guid.NewGuid(), new Message("payload"), _messageHandlerMetadata.MessageHandlerTypeName, JobStatus.InProgress, DateTime.UtcNow, lastOperationTime, "", 5, DateTime.UtcNow),
            };

            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            foreach (Job job in jobList)
            {
                await jobRepository.AddAsync(job);
            }

            await _sut.RescueAsync(_messageHandlerMetadata.RescueOption);

            for (int i = 0; i < jobList.Count; i++)
            {
                Job job = jobList[i];

                await using SqlConnection connection = new SqlConnection(_repositoryFactory.RepositoryConfiguration.ConnectionString);
                string script = $"SELECT JobStatus, ExecuteLaterThan FROM {SCHEMA}.jobs WHERE id = @id";
                var jobStatus = await connection.QueryFirstAsync<int>(script,
                                                                      new
                                                                      {
                                                                          id = job.Id
                                                                      }
                                                                     );

                string message = $"Expected : {(int) JobStatus.Queued}{Environment.NewLine}" +
                                 $"Actual : {jobStatus}{Environment.NewLine}" +
                                 $"Job Index : {i}{Environment.NewLine}";
                _output.WriteLine(message);

                replacedert.Equal((int) JobStatus.Queued, jobStatus);
            }
        }

19 Source : ContentMapProvider.cs
with MIT License
from Adoxio

private ContentMap GetContentMap(CrmDbContext context)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("LockTimeout={0}", this.LockTimeout));

			var sw = Stopwatch.StartNew();

			var solution = this.SolutionDefinitionProvider.GetSolution();
			var parameters = this.SolutionDefinitionProvider.GetQueryParameters();
			var map = new ContentMap(solution) { LockTimeout = this.LockTimeout.GetValueOrDefault(TimeSpan.FromMinutes(1)) };
			var enreplacedies = this.GetEnreplacedies(context, map.Solution, parameters).ToList();

			map.Using(ContentMapLockType.Write, () => this.BuildContentMap(map, enreplacedies));

			sw.Stop();

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Duration: {0} ms", sw.ElapsedMilliseconds));

			return map;
		}

19 Source : LoginManager.cs
with MIT License
from Adoxio

private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo, string userCacheKey, string userAuthResultCacheKey)
		{
			var client = this.GetGraphClient(loginInfo,
				PortalSettings.Instance.Authentication.RootUrl,
				PortalSettings.Instance.Authentication.TenantId);

			Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null;
			

			// retry tokenRetryCount times to retrieve the users. each time it fails, it will nullify the cache and try again
			for (var x = 0; x < TokenRetryCount; x++)
			{
				try
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Attempting to retrieve user from Graph with NameIdentifier {loginInfo.Login.ProviderKey}.");

					// when we call this, the client will try to retrieve a token from GetAuthTokenTask()
					user = await client.Me.ExecuteAsync();

					// if we get here then everything is alright. stop looping
					break;
				}
				catch (AggregateException ex)
				{
					var handled = false;

					foreach (var innerEx in ex.InnerExceptions)
					{
						if (innerEx.InnerException == null)
						{
							break;
						}

						// if the exception can be cast to a DataServiceClientException
						// NOTE: the version of Microsoft.Data.Services.Client MUST match the one Microsoft.Azure.ActiveDirectory.GraphClient uses (currently 5.6.4.0. 5.7.0.0 won't cast the exception correctly.)
						var clientException = innerEx.InnerException as DataServiceClientException;
						if (clientException?.StatusCode == (int)HttpStatusCode.Unauthorized)
						{
							ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Current GraphClient auth token didn't seem to work. Discarding...");

							// the token didn't seem to work. throw away cached token to retrieve new one
							this.HttpContext.Cache.Remove(TokenCacheKey);
							handled = true;
						}
					}

					if (!handled)
					{
						throw;
					}
				}
			}

			// if users is null here, we have a config problem where we can't get correct auth tokens despite repeated attempts
			if (user == null)
			{
				this.OutputGraphError(Enums.AzureADGraphAuthResults.AuthConfigProblem, userAuthResultCacheKey, loginInfo);
				return null;
			}

			// add cache entry for graph user object. it will expire in GraphCacheTtlMinutes minutes
			HttpRuntime.Cache.Add(userCacheKey, user, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);

			return user;
		}

19 Source : LoginManager.cs
with MIT License
from Adoxio

private Enums.AzureADGraphAuthResults OutputGraphError(Enums.AzureADGraphAuthResults result, string userAuthResultCacheKey, ExternalLoginInfo loginInfo)
		{
			// add cache entry for graph check result. it will expire in GraphCacheTtlMinutes minutes
			HttpRuntime.Cache.Add(userAuthResultCacheKey, result, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);

			switch (result)
			{
				case Enums.AzureADGraphAuthResults.UserNotFound:
					ADXTrace.Instance.TraceError(TraceCategory.Application, $"Azure AD didn't have the user with the specified NameIdentifier: {loginInfo.Login.ProviderKey}");

					return Enums.AzureADGraphAuthResults.UserNotFound;
				case Enums.AzureADGraphAuthResults.UserHasNoEmail:
					ADXTrace.Instance.TraceError(TraceCategory.Application, "UPN was not set on user.");

					return Enums.AzureADGraphAuthResults.UserHasNoEmail;
				case Enums.AzureADGraphAuthResults.NoValidLicense:
					ADXTrace.Instance.TraceError(TraceCategory.Application, $"No valid license was found replacedigned to the user: {loginInfo.Login.ProviderKey}");

					return Enums.AzureADGraphAuthResults.NoValidLicense;
				case Enums.AzureADGraphAuthResults.AuthConfigProblem:
					ADXTrace.Instance.TraceError(TraceCategory.Application, "There's a critical problem with retrieving Graph auth tokens.");

					return Enums.AzureADGraphAuthResults.AuthConfigProblem;
			}

			ADXTrace.Instance.TraceError(TraceCategory.Application, $"An unknown graph error occurred. Preplaceded through UserNotFound, UserHasNoEmail, and NoValidLicense. NameIdentifier: {loginInfo.Login.ProviderKey}");

			return Enums.AzureADGraphAuthResults.UnknownError;
		}

19 Source : BingAuthorization.cs
with MIT License
from adrenak

void CreateTimer() {
			if (m_TokenTimer != null)
				m_TokenTimer.Dispose();

			m_TokenTimer = new Timer(
				new TimerCallback(OnTokenExpiredCallback),
				this,
				TimeSpan.FromMinutes(k_RenewTimerDuration),
				TimeSpan.FromMilliseconds(-1)
			);
		}

19 Source : Startup.cs
with Apache License 2.0
from advanced-cms

public void Configuration(IAppBuilder app)
        {

            // Add CMS integration for ASP.NET Idenreplacedy
            app.AddCmsAspNetIdenreplacedy<ApplicationUser>();

            // Remove to block registration of administrators
            app.UseAdministratorRegistrationPage(() => HttpContext.Current.Request.IsLocal);

            // Use cookie authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString(Global.LoginPath),
                Provider = new CookieAuthenticationProvider
                {
                    // If the "/util/login.aspx" has been used for login otherwise you don't need it you can remove OnApplyRedirect.
                    OnApplyRedirect = cookieApplyRedirectContext =>
                    {
                        app.CmsOnCookieApplyRedirect(cookieApplyRedirectContext, cookieApplyRedirectContext.OwinContext.Get<ApplicationSignInManager<ApplicationUser>>());
                    },

                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a preplacedword or add an external login to your account.
                    OnValidateIdenreplacedy = SecurityStampValidator.OnValidateIdenreplacedy<ApplicationUserManager<ApplicationUser>, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdenreplacedy: (manager, user) => manager.GenerateUserIdenreplacedyAsync(user))
                }
            });
        }

19 Source : RedisLiteHelper.cs
with MIT License
from AElfProject

public static void Reset()
        {

            DefaultConnectTimeout = -1;
            DefaultSendTimeout = -1;
            DefaultReceiveTimeout = -1;
            DefaultRetryTimeout = 10 * 1000;
            DefaultIdleTimeOutSecs = 240;
            DefaultMaxPoolSize = null;
            BackOffMultiplier = 10;
            BufferPoolMaxSize = 500000;
            VerifyMasterConnections = true;
            HostLookupTimeoutMs = 200;
            replacedumeServerVersion = null;
            DeactivatedClientsExpiry = TimeSpan.FromMinutes(1);
            DisableVerboseLogging = false;
            replacedertAccessOnlyOnSameThread = false;
        }

19 Source : StackExchangeRedis.cs
with Mozilla Public License 2.0
from agebullhu

public bool SetNx(string key, byte[] value = null)
        {
            var re = Client.Execute("SetNx", key, value ?? new byte[0]);
            if (re.IsNull || (int)re != 1)
                return false;
            Client.KeyExpire(key, TimeSpan.FromMinutes(5));
            return true;
        }

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

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors()
                .AddAuthorization()
                .AddControllers();

            services.AddAuthentication(IdenreplacedyServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdenreplacedyServerAuthentication(options =>
                {
                    options.Authority = "https://localhost:5443";
                    options.RequireHttpsMetadata = false;
                    options.SupportedTokens = SupportedTokens.Both;
                    options.ApiName = "api1";
                    options.EnableCaching = true;
                    options.CacheDuration = TimeSpan.FromMinutes(10);
                    options.LegacyAudienceValidation = true;
                });
        }

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

public void ConfigureServices(IServiceCollection services)
        {
            var migrationsreplacedembly = typeof(Startup).GetTypeInfo().replacedembly.GetName().Name;
            var connectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(connectionString))
                .AddTheIdServerAdminEnreplacedyFrameworkStores(options =>
                    options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
                .AddConfigurationEnreplacedyFrameworkStores(options =>
                    options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
                .AddOperationalEnreplacedyFrameworkStores(options =>
                    options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)));

            var signalRBuilder = services.AddSignalR(options => Configuration.GetSection("SignalR:HubOptions").Bind(options));
            if (Configuration.GetValue<bool>("SignalR:UseMessagePack"))
            {
                signalRBuilder.AddMessagePackProtocol();
            }


            services.Configure<SendGridOptions>(Configuration)
                .AddControllersWithViews(options =>
            {
                options.AddIdenreplacedyServerAdminFilters();
            })
                .AddNewtonsoftJson(options =>
                {
                    var settings = options.SerializerSettings;
                    settings.NullValueHandling = NullValueHandling.Ignore;
                    settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                })
                .AddIdenreplacedyServerAdmin<ApplicationUser, SchemeDefinition>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(SharedConstants.WRITERPOLICY, policy =>
                {
                    policy.Requirereplacedertion(context =>
                       context.User.IsInRole(SharedConstants.WRITERPOLICY));
                });
                options.AddPolicy(SharedConstants.READERPOLICY, policy =>
                {
                    policy.Requirereplacedertion(context =>
                       context.User.IsInRole(SharedConstants.READERPOLICY));
                });
            })
                .AddAuthentication("Bearer")
                .AddIdenreplacedyServerAuthentication("Bearer", options =>
                {
                    options.Authority = "https://localhost:7443";
                    options.RequireHttpsMetadata = false;
                    options.SupportedTokens = IdenreplacedyServer4.AccessTokenValidation.SupportedTokens.Both;
                    options.ApiName = "theidserveradminapi";
                    options.ApiSecret = "5b556f7c-b3bc-4b5b-85ab-45eed0cb962d";
                    options.EnableCaching = true;
                    options.CacheDuration = TimeSpan.FromMinutes(10);
                    options.LegacyAudienceValidation = true;
                })
                .AddDynamic<SchemeDefinition>()
                .AddGoogle()
                .AddFacebook()
                .AddOpenIdConnect()
                .AddTwitter()
                .AddMicrosoftAccount()
                .AddOAuth("OAuth", options =>
                {
                });


            services.AddDatabaseDeveloperPageExceptionFilter()
                .AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });
        }

See More Examples