Here are the examples of the csharp api System.DateTime.Add(System.TimeSpan) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
961 Examples
19
View Source File : TokenAuthController.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null)
{
var now = DateTime.UtcNow;
var jwtSecurityToken = new JwtSecurityToken(
issuer: _configuration.Issuer,
audience: _configuration.Audience,
claims: claims,
notBefore: now,
expires: now.Add(expiration ?? _configuration.Expiration),
signingCredentials: _configuration.SigningCredentials
);
return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
19
View Source File : SystemDateTime.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
public static void AddToPausedTime(TimeSpan timeSpan)
{
_pausedUtcNow = _pausedUtcNow?.Add(timeSpan);
}
19
View Source File : RandomPricesDataSource.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private DateTime EmulateDateGap(DateTime candleOpenTime)
{
DateTime result = candleOpenTime;
TimeSpan timeOfDay = candleOpenTime.TimeOfDay;
if (timeOfDay > _closeMarketTime)
{
DateTime dateTime = candleOpenTime.Date;
dateTime = dateTime.AddDays(1.0);
result = dateTime.Add(_openMarketTime);
}
while (result.DayOfWeek == DayOfWeek.Saturday || result.DayOfWeek == DayOfWeek.Sunday)
{
result = result.AddDays(1.0);
}
return result;
}
19
View Source File : FileCache.cs
License : Apache License 2.0
Project Creator : acarteas
License : Apache License 2.0
Project Creator : acarteas
public override object Get(string key, string regionName = null)
{
FileCachePayload payload = CacheManager.ReadFile(PayloadReadMode, key, regionName) as FileCachePayload;
string cachedItemPath = CacheManager.GetCachePath(key, regionName);
DateTime cutoff = DateTime.Now;
if (PayloadReadMode == PayloadMode.Filename)
{
cutoff += FilenameAsPayloadSafetyMargin;
}
//null payload?
if (payload.Policy != null && payload.Payload != null)
{
//did the item expire?
if (payload.Policy.AbsoluteExpiration < cutoff)
{
//set the payload to null
payload.Payload = null;
//delete the file from the cache
try
{
// CT Note: I changed this to Remove from File.Delete so that the coresponding
// policy file will be deleted as well, and CurrentCacheSize will be updated.
Remove(key, regionName);
}
catch (Exception)
{
}
}
else
{
//does the item have a sliding expiration?
if (payload.Policy.SlidingExpiration > new TimeSpan())
{
payload.Policy.AbsoluteExpiration = DateTime.Now.Add(payload.Policy.SlidingExpiration);
WriteHelper(PayloadWriteMode, key, payload, regionName, true);
}
}
}
else
{
//remove null payload
Remove(key, regionName);
//create dummy one for return
payload = new FileCachePayload(null);
}
return payload.Payload;
}
19
View Source File : LandblockGroup.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public List<LandblockGroup> TrySplit()
{
if (IsDungeon)
return null;
var results = new List<LandblockGroup>();
var newLandblockGroup = DoTrySplit();
while (newLandblockGroup != null)
{
results.Add(newLandblockGroup);
newLandblockGroup = DoTrySplit();
}
NextTrySplitTime = DateTime.UtcNow.Add(TrySplitInterval);
uniqueLandblockIdsRemoved.Clear();
return results;
}
19
View Source File : SolarAnalysisManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private bool CreateShadowPlanViews(ModelSetupWizard.TransactionLog log)
{
var id = GetViewFamilyId(doc, ViewFamily.FloorPlan);
var levelId = GetHighestLevel(doc);
if (id == null || levelId == null) {
log.AddFailure("Could not gererate shadow plans. FamilyId or LevelId not found");
return false;
}
while (StartTime <= EndTime) {
using (var t = new Transaction(doc))
{
if (t.Start("Create Shadow Plans") == TransactionStatus.Started) {
View view = ViewPlan.Create(doc, id, levelId);
view.ViewTemplateId = ElementId.InvalidElementId;
var niceMinutes = "00";
if (StartTime.Minute > 0) {
niceMinutes = StartTime.Minute.ToString(CultureInfo.CurrentCulture);
}
var vname = "SHADOW PLAN - " + StartTime.ToShortDateString() + "-" + StartTime.Hour + "." +
niceMinutes;
view.Name = GetNiceViewName(doc, vname);
var sunSettings = view.SunAndShadowSettings;
sunSettings.StartDateAndTime = StartTime;
sunSettings.SunAndShadowType = SunAndShadowType.StillImage;
view.SunlightIntensity = 50;
log.AddSuccess("Shadow Plan created: " + vname);
t.Commit();
StartTime = StartTime.Add(ExportTimeInterval);
}
}
}
return true;
}
19
View Source File : SolarAnalysisManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private bool CreateWinterViews(ModelSetupWizard.TransactionLog log)
{
var id = GetViewFamilyId(doc, ViewFamily.ThreeDimensional);
// FIXME add error message here
if (id == null) {
log.AddFailure("Could not gererate 3d view. FamilyId not found");
return false;
}
while (StartTime <= EndTime)
{
using (var t = new Transaction(doc))
{
t.Start("Create Solar View");
View view = View3D.CreateIsometric(doc, id);
view.ViewTemplateId = ElementId.InvalidElementId;
var niceMinutes = "00";
if (StartTime.Minute > 0)
{
niceMinutes = StartTime.Minute.ToString(CultureInfo.CurrentCulture);
}
var vname = "SOLAR ACCESS - " + StartTime.ToShortDateString() + "-" + StartTime.Hour + "." +
niceMinutes;
view.Name = GetNiceViewName(doc, vname);
var sunSettings = view.SunAndShadowSettings;
sunSettings.StartDateAndTime = StartTime;
if (StartTime <= sunSettings.GetSunrise(StartTime).ToLocalTime() || StartTime >= sunSettings.GetSunset(EndTime).ToLocalTime())
{
doc.Delete(view.Id);
log.AddFailure("Cannot rotate a view that is not in daylight hours: " + vname);
StartTime = StartTime.Add(ExportTimeInterval);
continue;
}
sunSettings.SunAndShadowType = SunAndShadowType.StillImage;
t.Commit();
if (!RotateView(view)) {
doc.Delete(view.Id);
log.AddFailure("Could not rotate view: " + vname);
continue;
}
log.AddSuccess("View created: " + vname);
StartTime = StartTime.Add(ExportTimeInterval);
}
}
return true;
}
19
View Source File : VssOAuthJwtBearerAssertion.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public JsonWebToken GetBearerToken()
{
if (m_bearerToken != null)
{
return m_bearerToken;
}
else
{
var additionalClaims = new List<Claim>(this.AdditionalClaims ?? new Claim[0]);
if (!String.IsNullOrEmpty(m_subject))
{
additionalClaims.Add(new Claim(JsonWebTokenClaims.Subject, m_subject));
}
additionalClaims.Add(new Claim(JsonWebTokenClaims.TokenId, Guid.NewGuid().ToString()));
var nowUtc = DateTime.UtcNow;
return JsonWebToken.Create(m_issuer, m_audience, nowUtc, nowUtc.Add(BearerTokenLifetime), additionalClaims, m_signingCredentials);
}
}
19
View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : 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
View Source File : JobRetrier_RetryAsync_Test.cs
License : MIT License
Project Creator : AdemCatamak
License : MIT License
Project Creator : 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
View Source File : JobRetrier_RetryAsync_Test.cs
License : MIT License
Project Creator : AdemCatamak
License : MIT License
Project Creator : 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
View Source File : EventOccurrence.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static DateTime? GetEndTime(Enreplacedy eventSchedule, DateTime date)
{
var startTime = eventSchedule.GetAttributeValue<DateTime?>("adx_starttime");
var endTime = eventSchedule.GetAttributeValue<DateTime?>("adx_endtime");
return startTime.HasValue && endTime.HasValue && (endTime > startTime)
? new DateTime?(date.Add(endTime.Value - startTime.Value))
: null;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IEnumerable<DateTime> GetScheduledDates(this OrganizationServiceContext context, Enreplacedy evnt, TimeSpan duration)
{
return GetScheduledDates(context, evnt, DateTime.UtcNow, DateTime.UtcNow.Add(duration));
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IEnumerable<DateTime> GetDates(this OrganizationServiceContext context, Enreplacedy eventSchedule, TimeSpan timespan)
{
return GetDates(context, eventSchedule, DateTime.UtcNow, DateTime.UtcNow.Add(timespan));
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void SetResponseCachePolicy(
HttpCachePolicyElement policy,
HttpResponseBase response,
HttpCacheability defaultCacheability,
string defaultMaxAge = "01:00:00",
string defaultVaryByParams = null,
string defaultVaryByContentEncodings = null)
{
if (!string.IsNullOrWhiteSpace(policy.CacheExtension))
{
response.Cache.AppendCacheExtension(policy.CacheExtension);
}
var maxAge = policy.MaxAge ?? defaultMaxAge;
if (!string.IsNullOrWhiteSpace(maxAge))
{
var maxAgeSpan = TimeSpan.Parse(maxAge);
response.Cache.SetExpires(DateTime.Now.Add(maxAgeSpan));
response.Cache.SetMaxAge(maxAgeSpan);
}
if (!string.IsNullOrWhiteSpace(policy.Expires))
{
var expires = DateTime.Parse(policy.Expires);
response.Cache.SetExpires(expires);
}
var cacheability = policy.Cacheability != null ? policy.Cacheability.Value : defaultCacheability;
response.Cache.SetCacheability(cacheability);
if (policy.Revalidation != null)
{
response.Cache.SetRevalidation(policy.Revalidation.Value);
}
if (policy.SlidingExpiration != null)
{
response.Cache.SetSlidingExpiration(policy.SlidingExpiration.Value);
}
if (policy.ValidUntilExpires != null)
{
response.Cache.SetValidUntilExpires(policy.ValidUntilExpires.Value);
}
if (!string.IsNullOrWhiteSpace(policy.VaryByCustom))
{
response.Cache.SetVaryByCustom(policy.VaryByCustom);
}
// encoding based output caching should be disabled for annotations
var varyByContentEncodings = policy.VaryByContentEncodings == null || policy.VaryByContentEncodings == "gzip;x-gzip;deflate"
? defaultVaryByContentEncodings
: policy.VaryByContentEncodings;
if (!string.IsNullOrWhiteSpace(varyByContentEncodings))
{
ForEachParam(varyByContentEncodings, param => response.Cache.VaryByContentEncodings[param] = true);
}
if (!string.IsNullOrWhiteSpace(policy.VaryByHeaders))
{
ForEachParam(policy.VaryByHeaders, param => response.Cache.VaryByHeaders[param] = true);
}
var varyByParams = policy.VaryByParams ?? defaultVaryByParams;
if (!string.IsNullOrWhiteSpace(varyByParams))
{
ForEachParam(varyByParams, param => response.Cache.VaryByParams[param] = true);
}
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void SetResponseCachePolicy(
HttpCachePolicyElement policy,
HttpResponse response,
HttpCacheability defaultCacheability,
string defaultMaxAge = "01:00:00",
string defaultVaryByParams = null,
string defaultVaryByContentEncodings = null)
{
if (!string.IsNullOrWhiteSpace(policy.CacheExtension))
{
response.Cache.AppendCacheExtension(policy.CacheExtension);
}
var maxAge = policy.MaxAge ?? defaultMaxAge;
if (!string.IsNullOrWhiteSpace(maxAge))
{
var maxAgeSpan = TimeSpan.Parse(maxAge);
response.Cache.SetExpires(DateTime.Now.Add(maxAgeSpan));
response.Cache.SetMaxAge(maxAgeSpan);
}
if (!string.IsNullOrWhiteSpace(policy.Expires))
{
var expires = DateTime.Parse(policy.Expires);
response.Cache.SetExpires(expires);
}
var cacheability = policy.Cacheability != null ? policy.Cacheability.Value : defaultCacheability;
response.Cache.SetCacheability(cacheability);
if (policy.Revalidation != null)
{
response.Cache.SetRevalidation(policy.Revalidation.Value);
}
if (policy.SlidingExpiration != null)
{
response.Cache.SetSlidingExpiration(policy.SlidingExpiration.Value);
}
if (policy.ValidUntilExpires != null)
{
response.Cache.SetValidUntilExpires(policy.ValidUntilExpires.Value);
}
if (!string.IsNullOrWhiteSpace(policy.VaryByCustom))
{
response.Cache.SetVaryByCustom(policy.VaryByCustom);
}
var varyByContentEncodings = policy.VaryByContentEncodings ?? defaultVaryByContentEncodings;
if (!string.IsNullOrWhiteSpace(varyByContentEncodings))
{
ForEachParam(varyByContentEncodings, param => response.Cache.VaryByContentEncodings[param] = true);
}
if (!string.IsNullOrWhiteSpace(policy.VaryByHeaders))
{
ForEachParam(policy.VaryByHeaders, param => response.Cache.VaryByHeaders[param] = true);
}
var varyByParams = policy.VaryByParams ?? defaultVaryByParams;
if (!string.IsNullOrWhiteSpace(varyByParams))
{
ForEachParam(varyByParams, param => response.Cache.VaryByParams[param] = true);
}
}
19
View Source File : ChildEvents.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void Page_Load(object sender, EventArgs args)
{
var dataAdapter = new WebPageChildEventDataAdapter(Enreplacedy.ToEnreplacedyReference(), new PortalContextDataAdapterDependencies(Portal, PortalName));
var now = DateTime.UtcNow;
var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90));
var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));
var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray();
UpcomingEvents.DataSource = occurrences.Where(e => e.Start >= now).OrderBy(e => e.Start);
UpcomingEvents.DataBind();
PastEvents.DataSource = occurrences.Where(e => e.Start < now).OrderByDescending(e => e.Start);
PastEvents.DataBind();
}
19
View Source File : Event.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void Page_Load(object sender, EventArgs args)
{
var @event = _portal.Value.Enreplacedy;
if (@event == null || @event.LogicalName != "adx_event")
{
return;
}
var dataAdapter = new EventDataAdapter(@event, new PortalContextDataAdapterDependencies(_portal.Value, PortalName));
var now = DateTime.UtcNow;
var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90));
var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));
var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray();
IEventOccurrence requestOccurrence;
RequestEventOccurrence = dataAdapter.TryMatchRequestEventOccurrence(Request, occurrences, out requestOccurrence)
? requestOccurrence
: occurrences.Length == 1 ? occurrences.Single() : null;
var user = _portal.Value.User;
CanRegister = Request.IsAuthenticated && user != null && RequestEventOccurrence != null &&
RequestEventOccurrence.Start >= now && RequestEventOccurrence.EventSchedule != null &&
RequestEventOccurrence.Event != null;
RequiresRegistration = @event.GetAttributeValue<bool?>("adx_requiresregistration").GetValueOrDefault()
&& RequestEventOccurrence != null
&& RequestEventOccurrence.Start >= now;
RegistrationRequiresPayment =
_portal.Value.ServiceContext.CreateQuery("adx_eventproduct")
.Where(ep => ep.GetAttributeValue<EnreplacedyReference>("adx_event") == @event.ToEnreplacedyReference())
.ToList()
.Any();
if (CanRegister)
{
var registration = _portal.Value.ServiceContext.CreateQuery("adx_eventregistration")
.FirstOrDefault(e => e.GetAttributeValue<EnreplacedyReference>("adx_attendeeid") == user.ToEnreplacedyReference()
&& e.GetAttributeValue<EnreplacedyReference>("adx_eventscheduleid") == RequestEventOccurrence.EventSchedule.ToEnreplacedyReference()
&& e.GetAttributeValue<OptionSetValue>("statuscode") != null && e.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)EventStatusCode.Completed);
if (registration != null)
{
IsRegistered = true;
Unregister.CommandArgument = registration.Id.ToString();
}
}
OtherOccurrences.DataSource = occurrences
.Where(e => e.Start >= now)
.Where(e => RequestEventOccurrence == null || !(e.EventSchedule.Id == RequestEventOccurrence.EventSchedule.Id && e.Start == RequestEventOccurrence.Start));
OtherOccurrences.DataBind();
var sessionEvent = @event;
Speakers.DataSource = sessionEvent.GetRelatedEnreplacedies(_portal.Value.ServiceContext, new Relationship("adx_eventspeaker_event"))
.OrderBy(e => e.GetAttributeValue<string>("adx_name"));
Speakers.DataBind();
}
19
View Source File : Events.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void Page_Load(object sender, EventArgs args)
{
var dataAdapter = new WebsiteEventDataAdapter(new PortalContextDataAdapterDependencies(Portal, PortalName));
var now = DateTime.UtcNow;
var past = Html.TimeSpanSetting("Events/DisplayTimeSpan/Past").GetValueOrDefault(TimeSpan.FromDays(90));
var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));
var occurrences = dataAdapter.SelectEventOccurrences(now.Subtract(past), now.Add(future)).ToArray();
UpcomingEvents.DataSource = occurrences.Where(e => e.Start >= now).OrderBy(e => e.Start);
UpcomingEvents.DataBind();
PastEvents.DataSource = occurrences.Where(e => e.Start < now).OrderByDescending(e => e.Start);
PastEvents.DataBind();
}
19
View Source File : EventsPanel.ascx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void Page_Load(object sender, EventArgs e)
{
var dataAdapter = new WebsiteEventDataAdapter(new Adxstudio.Xrm.Cms.PortalContextDataAdapterDependencies(Portal));
var now = DateTime.UtcNow;
var future = Html.TimeSpanSetting("Events/DisplayTimeSpan/Future").GetValueOrDefault(TimeSpan.FromDays(90));
UpcomingEvents.DataSource = dataAdapter.SelectEventOccurrences(now, now.Add(future)).Take(Html.IntegerSetting("Home Event Count").GetValueOrDefault(3));
UpcomingEvents.DataBind();
}
19
View Source File : ExternalLinkPinCodeSecurityHandler.cs
License : Apache License 2.0
Project Creator : advanced-cms
License : Apache License 2.0
Project Creator : advanced-cms
public bool TryToSignIn(ExternalReviewLink externalReviewLink, string requestedPinCode)
{
// check if PIN code provided by user match link PIN code
var hash = PinCodeHashGenerator.Hash(requestedPinCode, externalReviewLink.Token);
if (externalReviewLink.PinCode != hash)
{
return false;
}
var user = HttpContext.Current.User;
// user is already authenticated. We need to add him new claims with access to link
if (user != null && user.Idenreplacedy != null && user.Idenreplacedy.IsAuthenticated && user.Idenreplacedy is ClaimsIdenreplacedy)
{
var idenreplacedy = (ClaimsIdenreplacedy)user.Idenreplacedy;
var claim = idenreplacedy.FindFirst("ExternalReviewTokens");
if (claim != null)
{
var tokens = new List<string>();
if (!string.IsNullOrEmpty(claim.Value))
{
tokens.AddRange(claim.Value.Split('|'));
}
tokens.Add(externalReviewLink.Token);
idenreplacedy.RemoveClaim(claim);
idenreplacedy.AddClaim(new Claim("ExternalReviewTokens", string.Join("|", tokens)));
}
else
{
idenreplacedy.AddClaim(new Claim("ExternalReviewTokens", externalReviewLink.Token));
}
var authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(idenreplacedy), new AuthenticationProperties() { IsPersistent = true });
}
else
{
// user is not authenticated, we need to authenticate and add claims to link
var userName = DateTime.Now.ToString("yyyyMMddmmhhss");
var claims = new List<Claim>();
// create required claims
claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
claims.Add(new Claim(ClaimTypes.Name, userName));
// custom – my serialized AppUserState object
claims.Add(new Claim("ExternalReviewTokens", externalReviewLink.Token));
var idenreplacedy = new ClaimsIdenreplacedy(claims, DefaultAuthenticationTypes.ApplicationCookie);
var authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.SignIn(new AuthenticationProperties()
{
AllowRefresh = true,
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.Add(_externalReviewOptions.PinCodeSecurity.AuthenticationCookieLifeTime),
RedirectUri = externalReviewLink.LinkUrl
}, idenreplacedy);
}
return true;
}
19
View Source File : ExternalReviewLinksRepository.cs
License : Apache License 2.0
Project Creator : advanced-cms
License : Apache License 2.0
Project Creator : advanced-cms
public ExternalReviewLink AddLink(ContentReference contentLink, bool isEditable, TimeSpan validTo,
int? projectId)
{
var externalReviewLink = new ExternalReviewLinkDds
{
ContentLink = contentLink,
IsEditable = isEditable,
ProjectId = projectId,
Token = Guid.NewGuid().ToString(),
ValidTo = DateTime.Now.Add(validTo)
};
GetStore().Save(externalReviewLink);
return _externalReviewLinkBuilder.FromExternalReview(externalReviewLink);
}
19
View Source File : RetryInterceptor.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private ClientInterceptorContext<TRequest, TResponse> BuildNewContext<TRequest, TResponse>(
ClientInterceptorContext<TRequest, TResponse> oldContext, TimeSpan timeout)
where TRequest : clreplaced
where TResponse : clreplaced
{
return new ClientInterceptorContext<TRequest, TResponse>(oldContext.Method, oldContext.Host,
oldContext.Options.WithDeadline(DateTime.UtcNow.Add(timeout)));
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Aerion
License : MIT License
Project Creator : Aerion
private static async Task<WaitingToken> GetValidWaitingTokenAsync(Client client)
{
var waitingToken = await RetryOnFailure(() => client.GetWaitingTokenAsync()).ConfigureAwait(false);
if (waitingToken.Delay == 0)
{
return waitingToken;
}
var waitingTokenDelay = TimeSpan.FromSeconds(waitingToken.Delay + 1);
Console.WriteLine(
$"Got waiting token, awaiting for {waitingTokenDelay} - until {DateTime.Now.Add(waitingTokenDelay).ToLongTimeString()}");
await Task.Delay(waitingTokenDelay).ConfigureAwait(false);
if (waitingToken.Token == null)
{
return await GetValidWaitingTokenAsync(client);
}
return waitingToken;
}
19
View Source File : SerialNumber.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static SerialNumber DeSerialize(string str, DateTime installTime)
{
SerialNumber sn = null;
if (!string.IsNullOrEmpty(str))
{
string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
if (ss.Length > 3)
{
var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
sn = new SerialNumber()
{
License = (LicenseType)Convert.ToInt32(ss[0]),
CreateTime = stm,
ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
MachineId = ss[3]
};
var span = sn.ExpireTime.Subtract(sn.CreateTime);
sn.CreateTime = installTime;
sn.ExpireTime = installTime.Add(span);
}
}
return sn;
}
19
View Source File : SerialNumber.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static SerialNumber DeSerialize(string licContent, string keyName, DateTime installTime)
{
SerialNumber sn = null;
if (!string.IsNullOrEmpty(licContent))
{
string[] ss = RSA.Decrypt(licContent, keyName).Split(',');
if (ss.Length > 4)
{
var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
sn = new SerialNumber()
{
LicenseType = (LicenseType)Convert.ToInt32(ss[0]),
CreateTime = stm,
ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
MachineId = ss[3],
MaxActivity = Convert.ToInt32(ss[4])
};
var span = sn.ExpireTime.Subtract(sn.CreateTime);
sn.CreateTime = installTime;
sn.ExpireTime = installTime.Add(span);
}
}
return sn;
}
19
View Source File : DataTimeUtil.cs
License : MIT License
Project Creator : aishang2015
License : MIT License
Project Creator : aishang2015
public static DateTime ConvertStringToDateTime(string timeStamp)
{
var intStamp = long.Parse(timeStamp);
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = intStamp * 10000000;
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
19
View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out DateTimeOffset dt)
{
long ticks;
TimeSpan offset;
DateTimeKind kind;
if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind))
{
dt = default(DateTime);
return false;
}
DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(ticks);
dt = new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset);
return true;
}
19
View Source File : CommitRefreshing.cs
License : Apache License 2.0
Project Creator : akkadotnet
License : Apache License 2.0
Project Creator : akkadotnet
public void UpdateRefreshDeadlines(IImmutableSet<TopicParreplacedion> topicParreplacedions)
{
_refreshDeadlines = _refreshDeadlines.Sereplacedems(topicParreplacedions.ToImmutableDictionary(p => p, p => DateTime.UtcNow.Add(_commitRefreshInterval)));
}
19
View Source File : Bangumi.cs
License : MIT License
Project Creator : AlaricGilbert
License : MIT License
Project Creator : AlaricGilbert
public static List<BangumiInfo> GetBangumiInfos(BangumiSeason bseason)
{
var result = new List<BangumiInfo>();
for (int i = 0;i<bseason.Result.Count;i++)
{
var daySeason = bseason.Result[i];
for (int j=0;j<daySeason.Seasons.Count;j++)
{
var season = daySeason.Seasons[j];
if (season.Is_published == 1||season.Delay==1)
continue;
long pubts = season.Pub_ts;
pubts *= 10000000;
DateTime t = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
t = t.Add(new TimeSpan(pubts)).ToLocalTime();
Console.WriteLine(season.Pub_index);
var binfo = new BangumiInfo
{
Cover = season.Cover,
SquareCover = season.Square_cover,
Index = season.Pub_index.Substring(1, season.Pub_index.Length - 2),
EpNumber = Convert.ToInt32(season.Ep_id),
SeasonId = season.Season_id,
replacedle = season.replacedle,
UpdateTime = t
};
result.Add(binfo);
}
}
return result;
}
19
View Source File : UnixTimestampUtils.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public static DateTime From(double timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Add(TimeSpan.FromSeconds(timestamp));
}
19
View Source File : UnixTimestampUtils.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public static DateTime FromMilliseconds(double timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Add(TimeSpan.FromMilliseconds(timestamp));
}
19
View Source File : UnixTimestampUtils.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public static DateTime From(long timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Add(TimeSpan.FromTicks(timestamp));
}
19
View Source File : ExperimentController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
[HttpGet("{id}/remainingTime")]
public IActionResult GetRemainingTime(int id)
{
var sim = _context.Experiments
.Include(s => s.ExperimentInstances)
.SingleOrDefault(s => s.Id == id);
if (sim == null)
{
return NotFound();
}
var workStarted = sim.ExperimentInstances
.Where(i => i.Status == ExperimentStatus.Finished || i.Status == ExperimentStatus.Error)
.Select(i => i.WorkStarted)
.DefaultIfEmpty().Min();
var avgTimeSpan = TimeSpan.FromTicks(Convert.ToInt64(sim.ExperimentInstances
.Where(i => i.Status == ExperimentStatus.Finished || i.Status == ExperimentStatus.Error)
.Select(i => (i.WorkFinished - i.WorkStarted).Ticks)
.DefaultIfEmpty().Average()));
var activeWorkers =
_context.Workers.Count(w => w.LastRequestTime > DateTime.UtcNow.AddTicks(-2 * avgTimeSpan.Ticks));
var remainingExperiments =
sim.ExperimentInstances.Count(
i => i.Status == ExperimentStatus.Pending || i.Status == ExperimentStatus.Running);
var estimatedRemainingTime = TimeSpan.FromMilliseconds(-1);
if (activeWorkers > 0)
{
estimatedRemainingTime = TimeSpan.FromTicks(avgTimeSpan.Ticks * remainingExperiments / activeWorkers);
}
var result = new
{
WorkStarted = workStarted,
ElapsedTime = DateTime.UtcNow - workStarted,
AverageTimeToCompletion = avgTimeSpan,
ActiveWorkerCount = activeWorkers,
RemainingExperimentCount = remainingExperiments,
EstimatedRemainingTime = estimatedRemainingTime,
EstimatedTimeOfCompletion = DateTime.UtcNow.Add(estimatedRemainingTime)
};
return new ObjectResult(result);
}
19
View Source File : VssClientCredentialClientStorage.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
private DateTime GetNewExpirationDateTime()
{
var now = DateTime.Now;
// Ensure we don't overflow the max DateTime value
var lease = Math.Min((DateTime.MaxValue - now.Add(TimeSpan.FromSeconds(1))).TotalSeconds, this._tokenLeaseInSeconds);
// ensure we don't have negative leases
lease = Math.Max(lease, 0);
return now.AddSeconds(lease);
}
19
View Source File : ConnectionStringTest.cs
License : MIT License
Project Creator : allantargino
License : MIT License
Project Creator : allantargino
[TestMethod]
public void BuildToken()
{
ServiceBusConnectionValues values = ServiceBusConnectionValues.CreateFromConnectionString(connectionString);
TimeSpan validFor = new TimeSpan(1,0,0);
DateTime expiresOn = DateTime.Now.Add(validFor);
ServiceBusToken token = ServiceBusTokenManager.GetToken(values, validFor.TotalSeconds);
replacedert.AreEqual(token.IsExpired, false);
replacedert.AreEqual(token.ExpiresOn > expiresOn, true);
replacedert.AreNotEqual(token.Value, string.Empty);
Trace.WriteLine(token.Value);
}
19
View Source File : TimeSpanExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static DateTime FromNow(this TimeSpan @this) => DateTime.Now.Add(@this);
19
View Source File : TimeSpanExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static DateTime UtcFromNow(this TimeSpan @this) => DateTime.UtcNow.Add(@this);
19
View Source File : JwtTokenMock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public static string GenerateAccessToken(string issuer, string app, TimeSpan tokenExpiry)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(AccessTokenClaimTypes.App, app, ClaimValueTypes.String, issuer));
ClaimsIdenreplacedy idenreplacedy = new ClaimsIdenreplacedy("AccessToken");
idenreplacedy.AddClaims(claims);
ClaimsPrincipal principal = new ClaimsPrincipal(idenreplacedy);
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(principal.Idenreplacedy),
Expires = DateTime.Now.Add(tokenExpiry),
SigningCredentials = GetAccesTokenCredentials(issuer),
Audience = "platform.altinn.no",
Issuer = issuer
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string tokenstring = tokenHandler.WriteToken(token);
return tokenstring;
}
19
View Source File : Scheduler.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public int ScheduleAt(DateTime time, AnkhAction action)
{
if (action == null)
throw new ArgumentNullException("action");
if (time.Kind == DateTimeKind.Utc)
time = time.ToLocalTime();
lock (_actions)
{
while (_actions.ContainsKey(time))
time = time.Add(TimeSpan.FromMilliseconds(1));
ActionItem ai = new ActionItem(unchecked(++_nextActionId), action);
_actions.Add(time, ai);
Reschedule();
return ai.Id;
}
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
public static DateTime GetOffsetTime(DateTime time)
{
return UserSettingsManager.UserSettings.TimeOffsetType switch
{
TimeOffsetType.None => time,
TimeOffsetType.Predefined => time.Add(UserSettingsManager.UserSettings.TimeOffset),
TimeOffsetType.UtcToLocalTime => time.ToLocalTime(),
TimeOffsetType.LocalTimeToUtc => time.ToUniversalTime(),
_ => time
};
19
View Source File : Scheduler.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
public static void StartNew<T>(TimeSpan interval, bool immediate = true) where T : IJob
{
var firstRunTime = immediate ? DateTime.Now : DateTime.Now.Add(interval);
StartNewAt<T>(firstRunTime, interval);
}
19
View Source File : ChartElement.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
internal static double GetIntervalSize(
double current,
double interval,
DateTimeIntervalType type,
Series series,
double intervalOffset,
DateTimeIntervalType intervalOffsetType,
bool forceIntIndex,
bool forceAbsInterval)
{
// AxisName is not date.
if( type == DateTimeIntervalType.Number || type == DateTimeIntervalType.Auto )
{
return interval;
}
// Special case for indexed series
if(series != null && series.IsXValueIndexed)
{
// Check point index
int pointIndex = (int)Math.Ceiling(current - 1);
if(pointIndex < 0)
{
pointIndex = 0;
}
if(pointIndex >= series.Points.Count || series.Points.Count <= 1)
{
return interval;
}
// Get starting and ending values of the closest interval
double adjuster = 0;
double xValue = series.Points[pointIndex].XValue;
xValue = AlignIntervalStart(xValue, 1, type, null);
double xEndValue = xValue + GetIntervalSize(xValue, interval, type);
xEndValue += GetIntervalSize(xEndValue, intervalOffset, intervalOffsetType);
xValue += GetIntervalSize(xValue, intervalOffset, intervalOffsetType);
if(intervalOffset < 0)
{
xValue = xValue + GetIntervalSize(xValue, interval, type);
xEndValue = xEndValue + GetIntervalSize(xEndValue, interval, type);
}
// The first point in the series
if(pointIndex == 0 && current < 0)
{
// Round the first point value depending on the interval type
DateTime dateValue = DateTime.FromOADate(series.Points[pointIndex].XValue);
DateTime roundedDateValue = dateValue;
switch(type)
{
case(DateTimeIntervalType.Years): // Ignore hours,...
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
case(DateTimeIntervalType.Months): // Ignore hours,...
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
case(DateTimeIntervalType.Days): // Ignore hours,...
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
case(DateTimeIntervalType.Hours): //
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, dateValue.Hour,
dateValue.Minute, 0);
break;
case(DateTimeIntervalType.Minutes):
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month,
dateValue.Day,
dateValue.Hour,
dateValue.Minute,
dateValue.Second);
break;
case(DateTimeIntervalType.Seconds):
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month,
dateValue.Day,
dateValue.Hour,
dateValue.Minute,
dateValue.Second,
0);
break;
case(DateTimeIntervalType.Weeks):
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
}
// The first point value is exactly on the interval boundaries
if(roundedDateValue.ToOADate() == xValue || roundedDateValue.ToOADate() == xEndValue)
{
return - current + 1;
}
}
// Adjuster of 0.5 means that position should be between points
++pointIndex;
while(pointIndex < series.Points.Count)
{
if(series.Points[pointIndex].XValue >= xEndValue)
{
if(series.Points[pointIndex].XValue > xEndValue && !forceIntIndex)
{
adjuster = -0.5;
}
break;
}
++pointIndex;
}
// If last point outside of the max series index
if(pointIndex == series.Points.Count)
{
pointIndex += series.Points.Count/5 + 1;
}
double size = (pointIndex + 1) - current + adjuster;
return (size != 0) ? size : interval;
}
// Non indexed series
else
{
DateTime date = DateTime.FromOADate(current);
TimeSpan span = new TimeSpan(0);
if(type == DateTimeIntervalType.Days)
{
span = TimeSpan.FromDays(interval);
}
else if(type == DateTimeIntervalType.Hours)
{
span = TimeSpan.FromHours(interval);
}
else if(type == DateTimeIntervalType.Milliseconds)
{
span = TimeSpan.FromMilliseconds(interval);
}
else if(type == DateTimeIntervalType.Seconds)
{
span = TimeSpan.FromSeconds(interval);
}
else if(type == DateTimeIntervalType.Minutes)
{
span = TimeSpan.FromMinutes(interval);
}
else if(type == DateTimeIntervalType.Weeks)
{
span = TimeSpan.FromDays(7.0 * interval);
}
else if(type == DateTimeIntervalType.Months)
{
// Special case handling when current date points
// to the last day of the month
bool lastMonthDay = false;
if(date.Day == DateTime.DaysInMonth(date.Year, date.Month))
{
lastMonthDay = true;
}
// Add specified amount of months
date = date.AddMonths((int)Math.Floor(interval));
span = TimeSpan.FromDays(30.0 * ( interval - Math.Floor(interval) ));
// Check if last month of the day was used
if(lastMonthDay && span.Ticks == 0)
{
// Make sure the last day of the month is selected
int daysInMobth = DateTime.DaysInMonth(date.Year, date.Month);
date = date.AddDays(daysInMobth - date.Day);
}
}
else if(type == DateTimeIntervalType.Years)
{
date = date.AddYears((int)Math.Floor(interval));
span = TimeSpan.FromDays(365.0 * ( interval - Math.Floor(interval) ));
}
// Check if an absolute interval size must be returned
double result = date.Add(span).ToOADate() - current;
if(forceAbsInterval)
{
result = Math.Abs(result);
}
return result;
}
}
19
View Source File : JwtToken.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static TokenInfoViewModel BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement)
{
var now = DateTime.Now;
// 实例化JwtSecurityToken
var jwt = new JwtSecurityToken(
issuer: permissionRequirement.Issuer,
audience: permissionRequirement.Audience,
claims: claims,
notBefore: now,
expires: now.Add(permissionRequirement.Expiration),
signingCredentials: permissionRequirement.SigningCredentials
);
// 生成 Token
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
//打包返回前台
var responseJson = new TokenInfoViewModel
{
success = true,
token = encodedJwt,
expires_in = permissionRequirement.Expiration.TotalSeconds,
token_type = "Bearer"
};
return responseJson;
}
19
View Source File : SplashWindow.xaml.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public async void StartFadeOut()
{
this.FadeOutStartTime = DateTime.Now.Add(SplashDuration);
await Task.Run(async () =>
{
while (DateTime.Now <= this.FadeOutStartTime || this.IsSustainFadeOut)
{
await Task.Delay(200);
}
});
await Application.Current.Dispatcher.InvokeAsync(
() => this.BeginAnimation(
Window.OpacityProperty,
this.OpacityAnimation),
DispatcherPriority.Normal);
}
19
View Source File : AdaptiveTimerService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private DateTime GetPlannedMeetingEnd()
{
Debug.replacedert(_meetingStartTimeUtc != null, "_meetingStartTimeUtc != null");
var lasreplacedem = _scheduleService.GetTalkScheduleItems().Last();
return _meetingStartTimeUtc.Value.Add(lasreplacedem.StartOffsetIntoMeeting + lasreplacedem.OriginalDuration);
}
19
View Source File : ConvertUtil.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
internal static double GetValueDouble(object v, bool ignoreBool = false, bool retNaN=false)
{
double d;
try
{
if (ignoreBool && v is bool)
{
return 0;
}
if (IsNumeric(v))
{
if (v is DateTime)
{
d = ((DateTime)v).ToOADate();
}
else if (v is TimeSpan)
{
d = DateTime.FromOADate(0).Add((TimeSpan)v).ToOADate();
}
else
{
d = Convert.ToDouble(v, CultureInfo.InvariantCulture);
}
}
else
{
d = retNaN ? double.NaN : 0;
}
}
catch
{
d = retNaN ? double.NaN : 0;
}
return d;
}
19
View Source File : ExcelRangeBase.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
internal static string FormatValue(object v, ExcelNumberFormatXml.ExcelFormatTranslator nf, string format, string textFormat)
{
if (v is decimal || TypeCompat.IsPrimitive(v))
{
double d;
try
{
d = Convert.ToDouble(v);
}
catch
{
return "";
}
if (nf.DataType == ExcelNumberFormatXml.eFormatType.Number)
{
if (string.IsNullOrEmpty(nf.FractionFormat))
{
return d.ToString(format, nf.Culture);
}
else
{
return nf.FormatFraction(d);
}
}
else if (nf.DataType == ExcelNumberFormatXml.eFormatType.DateTime)
{
var date = DateTime.FromOADate(d);
//return date.ToString(format, nf.Culture);
return GetDateText(date, format, nf.Culture);
}
}
else if (v is DateTime)
{
if (nf.DataType == ExcelNumberFormatXml.eFormatType.DateTime)
{
return GetDateText((DateTime)v, format, nf.Culture);
}
else
{
double d = ((DateTime)v).ToOADate();
if (string.IsNullOrEmpty(nf.FractionFormat))
{
return d.ToString(format, nf.Culture);
}
else
{
return nf.FormatFraction(d);
}
}
}
else if (v is TimeSpan)
{
if (nf.DataType == ExcelNumberFormatXml.eFormatType.DateTime)
{
return GetDateText(new DateTime(((TimeSpan)v).Ticks), format, nf.Culture);
//return new DateTime(((TimeSpan)v).Ticks).ToString(format, nf.Culture);
}
else
{
double d = new DateTime(0).Add((TimeSpan)v).ToOADate();
if (string.IsNullOrEmpty(nf.FractionFormat))
{
return d.ToString(format, nf.Culture);
}
else
{
return nf.FormatFraction(d);
}
}
}
else
{
if (textFormat == "")
{
return v.ToString();
}
else
{
return string.Format(textFormat, v);
}
}
return v.ToString();
}
19
View Source File : ExcelWorksheet.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
private string GetValueForXml(object v)
{
string s;
try
{
if (v is DateTime)
{
double sdv = ((DateTime)v).ToOADate();
if (Workbook.Date1904)
{
sdv -= ExcelWorkbook.date1904Offset;
}
s = sdv.ToString(CultureInfo.InvariantCulture);
}
else if (v is TimeSpan)
{
s = DateTime.FromOADate(0).Add(((TimeSpan)v)).ToOADate().ToString(CultureInfo.InvariantCulture);
}
else if(TypeCompat.IsPrimitive(v) || v is double || v is decimal)
{
if (v is double && double.IsNaN((double)v))
{
s = "";
}
else if (v is double && double.IsInfinity((double)v))
{
s = "#NUM!";
}
else
{
s = Convert.ToDouble(v, CultureInfo.InvariantCulture).ToString("R15", CultureInfo.InvariantCulture);
}
}
else
{
s = v.ToString();
}
}
catch
{
s = "0";
}
return s;
}
19
View Source File : ConvertUtil.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
internal static double GetValueDouble(object v, bool ignoreBool = false)
{
double d;
try
{
if (ignoreBool && v is bool)
{
return 0;
}
if (IsNumeric(v))
{
if (v is DateTime)
{
d = ((DateTime)v).ToOADate();
}
else if (v is TimeSpan)
{
d = DateTime.FromOADate(0).Add((TimeSpan)v).ToOADate();
}
else
{
d = Convert.ToDouble(v, CultureInfo.InvariantCulture);
}
}
else
{
d = 0;
}
}
catch
{
d = 0;
}
return d;
}
See More Examples