Here are the examples of the csharp api System.DateTime.Parse(string, System.IFormatProvider, System.Globalization.DateTimeStyles) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
619 Examples
19
View Source File : AuditTrailTests.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
[Fact]
public void AuditTrailPipeInText()
{
Fixture.CleanupAuditTable();
Repository<Employee> empRepo = new Repository<Employee>(Fixture.Connection);
Employee emp = new Employee
{
EmployeeName = "Rajesh",
Department = "AC|IT",
DOB = new DateTime(1980, 7, 22),
};
//add record
var id = empRepo.Add(emp);
//update record
emp.Department = "IT";
emp.DOB = new DateTime(1983, 7, 22);
empRepo.Update(emp);
//read history
var empHistory = empRepo.ReadHistory(id);
replacedert.Equal(2, empHistory.Count());
replacedert.Equal("Rajesh", empHistory.First().EmployeeName);
replacedert.Equal("AC|IT", empHistory.First().Department);
replacedert.Equal(new DateTime(1980, 7, 22), empHistory.First().DOB);
replacedert.Equal("IT", empHistory.ElementAt(1).Department);
replacedert.Equal(new DateTime(1983, 7, 22), empHistory.ElementAt(1).DOB);
AuditTrailRepository<Employee> auditRepo = new AuditTrailRepository<Employee>(Fixture.Connection);
//read audittrail
var history = auditRepo.ReadAllAuditTrail(id);
replacedert.Equal(2, history.Count);
replacedert.Equal("Rajesh", history.First().lstAuditTrailDetail.Find(p => p.ColumnName == "EmployeeName").NewValue);
replacedert.Equal("AC|IT", history.First().lstAuditTrailDetail.Find(p => p.ColumnName == "Department").NewValue);
replacedert.Equal(new DateTime(1980, 7, 22), DateTime.Parse(history.First().lstAuditTrailDetail.Find(p => p.ColumnName == "DOB").NewValue));
replacedert.Equal("IT", history.ElementAt(1).lstAuditTrailDetail.Find(p => p.ColumnName == "Department").NewValue);
replacedert.Equal("AC|IT", history.ElementAt(1).lstAuditTrailDetail.Find(p => p.ColumnName == "Department").OldValue);
replacedert.Equal(new DateTime(1983, 7, 22), DateTime.Parse(history.ElementAt(1).lstAuditTrailDetail.Find(p => p.ColumnName == "DOB").NewValue));
replacedert.Equal(new DateTime(1980, 7, 22), DateTime.Parse(history.ElementAt(1).lstAuditTrailDetail.Find(p => p.ColumnName == "DOB").OldValue));
}
19
View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public static DateTime DeserializeDateTime(Slice slice)
{
if (slice.IsNullOrEmpty) return DateTime.MinValue; //TODO: fail ?
byte type = slice[0];
switch (type)
{
case FdbTupleTypes.Nil:
{
return DateTime.MinValue;
}
case FdbTupleTypes.Utf8:
{ // we only support ISO 8601 dates. For ex: YYYY-MM-DDTHH:MM:SS.fffff"
string str = FdbTupleParser.ParseUnicode(slice);
return DateTime.Parse(str, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
}
case FdbTupleTypes.Double:
{ // Number of days since Epoch
const long UNIX_EPOCH_TICKS = 621355968000000000L;
//note: we can't user TimeSpan.FromDays(...) because it rounds to the nearest millisecond!
long ticks = UNIX_EPOCH_TICKS + (long)(FdbTupleParser.ParseDouble(slice) * TimeSpan.TicksPerDay);
return new DateTime(ticks, DateTimeKind.Utc);
}
}
// If we have an integer, we consider it to be a number of Ticks (Windows Only)
if (type <= FdbTupleTypes.IntPos8 && type >= FdbTupleTypes.IntNeg8)
{
return new DateTime(DeserializeInt64(slice), DateTimeKind.Utc);
}
throw new FormatException(String.Format("Cannot convert tuple segment of type 0x{0:X} into a DateTime", type));
}
19
View Source File : BankIdGetSessionUserAttributesExtensions.cs
License : MIT License
Project Creator : ActiveLogin
License : MIT License
Project Creator : ActiveLogin
public static DateTime GetNotBeforeDateTime(this BankIdGetSessionUserAttributes userAttributes)
{
return DateTime.Parse(userAttributes.NotBefore).ToUniversalTime();
}
19
View Source File : BankIdGetSessionUserAttributesExtensions.cs
License : MIT License
Project Creator : ActiveLogin
License : MIT License
Project Creator : ActiveLogin
public static DateTime GetNotAfterDateTime(this BankIdGetSessionUserAttributes userAttributes)
{
return DateTime.Parse(userAttributes.NotAfter).ToUniversalTime();
}
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 : ConfigurationExtensions.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
private static void HydrateInstance(ref object config, ConfigSection section)
{
var props = config.GetType().GetProperties();
foreach (var prop in props)
{
// Must have a set method for this to work, otherwise continue on
if (prop.SetMethod == null)
continue;
var entry = section.GetValue(prop.Name);
object? value = null;
if (typeof(string) == prop.PropertyType)
{
// We do NOT want to override value if nothing was provided
if(!string.IsNullOrEmpty(entry))
prop.SetValue(config, entry);
continue;
}
// We need to address collections a bit differently
// They can come in the form of "root:section:name" with a string representation OR
// "root:section:name:0" <--- this is not detectable when checking the above path
if (typeof(IEnumerable).IsreplacedignableFrom(prop.PropertyType))
{
value = string.IsNullOrEmpty(section.GetValue(prop.Name))
? section.Config
.GetSection(section.GetPath(prop.Name)).Get(prop.PropertyType)
: Newtonsoft.Json.JsonConvert.DeserializeObject(entry, prop.PropertyType);
if (value == null)
continue;
prop.SetValue(config, value);
}
// From this point onward we require the 'entry' value to have something useful
if (string.IsNullOrEmpty(entry))
continue;
try
{
// Primitive types are simple to convert
if (prop.PropertyType.IsPrimitive)
value = Convert.ChangeType(entry, prop.PropertyType);
else
{
// The following types require a different approach
if (prop.PropertyType.IsEnum)
value = Enum.Parse(prop.PropertyType, entry);
else if (typeof(TimeSpan) == prop.PropertyType)
value = TimeSpan.Parse(entry);
else if (typeof(DateTime) == prop.PropertyType)
value = DateTime.Parse(entry);
else if (typeof(DateTimeOffset) == prop.PropertyType)
value = DateTimeOffset.Parse(entry);
}
// Update value within our config instance
prop.SetValue(config, value);
}
catch (Exception ex)
{
Console.Error.WriteLine(
$"Unable to convert value of '{entry}' to type '{prop.PropertyType.Name}' for prop '{prop.Name}' in config '{config.GetType().Name}'\n\t\t{ex.Message}");
}
}
}
19
View Source File : ConversationController.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[APIProduces(typeof(FileHistoryViewModel))]
public async Task<IActionResult> FileHistory([Required] int id, [Required] int skipDates)
{
var user = await GetKahlaUser();
var conversation = await _dbContext
.Conversations
.Include(nameof(GroupConversation.Users))
.SingleOrDefaultAsync(t => t.Id == id);
if (conversation == null)
{
return this.Protocol(ErrorType.NotFound, $"Can not find conversation with id: {id}.");
}
if (!conversation.HasUser(user.Id))
{
return this.Protocol(ErrorType.Unauthorized, "You don't have any relationship with that conversation.");
}
var folders = await _foldersService
.ViewContentAsync(await _appsContainer.AccessToken(), _configuration["UserFilesSiteName"], $"conversation-{conversation.Id}");
var folder = folders.Value
.SubFolders
.OrderByDescending(t => DateTime.Parse(t.FolderName))
.Skip(skipDates)
.FirstOrDefault();
if (folder == null)
{
return this.Protocol(ErrorType.Gone, "No files sent that day.");
}
var filesInSubfolder = await _foldersService.ViewContentAsync(await _appsContainer.AccessToken(), _configuration["UserFilesSiteName"], $"conversation-{conversation.Id}/{folder.FolderName}");
return this.Protocol(new FileHistoryViewModel(filesInSubfolder.Value.Files.ToList())
{
Code = ErrorType.Success,
ShowingDateUTC = folder.FolderName,
Message = $"Successfully get all files that day in your conversation. Please download with pattern: '{_probeLocator.OpenFormat}'.",
SiteName = _configuration["UserFilesSiteName"],
RootPath = $"conversation-{conversation.Id}"
});
}
19
View Source File : RargbParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
public async Task<TorrentQueryResult> ParsePageForTorrentEntriesAsync(string pageContents)
{
return await Task.Run(() =>
{
try
{
_logger.Information("RARGB parsing");
var htmlAgility = LoadedHtmlDoreplacedent(pageContents);
var tableRows = htmlAgility.DoreplacedentNode.SelectNodes("//tr[@clreplaced='lista2']");//gets table rows that contain torrent data
if (NoTableEntries(tableRows))
return new TorrentQueryResult { IsLastPage = true };
var result = new List<TorrentEntry>();
foreach (var row in tableRows)
{
var columns = row.SelectNodes("td");
if(columns == null || columns.Count != DataColumnCount)
{
_logger.Warning($"Could not find all columns for torrent {Environment.NewLine} {row.OuterHtml}");
continue;
}
var replacedleNode = columns[RargbTorrentIndexer.Name]
.SelectSingleNode("a");
if (replacedleNode == null)
{
_logger.Warning($"Could not find replacedle node for torrent {Environment.NewLine} {columns[RargbTorrentIndexer.Name].OuterHtml}");
continue;
}
var replacedle = replacedleNode.InnerText;
if (string.IsNullOrEmpty(replacedle))//empty replacedle entry makes no sense. log and skip
{
_logger.Warning($"Empty replacedle from {Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var torrentUri = replacedleNode.Attributes.FirstOrDefault(a => a.Name == "href")?.Value;
if (string.IsNullOrEmpty(torrentUri))
{
_logger.Warning($"Empty torrent uri from{Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var magnetLink = string.Empty;
if (!int.TryParse(columns[RargbTorrentIndexer.Seeders].InnerText, out var seeders))
_logger.Warning($"Could not parse seeders {Environment.NewLine}{columns[RargbTorrentIndexer.Seeders].OuterHtml}");
if (!int.TryParse(columns[RargbTorrentIndexer.Leechers].InnerText, out var leechers))
_logger.Warning($"Could not parse leechers {Environment.NewLine}{columns[RargbTorrentIndexer.Leechers].OuterHtml}");
var date = columns[RargbTorrentIndexer.Date].InnerText;
var size = columns[RargbTorrentIndexer.Size].InnerText;
var uploader = columns[RargbTorrentIndexer.Uploader].InnerText;
var splitSize = size.Split(' ');
result.Add(new TorrentEntry
{
replacedle = replacedle,
TorrentUri = TrimUriStart(torrentUri),
TorrentMagnet = magnetLink,
Date = DateTime.Parse(date),
Size = new SizeEnreplacedy
{
Value = double.Parse(splitSize[0], CultureInfo.InvariantCulture),
Postfix = splitSize[1]
},
Uploader = uploader,
Seeders = seeders,
Leechers = leechers,
Source = TorrentSource.Rargb
});
}
var pagination = htmlAgility.DoreplacedentNode.SelectSingleNode("//div[@id='pager_links']");
return new TorrentQueryResult
{
TorrentEntries = result,
IsLastPage = IsLastPage(pagination)
};
}
catch(Exception ex)
{
_logger.Warning("RARGB parse exception", ex);
throw;
}
});
}
19
View Source File : IsoDateTimeConverter.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullableType(objectType);
#if !NET20
Type t = (nullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
#endif
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
if (reader.TokenType == JsonToken.Date)
{
#if !NET20
if (t == typeof(DateTimeOffset))
{
return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value);
}
// converter is expected to return a DateTime
if (reader.Value is DateTimeOffset)
{
return ((DateTimeOffset)reader.Value).DateTime;
}
#endif
return reader.Value;
}
if (reader.TokenType != JsonToken.String)
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
string dateText = reader.Value.ToString();
if (string.IsNullOrEmpty(dateText) && nullable)
{
return null;
}
#if !NET20
if (t == typeof(DateTimeOffset))
{
if (!string.IsNullOrEmpty(_dateTimeFormat))
{
return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
}
else
{
return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
}
}
#endif
if (!string.IsNullOrEmpty(_dateTimeFormat))
{
return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
}
else
{
return DateTime.Parse(dateText, Culture, _dateTimeStyles);
}
}
19
View Source File : TechLogFileReader.cs
License : MIT License
Project Creator : akpaevj
License : MIT License
Project Creator : akpaevj
private TechLogItem ParseRawItem(ReadOnlySpan<char> rawItem, CancellationToken cancellationToken = default)
{
var properties = new Dictionary<string, string>();
var item = new TechLogItem
{
FolderName = FolderName,
FileName = FileName,
EndPosition = _lastEventEndPosition
};
// set event end position no new line
_lastEventEndPosition = Position;
var dtd = ReadNextPropertyWithoutName(rawItem);
var dtEndIndex = dtd.LastIndexOf('-');
item.DateTime = DateTime.Parse(dtd[..dtEndIndex]);
item.EndTicks = item.DateTime.Ticks;
var position = dtEndIndex + 1;
var duration = ReadNextPropertyWithoutName(rawItem[position..]);
position += duration.Length + 1;
item.Duration = long.Parse(duration);
item.StartTicks = item.EndTicks - item.Duration * (TimeSpan.TicksPerMillisecond / 1000);
var eventName = ReadNextPropertyWithoutName(rawItem[position..]);
position += eventName.Length + 1;
item.EventName = eventName.ToString();
var level = ReadNextPropertyWithoutName(rawItem[position..]);
position += level.Length + 1;
item.Level = int.Parse(level);
while (!cancellationToken.IsCancellationRequested)
{
var propertyName = ReadPropertyName(rawItem[position..]);
position += propertyName.Length + 1;
propertyName = propertyName.Trim();
if (position >= rawItem.Length)
break;
if (propertyName == "")
continue;
var propertyValue = ReadPropertyValue(rawItem[position..]);
position += propertyValue.Length + 1;
propertyValue = propertyValue.Trim(new[] { '\'', '"' }).Trim();
if (!item.AllProperties.TryAdd(propertyName.ToString(), propertyValue.ToString()))
item.AllProperties.TryAdd(GetPropertyName(properties, propertyName), propertyValue.ToString());
if (position >= rawItem.Length)
break;
}
return item;
}
19
View Source File : HomeController.cs
License : MIT License
Project Creator : alanmacgowan
License : MIT License
Project Creator : alanmacgowan
private async Task<string> GetAccessToken()
{
var exp = await HttpContext.GetTokenAsync("expires_at");
var expires = DateTime.Parse(exp);
if (expires > DateTime.Now)
{
return await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
}
return await GetRefreshedAccessToken();
}
19
View Source File : SoftwareUpdater.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
public bool Check(bool debug = false) {
if (MainProgram.isCheckingForUpdate)
return false;
MainProgram.isCheckingForUpdate = true;
MainProgram.DoDebug("Checking for updates...");
string latestReleaseJson = null;
string latestBetaJson = null;
//Check and get latest
if (Properties.Settings.Default.LastOpenedDate.Date != DateTime.UtcNow.Date) {
releaseJsonUrl += "&daily_check";
betaJsonUrl += "&daily_check";
Properties.Settings.Default.LastOpenedDate = DateTime.UtcNow;
Properties.Settings.Default.Save();
}
try {
if (RemoteFileExists(releaseJsonUrl)) {
using (WebClient client = new WebClient()) {
latestReleaseJson = client.DownloadString(releaseJsonUrl);
}
if (latestReleaseJson == string.Empty) {
latestReleaseJson = null;
}
}
//Check and get beta
if (Properties.Settings.Default.BetaProgram && RemoteFileExists(betaJsonUrl)) {
using (WebClient client = new WebClient()) {
latestBetaJson = client.DownloadString(betaJsonUrl);
}
if (latestBetaJson == string.Empty)
latestBetaJson = null;
}
if (latestReleaseJson != null || latestBetaJson != null) {
Version newVersion = null,
latestRelease,
latestBeta;
if (latestReleaseJson != null && latestBetaJson != null) {
//Beta program enabled; check both release and beta for newest update
latestRelease = JsonConvert.DeserializeObject<Version>(latestReleaseJson);
latestBeta = JsonConvert.DeserializeObject<Version>(latestBetaJson);
if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) ||
DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate)) {
//Both latest release and beta is ahead of this current build
if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(latestBeta.datetime)) {
//Release is newest
newVersion = latestRelease;
} else {
//Beta is newest
newVersion = latestBeta;
}
} else {
//None of them are newer. Nothing new
MainProgram.DoDebug("Software up to date (beta program enabled)");
MainProgram.isCheckingForUpdate = false;
return false;
}
} else if (latestReleaseJson != null && latestBetaJson == null) {
//Only check latest
latestRelease = JsonConvert.DeserializeObject<Version>(latestReleaseJson);
if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) && latestRelease.version != MainProgram.softwareVersion) {
//Newer build
newVersion = latestRelease;
} else {
//Not new, move on
MainProgram.DoDebug("Software up to date");
MainProgram.isCheckingForUpdate = false;
return false;
}
} else if (latestReleaseJson == null && latestBetaJson != null) {
//Couldn't reach "latest" update, but beta-updates are enabled
latestBeta = JsonConvert.DeserializeObject<Version>(latestBetaJson);
if (latestBeta != null) {
if (DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate)) {
//Newer build
newVersion = latestBeta;
} else {
//Not new, move on
MainProgram.DoDebug("Software up to date (beta program enabled)");
MainProgram.isCheckingForUpdate = false;
return false;
}
}
} else {
MainProgram.DoDebug("Both release and beta is NULL, no new updates, or no contact to the server.");
}
if (newVersion != null && newVersion.version != MainProgram.softwareVersion) {
//New version available
MainProgram.DoDebug("New software version found (" + newVersion.version + ") [" + newVersion.type + "], current; " + MainProgram.softwareVersion);
DialogResult dialogResult = MessageBox.Show(Translator.__("new_version_found", "check_for_update").Replace("{version_num}", newVersion.version).Replace("{version_type}", newVersion.type), Translator.__("new_version_found_replacedle", "check_for_update") + " | " + MainProgram.messageBoxreplacedle, MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
if (dialogResult == DialogResult.Yes) {
MainProgram.DoDebug("User chose \"yes\" to install update");
DownloadFile(newVersion.installpath + "&upgrade=true");
} else if (dialogResult == DialogResult.No) {
MainProgram.DoDebug("User did not want to install update");
}
MainProgram.isCheckingForUpdate = false;
return true;
} else {
MainProgram.DoDebug("Software up to date");
if (debug)
MessageBox.Show(Translator.__("no_new_update", "check_for_update"), Translator.__("check_for_update_replacedle", "check_for_update") + " | " + MainProgram.messageBoxreplacedle, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
}
} else {
MainProgram.DoDebug("Could not reach the webserver (both 'release' and 'beta' json files couldn't be reached)");
if (debug)
MessageBox.Show(Translator.__("webservers_offline", "check_for_update"), Translator.__("check_for_update_replacedle", "check_for_update") + " | " + MainProgram.messageBoxreplacedle, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
}
} catch (Exception e) {
MainProgram.DoDebug("Failed to check for update (exception); " + e.Message + "; " + e.StackTrace);
}
MainProgram.isCheckingForUpdate = false;
return false;
}
19
View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void ExecuteOrder(Order order)
{
if (IsConnected == false)
{
return;
}
_osEngineOrders.Add(order);
string url = "https://www.bitstamp.net/api/v2";
if (order.Side == Side.Buy)
{
url += "/buy/";
}
else
{
url += "/sell/";
}
url += order.SecurityNameCode + "/";
BuySellResponse result = Execute((double)order.Volume, (double)order.Price, url);
if (result == null)
{
return;
}
SendLogMessage("order status: " + result.status + " " + result.reason, LogMessageType.System);
if (result.id != null)
{
Order newOrder = new Order();
newOrder.SecurityNameCode = order.SecurityNameCode;
newOrder.TimeCallBack = DateTime.Parse(result.datetime);
newOrder.NumberUser = order.NumberUser;
newOrder.NumberMarket = result.id;
newOrder.PortfolioNumber = order.PortfolioNumber;
newOrder.Side = order.Side;
newOrder.Price = order.Price;
newOrder.State = OrderStateType.Activ;
newOrder.Volume = order.Volume;
if (MyOrderEvent != null)
{
MyOrderEvent(newOrder);
}
}
else
{
Order newOrder = new Order();
newOrder.SecurityNameCode = order.SecurityNameCode;
newOrder.NumberUser = order.NumberUser;
newOrder.PortfolioNumber = order.PortfolioNumber;
newOrder.Side = order.Side;
newOrder.State = OrderStateType.Fail;
if (MyOrderEvent != null)
{
MyOrderEvent(newOrder);
}
}
}
19
View Source File : OandaClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
void _transactionsSession_DataReceived(OkonkwoOandaV20.TradeLibrary.DataTypes.Stream.TransactionStreamResponse data)
{
if (_isDisposed)
{
return;
}
if (data.transaction.type == "LIMIT_ORDER")
{
LimitOrderTransaction order = (LimitOrderTransaction) data.transaction;
Order newOrder = new Order();
newOrder.NumberUser = Convert.ToInt32(order.clientExtensions.id);
newOrder.NumberMarket = order.id.ToString();
newOrder.SecurityNameCode = order.instrument;
newOrder.Price = Convert.ToDecimal(order.price);
newOrder.TimeCallBack = DateTime.Parse(order.time);
newOrder.State = OrderStateType.Activ;
if (NewOrderEvent != null)
{
NewOrderEvent(newOrder);
}
}
else if (data.transaction.type == "LIMIT_ORDER_REJECT")
{
LimitOrderRejectTransaction order = (LimitOrderRejectTransaction)data.transaction;
Order newOrder = new Order();
newOrder.NumberUser = Convert.ToInt32(order.clientExtensions.id);
newOrder.NumberMarket = order.id.ToString();
newOrder.SecurityNameCode = order.instrument;
newOrder.Price = Convert.ToDecimal(order.price);
newOrder.State = OrderStateType.Fail;
newOrder.TimeCallBack = DateTime.Parse(order.time);
if (NewOrderEvent != null)
{
NewOrderEvent(newOrder);
}
}
else if (data.transaction.type == "ORDER_FILL")
{
OrderFillTransaction order = (OrderFillTransaction)data.transaction;
MyTrade trade = new MyTrade();
trade.NumberOrderParent = order.clientOrderID;
trade.NumberTrade = order.id.ToString();
trade.Price = Convert.ToDecimal(order.price);
trade.Volume = Convert.ToDecimal(order.units);
trade.Time = DateTime.Parse(order.time);
trade.SecurityNameCode = order.instrument;
Order myOrder = _orders.Find(o => o.NumberUser.ToString() == order.clientOrderID);
if (myOrder == null)
{
return;
}
trade.Volume = myOrder.Volume;
if (order.units == 1)
{
trade.Side = Side.Buy;
}
else
{
trade.Side = Side.Sell;
}
if (NewMyTradeEvent != null)
{
NewMyTradeEvent(trade);
}
}
else if (data.transaction.type == "SystemOrderReject")
{
Order newOrder = new Order();
// newOrder.NumberUser = order.NumberUser;
newOrder.State = OrderStateType.Fail;
//trade.Time = DateTime.Parse(order.time);
if (NewOrderEvent != null)
{
NewOrderEvent(newOrder);
}
}
else if (data.transaction.type == "ORDER_CANCEL")
{
OrderCancelTransaction order = (OrderCancelTransaction)data.transaction;
Order newOrder= new Order();
newOrder.NumberUser = Convert.ToInt32(order.clientOrderID);
newOrder.State = OrderStateType.Cancel;
newOrder.TimeCallBack = DateTime.Parse(order.time);
newOrder.TimeCancel = newOrder.TimeCallBack;
if (NewOrderEvent != null)
{
NewOrderEvent(newOrder);
}
}
}
19
View Source File : OandaClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
void _marketDepthStream_DataReceived(OkonkwoOandaV20.TradeLibrary.DataTypes.Stream.PricingStreamResponse data)
{
if (_isDisposed)
{
return;
}
Trade newTrade = new Trade();
Trade newTrade2 = new Trade();
newTrade.Price = Convert.ToDecimal(data.price.closeoutAsk);
newTrade2.Price = Convert.ToDecimal(data.price.closeoutAsk);
newTrade.SecurityNameCode = data.price.instrument;
newTrade2.SecurityNameCode = data.price.instrument;
newTrade.Time = DateTime.Parse(data.price.time);
newTrade2.Time = DateTime.Parse(data.price.time);
newTrade.MicroSeconds = newTrade.Time.Millisecond * 1000;
newTrade2.MicroSeconds = newTrade.Time.Millisecond * 1000;
if (NewTradeEvent != null)
{
NewTradeEvent(newTrade);
NewTradeEvent(newTrade2);
}
MarketDepth depth = new MarketDepth();
depth.Time = newTrade.Time;
depth.SecurityNameCode = data.price.instrument;
for (int i = 0; i < data.price.asks.Count; i++)
{
depth.Asks.Add(new MarketDepthLevel() { Ask = data.price.asks[i].liquidity, Price = Convert.ToDecimal(data.price.asks[i].price) });
}
for (int i = 0; i < data.price.bids.Count; i++)
{
depth.Bids.Add(new MarketDepthLevel() { Bid = data.price.bids[i].liquidity, Price = Convert.ToDecimal(data.price.bids[i].price) });
}
if (MarketDepthChangeEvent != null)
{
MarketDepthChangeEvent(depth);
}
}
19
View Source File : OandaServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void CandleGeterThread()
{
while (true)
{
Thread.Sleep(1000);
if (_depthsDontGo == false)
{
return;
}
try
{
for (int i = 0; i < _namesSecuritiesToGetTicks.Count; i++)
{
short count = 1;
string price = "MBA";
string instrument = _namesSecuritiesToGetTicks[i].Name;
string granularity = GetTimeFrameInOandaFormat(TimeFrame.Min1).ToString();
var parameters = new Dictionary<string, string>();
parameters.Add("price", price);
parameters.Add("granularity", granularity);
parameters.Add("count", count.ToString());
Task<List<CandlestickPlus>> result = Rest20.GetCandlesAsync(instrument, parameters);
while (!result.IsCanceled &&
!result.IsCompleted &&
!result.IsFaulted)
{
Thread.Sleep(10);
}
List<CandlestickPlus> candleOanda = result.Result;
Trade newCandle = new Trade();
newCandle.Price = Convert.ToDecimal(candleOanda[0].bid.c);
newCandle.Time = DateTime.Parse(candleOanda[0].time);
newCandle.SecurityNameCode = _namesSecuritiesToGetTicks[i].Name;
newCandle.Volume = candleOanda[0].volume;
newCandle.Side = Side.Buy;
if (NewTradesEvent != null)
{
NewTradesEvent(newCandle);
}
MarketDepth depth = new MarketDepth();
depth.SecurityNameCode = newCandle.SecurityNameCode;
depth.Time = newCandle.Time;
depth.Asks = new List<MarketDepthLevel>()
{
new MarketDepthLevel()
{
Ask = 1,Price = newCandle.Price + _namesSecuritiesToGetTicks[i].PriceStep
}
};
depth.Bids = new List<MarketDepthLevel>()
{
new MarketDepthLevel()
{
Bid= 1,Price = newCandle.Price - _namesSecuritiesToGetTicks[i].PriceStep
}
};
if (MarketDepthEvent != null)
{
MarketDepthEvent(depth);
}
}
}
catch (Exception error)
{
SendLogMessage(error.ToString(), LogMessageType.Error);
Thread.Sleep(1000);
}
}
}
19
View Source File : Reflection.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public static object ConvertObject(object obj, Type type)
{
var t = GetObjectType(type);
if(obj == null)
{
return GetDefault(t);
}
if(t.IsEnum)
{
obj = Enum.Parse(t, obj is string value ? value : obj.ToString(), false);
}
if(t == typeof(string))
{
if(obj is string convertObject)
{
return convertObject;
}
var mi = obj.GetType().GetMethods().SingleOrDefault(m => m.Name == "ToString" && !m.GetMethodParameters().Any());
return mi?.Invoke(obj, Array.Empty<object>());
}
if((obj is string s) && t == typeof(char[]))
{
return s.Split();
}
if(t.IsArray)
{
if(obj is Array arrSrc)
{
var arrDest = (Array)CreateArray(t.GetElementType(), arrSrc.Length);
Array.Copy(arrSrc, arrDest, arrSrc.Length);
return arrDest;
}
}
if(t == typeof(object))
{
return obj;
}
if(obj is not string o)
{
return Convert.ChangeType(obj, t);
}
if(t == typeof(bool))
{
if(short.TryParse(o, out var i))
{
return i != 0;
}
return bool.Parse(o);
}
if(t == typeof(decimal) || t == typeof(float))
{
var types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), t.MakeByRefType() };
var args = new[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "," }, GetDefault(t) };
if((bool)t.GetMethod("TryParse", types)?.Invoke(null, args)!)
{
return args[3];
}
types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider) };
args = new object[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "." } };
return t.GetMethod("Parse", types)?.Invoke(null, args);
}
if(t == typeof(long)
|| t == typeof(ulong)
|| t == typeof(int)
|| t == typeof(uint)
|| t == typeof(short)
|| t == typeof(ushort)
|| t == typeof(byte)
|| t == typeof(sbyte)
|| t == typeof(char))
{
return t.GetMethod("Parse", new[] { typeof(string) })?.Invoke(null, new object[] {o});
}
if(t == typeof(DateTime))
{
return DateTime.TryParse(o, CultureInfo.GetCultureInfo("ru-RU"), DateTimeStyles.replacedumeLocal, out var dt) ? dt : DateTime.Parse(o, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.replacedumeLocal);
}
return Convert.ChangeType(o, t);
}
19
View Source File : DateTimeConverter.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
19
View Source File : DateTimeHelper.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 DateTime ParseAndConvertToUniversalTime(string serializedDateTime)
{
return DateTime.Parse(serializedDateTime, CultureInfo.InvariantCulture, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal);
}
19
View Source File : DateTimeHelper.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 DateTime ParseAndConvertToUniversalTime(string dateTimeString)
{
return DateTime.Parse(dateTimeString, CultureInfo.InvariantCulture, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal);
}
19
View Source File : ApiClient.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public object Deserialize(IRestResponse response, Type type)
{
var headers = response.Headers;
// return byte array
if (type == typeof(byte[]))
{
return response.RawBytes;
}
// TODO: ? if (type.IsreplacedignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = string.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", string.Empty).Replace("'", string.Empty));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
// return a datetime object
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime"))
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
// return primitive type
if (type == typeof(string) || type.Name.StartsWith("System.Nullable"))
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
19
View Source File : PermissionHandler.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
var httpContext = _accessor.HttpContext;
// 获取系统中所有的角色和菜单的关系集合
if (!requirement.Permissions.Any())
{
var data = await _roleModulePermissionServices.RoleModuleMaps();
var list = new List<PermissionItem>();
// ids4和jwt切换
// ids4
if (Permissions.IsUseIds4)
{
list = (from item in data
where item.IsDeleted == false
orderby item.Id
select new PermissionItem
{
Url = item.Module?.LinkUrl,
Role = item.Role?.Id.ObjToString(),
}).ToList();
}
// jwt
else
{
list = (from item in data
where item.IsDeleted == false
orderby item.Id
select new PermissionItem
{
Url = item.Module?.LinkUrl,
Role = item.Role?.Name.ObjToString(),
}).ToList();
}
requirement.Permissions = list;
}
if (httpContext != null)
{
var questUrl = httpContext.Request.Path.Value.ToLower();
// 整体结构类似认证中间件UseAuthentication的逻辑,具体查看开源地址
// https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs
httpContext.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
{
OriginalPath = httpContext.Request.Path,
OriginalPathBase = httpContext.Request.PathBase
});
// Give any IAuthenticationRequestHandler schemes a chance to handle the request
// 主要作用是: 判断当前是否需要进行远程验证,如果是就进行远程验证
var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
{
if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
{
context.Fail();
return;
}
}
//判断请求是否拥有凭据,即有没有登录
var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);
// 是否开启测试环境
var isTestCurrent = Appsettings.app(new string[] { "AppSettings", "UseLoadTest" }).ObjToBool();
//result?.Principal不为空即登录成功
if (result?.Principal != null || isTestCurrent)
{
if (!isTestCurrent) httpContext.User = result.Principal;
// 获取当前用户的角色信息
var currentUserRoles = new List<string>();
// ids4和jwt切换
// ids4
if (Permissions.IsUseIds4)
{
currentUserRoles = (from item in httpContext.User.Claims
where item.Type == "role"
select item.Value).ToList();
}
else
{
// jwt
currentUserRoles = (from item in httpContext.User.Claims
where item.Type == requirement.ClaimType
select item.Value).ToList();
}
var isMatchRole = false;
var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
foreach (var item in permisssionRoles)
{
try
{
if (Regex.Match(questUrl, item.Url?.ObjToString().ToLower())?.Value == questUrl)
{
isMatchRole = true;
break;
}
}
catch (Exception)
{
// ignored
}
}
//验证权限
if (currentUserRoles.Count <= 0 || !isMatchRole)
{
context.Fail();
return;
}
var isExp = false;
// ids4和jwt切换
// ids4
if (Permissions.IsUseIds4)
{
isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) != null && DateHelper.StampToDateTime(httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) >= DateTime.Now;
}
else
{
// jwt
isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now;
}
if (isExp)
{
context.Succeed(requirement);
}
else
{
context.Fail();
return;
}
return;
}
}
//判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
if (!(questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType)))
{
context.Fail();
return;
}
}
//context.Succeed(requirement);
}
19
View Source File : PermissionHandler.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
var httpContext = _accessor.HttpContext;
// 获取系统中所有的角色和菜单的关系集合
if (!requirement.Permissions.Any())
{
var data = await _roleModulePermissionRepository.RoleModuleMaps();
var list = new List<PermissionItem>();
{
list = (from item in data
where item.IsDeleted == false
orderby item.Id
select new PermissionItem
{
Url = item.Module?.LinkUrl,
Role = item.Role?.Name.ObjToString(),
}).ToList();
}
requirement.Permissions = list;
}
if (httpContext != null)
{
var questUrl = httpContext.Request.Path.Value.ToLower();
// 整体结构类似认证中间件UseAuthentication的逻辑,具体查看开源地址
// https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs
httpContext.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
{
OriginalPath = httpContext.Request.Path,
OriginalPathBase = httpContext.Request.PathBase
});
// Give any IAuthenticationRequestHandler schemes a chance to handle the request
// 主要作用是: 判断当前是否需要进行远程验证,如果是就进行远程验证
var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
{
if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
{
context.Fail();
return;
}
}
//判断请求是否拥有凭据,即有没有登录
var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);
//result?.Principal不为空即登录成功
if (result?.Principal != null)
{
httpContext.User = result.Principal;
// 获取当前用户的角色信息
var currentUserRoles = new List<string>();
{
// jwt
currentUserRoles = (from item in httpContext.User.Claims
where item.Type == requirement.ClaimType
select item.Value).ToList();
}
var isMatchRole = false;
var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
foreach (var item in permisssionRoles)
{
try
{
if (Regex.Match(questUrl, item.Url?.ObjToString().ToLower())?.Value == questUrl)
{
isMatchRole = true;
break;
}
}
catch (Exception)
{
// ignored
}
}
//验证权限
if (currentUserRoles.Count <= 0 || !isMatchRole)
{
context.Fail();
return;
}
var isExp = false;
{
// jwt
isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now;
}
if (isExp)
{
context.Succeed(requirement);
}
else
{
context.Fail();
return;
}
return;
}
}
//判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
if (!(questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType)))
{
context.Fail();
return;
}
}
//context.Succeed(requirement);
}
19
View Source File : Engine.cs
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
public static ExpressionSet FixRules(ExpressionSet rules)
{
foreach (var rule in rules.Expressions)
{
if (rule.MemberName == "PremiereDate")
{
var somedate = DateTime.Parse(rule.TargetValue);
rule.TargetValue = ConvertToUnixTimestamp(somedate).ToString();
}
}
return rules;
}
19
View Source File : YoutubeDLMetadataProvider.cs
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
License : GNU Affero General Public License v3.0
Project Creator : ankenyr
public static void ProcessResult(Video item, Google.Apis.YouTube.v3.Data.Video result)
{
item.Name = result.Snippet.replacedle;
item.Overview = result.Snippet.Description;
var date = DateTime.Parse(result.Snippet.PublishedAtRaw);
item.ProductionYear = date.Year;
item.PremiereDate = date;
}
19
View Source File : DateTimeTypeDrawer.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target)
{
var dateString = value.ToString();
var newDateString = EditorGUILayout.TextField(memberName, dateString);
return newDateString != dateString
? DateTime.Parse(newDateString)
: value;
}
19
View Source File : JobPositionController.cs
License : MIT License
Project Creator : anteatergames
License : MIT License
Project Creator : anteatergames
[Authorize]
[HttpPost("work/jobposition/save")]
public IActionResult Save(JobPositionViewModel vm)
{
try
{
bool isNew = vm.Id == Guid.Empty;
vm.UserId = CurrentUserId;
if (!string.IsNullOrWhiteSpace(vm.ClosingDateText))
{
vm.ClosingDate = DateTime.Parse(vm.ClosingDateText);
}
OperationResultVo<Guid> saveResult = jobPositionAppService.Save(CurrentUserId, vm);
if (saveResult.Success)
{
GenerateFeedPost(vm);
string url = Url.Action("Details", "JobPosition", new { area = "Work", id = vm.Id, pointsEarned = saveResult.PointsEarned });
if (isNew)
{
NotificationSender.SendTeamNotificationAsync("New Job Position posted!");
}
return Json(new OperationResultRedirectVo(saveResult, url));
}
else
{
return Json(new OperationResultVo(false));
}
}
catch (Exception ex)
{
return Json(new OperationResultVo(ex.Message));
}
}
19
View Source File : Note.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
public DateTime GetLastModifiedDateTime()
{
return DateTime.Parse(LastModified);
}
19
View Source File : ProductManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private static void DownloadLatest(ApexSettings settings, string manifestPath)
{
var client = new WebClient
{
BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
};
string serviceUrl = null;
try
{
client.Headers.Add("Accept", "application/xml");
var latestUpdate = XmlSingleValue(client.DownloadString("api/Service/GetLatestUpdateTime"));
if (settings.lastUpdateCheck >= DateTime.Parse(latestUpdate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal))
{
settings.UpdateCompleted(null);
return;
}
client.Headers.Add("Accept", "application/xml");
var productManifest = client.DownloadString("api/Products/GetProducts");
using (var w = new StreamWriter(manifestPath))
{
w.Write(productManifest);
}
client.Headers.Add("Accept", "application/xml");
serviceUrl = XmlSingleValue(client.DownloadString("api/Service/GetServiceUrl"));
}
catch
{
return;
}
settings.UpdateCompleted(serviceUrl);
}
19
View Source File : DoubleArgumentParser.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override object Parse(object obj)
{
Require.That(obj).Named("argument").IsNotNull();
if (obj is ExcelDataProvider.IRangeInfo)
{
var r=((ExcelDataProvider.IRangeInfo)obj).FirstOrDefault();
return r == null ? 0 : r.ValueDouble;
}
if (obj is double) return obj;
if (obj.IsNumeric()) return util.ConvertUtil.GetValueDouble(obj);
var str = obj != null ? obj.ToString() : string.Empty;
try
{
double d;
if (double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
return d;
return System.DateTime.Parse(str, CultureInfo.CurrentCulture, DateTimeStyles.None).ToOADate();
}
catch// (Exception e)
{
throw new ExcelErrorValueException(ExcelErrorValue.Create(eErrorType.Value));
}
}
19
View Source File : Minute.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var dateObj = arguments.ElementAt(0).Value;
System.DateTime date = System.DateTime.MinValue;
if (dateObj is string)
{
date = System.DateTime.Parse(dateObj.ToString());
}
else
{
var d = ArgToDecimal(arguments, 0);
date = System.DateTime.FromOADate(d);
}
return CreateResult(date.Minute, DataType.Integer);
}
19
View Source File : Year.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var dateObj = arguments.ElementAt(0).Value;
System.DateTime date = System.DateTime.MinValue;
if (dateObj is string)
{
date = System.DateTime.Parse(dateObj.ToString());
}
else
{
var d = ArgToDecimal(arguments, 0);
date = System.DateTime.FromOADate(d);
}
return CreateResult(date.Year, DataType.Integer);
}
19
View Source File : Extensions.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public static DateTime ToDateTime(this string self)
{
return DateTime.Parse(self, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}
19
View Source File : PageUserInfo.cs
License : MIT License
Project Creator : AtiLion
License : MIT License
Project Creator : AtiLion
private static void SetupUserInfo(PageUserInfo __instance)
{
SelectedAPI = __instance.user;
ExtendedUser eUser = ExtendedServer.Users.FirstOrDefault(a => a.UniqueID == SelectedAPI.id);
VRCExtended.ToggleUserInfoMore(false);
VRCEUi.InternalUserInfoScreen.Moderator.gameObject.SetActive(false);
if (APIUser.CurrentUser.id == __instance.user.id)
{
VRCExtended.UserInfoLastLogin.Text.text = "";
VRCExtended.UserInfoMore.Button.interactable = false;
}
else
{
APIUser.FetchUser(__instance.user.id, (APIUser user) =>
{
if (string.IsNullOrEmpty(user.last_login))
return;
DateTime dt = DateTime.Parse(user.last_login);
if (ModPrefs.GetBool("vrcextended", "useDTFormat"))
VRCExtended.UserInfoLastLogin.Text.text = "Last login: " + dt.ToString("MM.dd.yyyy hh:mm tt");
else
VRCExtended.UserInfoLastLogin.Text.text = "Last login: " + dt.ToString("dd.MM.yyyy hh:mm");
},
(string error) =>
{
ExtendedLogger.LogError(error);
});
VRCExtended.UserInfoMore.Button.interactable = true;
if(eUser != null)
{
VRCExtended.UserInfoColliderControl.Button.interactable = true;
VRCExtended.UserInfoColliderControl.Text.text = (eUser.HasColliders ? "Disable colliders" : "Enable colliders");
}
else
{
VRCExtended.UserInfoColliderControl.Button.interactable = false;
VRCExtended.UserInfoColliderControl.Text.text = "Not in world!";
}
}
}
19
View Source File : TzktApi.cs
License : GNU General Public License v3.0
Project Creator : atomex-me
License : GNU General Public License v3.0
Project Creator : atomex-me
private Result<IEnumerable<TezosTransaction>> ParseTxs(
JArray data)
{
var result = new List<TezosTransaction>();
foreach (var op in data)
{
if (!(op is JObject transaction))
return new Error(Errors.NullOperation, "Null operation in response");
var state = StateFromStatus(transaction["status"].Value<string>());
var alias = $"{transaction["sender"]["alias"]?.Value<string>()}/{transaction["target"]["alias"]?.Value<string>()}";
if (alias.Length == 1)
alias = string.Empty;
var tx = new TezosTransaction()
{
Id = transaction["hash"].ToString(),
Currency = _currency.Name,
State = state,
Type = BlockchainTransactionType.Unknown,
CreationTime = DateTime.SpecifyKind(DateTime.Parse(transaction["timestamp"].ToString()), DateTimeKind.Utc),
GasUsed = transaction["gasUsed"].Value<decimal>(),
Burn = transaction["storageFee"].Value<decimal>() +
transaction["allocationFee"].Value<decimal>(),
Alias = alias,
IsInternal = transaction.ContainsKey("nonce"),
//tx.IsInternal = tx.From == ((TezosTokens.FA12) _currency).SwapContractAddress;
InternalIndex = transaction["nonce"]?.Value<int>() ?? 0,
BlockInfo = new BlockInfo
{
Confirmations = state == BlockchainTransactionState.Failed ? 0 : 1,
BlockHash = null,
BlockHeight = transaction["level"].Value<long>(),
BlockTime = DateTime.SpecifyKind(DateTime.Parse(transaction["timestamp"].ToString()), DateTimeKind.Utc),
FirstSeen = DateTime.SpecifyKind(DateTime.Parse(transaction["timestamp"].ToString()), DateTimeKind.Utc)
}
};
tx.From = transaction["sender"]?["address"]?.ToString();
tx.To = transaction["target"]?["address"]?.ToString();
tx.Amount = transaction["amount"].Value<decimal>();
tx.Alias = alias;
if (tx.IsInternal)
{
tx.InternalIndex = transaction["nonce"]?.Value<int>() ?? 0;
}
else
{
var txParameters = transaction.ContainsKey("parameters")
? JObject.Parse(transaction["parameters"].Value<string>())
: null;
tx.Params = txParameters;
tx.Fee = transaction["bakerFee"].Value<decimal>();
tx.GasLimit = transaction["gasLimit"].Value<decimal>();
tx.StorageLimit = transaction["storageLimit"].Value<decimal>();
}
if (tx != null)
result.Add(tx);
}
return result;
}
19
View Source File : ApiClient.cs
License : Apache License 2.0
Project Creator : Autodesk-Forge
License : Apache License 2.0
Project Creator : Autodesk-Forge
public /*object*/dynamic Deserialize (IRestResponse response, Type type, bool asType = false) {
#pragma warning disable CS0618 // Type or member is obsolete
IList<Parameter> headers = response.Headers;
#pragma warning restore CS0618 // Type or member is obsolete
if ( type == typeof (byte []) ) // return byte array
return response.RawBytes;
if ( type == typeof (Stream) ) {
if ( headers != null ) {
var filePath = String.IsNullOrEmpty (Configuration.TempFolderPath)
? Path.GetTempPath ()
: Configuration.TempFolderPath;
var regex = new Regex (@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach ( var header in headers ) {
var match = regex.Match (header.ToString ());
if ( match.Success ) {
string fileName = filePath + SanitizeFilename (match.Groups [1].Value.Replace ("\"", "").Replace ("'", ""));
File.WriteAllBytes (fileName, response.RawBytes);
return new FileStream (fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream (response.RawBytes);
return stream;
}
if ( type.Name.StartsWith ("System.Nullable`1[[System.DateTime") ) // return a datetime object
{
return DateTime.Parse (response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if ( type == typeof (String) || type.Name.StartsWith ("System.Nullable") ) // return primitive type
{
return ConvertType (response.Content, type);
}
// at this point, it must be a model (json)
try {
if ( asType )
return JsonConvert.DeserializeObject (response.Content, type, serializerSettings);
return new DynamicJsonResponse (JObject.Parse (response.Content));
} catch ( Exception /*e*/) {
//throw new ApiException(500, e.Message);
return (new DynamicJsonResponse ());
}
}
19
View Source File : FileUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
DateTime GetTime()
{
return DateTime.Parse(mc.Value);
}
19
View Source File : SqlDataRow.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public void AddColumn(SqlDataColumn column)
{
if (column == null)
throw new ArgumentNullException(nameof(column));
if (string.IsNullOrEmpty(column.Name))
throw new ArgumentException("Column.Name must have a value.", nameof(column));
var col = Table.DbTable.Columns.Where(c => c.Name == column.Name).SingleOrDefault();
if (col == null)
{
// Check and see if it is a reference data id.
col = Table.DbTable.Columns.Where(c => c.Name == column.Name + "Id").SingleOrDefault();
if (col == null || !col.IsForeignRefData)
throw new SqlDataUpdaterException($"Table '{Table.Schema}.{Table.Name}' does not have a column named '{column.Name}' or '{column.Name}Id'; or was not identified as a foreign key to Reference Data.");
column.Name += "Id";
}
if (Columns.Any(x => x.Name == column.Name))
throw new SqlDataUpdaterException($"Table '{Table.Schema}.{Table.Name}' column '{column.Name}' has been specified more than once.");
column.DbColumn = col;
Columns.Add(column);
if (column.Value == null)
return;
string? str = null;
try
{
str = column.Value is DateTime time ? time.ToString(SqlDataUpdater.DateTimeFormat, System.Globalization.CultureInfo.InvariantCulture) : column.Value.ToString()!;
switch (DbColumn.GetDotNetTypeName(col.Type))
{
case "string": column.Value = str; break;
case "decimal": column.Value = decimal.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "DateTime": column.Value = DateTime.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "bool": column.Value = bool.Parse(str); break;
case "DateTimeOffset": column.Value = DateTimeOffset.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "double": column.Value = double.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "int": column.Value = int.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "long": column.Value = long.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "short": column.Value = short.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "byte": column.Value = byte.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "float": column.Value = float.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "TimeSpan": column.Value = TimeSpan.Parse(str, System.Globalization.CultureInfo.InvariantCulture); break;
case "Guid":
if (int.TryParse(str, out int a))
column.Value = new Guid(a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
else
{
if (Guid.TryParse(str, out Guid g))
column.Value = g;
else if (col.IsForeignRefData)
{
column.Value = str;
column.UseForeignKeyQueryForId = true;
}
}
break;
default:
throw new SqlDataUpdaterException($"Table '{Table.Schema}.{Table.Name}' column '{column.Name}' type '{col.Type}' is not supported.");
}
}
catch (FormatException fex)
{
if (col.IsForeignRefData)
{
column.Value = str;
column.UseForeignKeyQueryForId = true;
}
else
throw new SqlDataUpdaterException($"'{Table.Schema}.{Table.Name}' column '{column.Name}' type '{col.Type}' cannot parse value '{column.Value}': {fex.Message}");
}
}
19
View Source File : ListLayerVersionsCommand.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
protected override async Task<bool> PerformActionAsync()
{
var layerName = this.GetStringValueOrDefault(this.LayerName, LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME, true);
this.Logger.WriteLine("Description".PadRight(LAYER_DESCRIPTION_WIDTH) + " " +
"Compatible Runtimes".PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " +
"Created".PadRight(TIMESTAMP_WIDTH) + " " +
"Latest Version ARN".PadRight(LAYER_ARN_WIDTH)
);
this.Logger.WriteLine($"{new string('-', LAYER_DESCRIPTION_WIDTH)} {new string('-', LAYER_COMPATIBLE_RUNTIMES_WIDTH)} {new string('-', TIMESTAMP_WIDTH)} {new string('-', LAYER_ARN_WIDTH)}");
var request = new ListLayerVersionsRequest { LayerName = layerName};
ListLayerVersionsResponse response = null;
do
{
request.Marker = response?.NextMarker;
try
{
response = await this.LambdaClient.ListLayerVersionsAsync(request);
}
catch (Exception e)
{
throw new LambdaToolsException("Error listing versions for Lambda layer: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaListLayerVersions, e);
}
foreach (var layerVersion in response.LayerVersions)
{
this.Logger.WriteLine( LambdaUtilities.DetermineListDisplayLayerDescription(layerVersion.Description, LAYER_DESCRIPTION_WIDTH).PadRight(LAYER_DESCRIPTION_WIDTH) + " " +
string.Join(", ", layerVersion.CompatibleRuntimes.ToArray()).PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " +
DateTime.Parse(layerVersion.CreatedDate).ToString("g").PadRight(TIMESTAMP_WIDTH) + " " +
layerVersion.LayerVersionArn
);
}
} while (!string.IsNullOrEmpty(response.NextMarker));
return true;
}
19
View Source File : GetLayerVersionDetailsCommand.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
protected override async Task<bool> PerformActionAsync()
{
var layerVersionArn = this.GetStringValueOrDefault(this.LayerVersionArn,
LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN, true);
var result = LambdaUtilities.ParseLayerVersionArn(layerVersionArn);
var getRequest = new GetLayerVersionRequest
{
LayerName = result.Name,
VersionNumber = result.VersionNumber
};
try
{
var response = await this.LambdaClient.GetLayerVersionAsync(getRequest);
this.Logger.WriteLine("Layer ARN:".PadRight(PAD_SIZE) + response.LayerArn);
this.Logger.WriteLine("Version Number:".PadRight(PAD_SIZE) + response.Version);
this.Logger.WriteLine("Created:".PadRight(PAD_SIZE) + DateTime.Parse(response.CreatedDate).ToString("g"));
this.Logger.WriteLine("License Info:".PadRight(PAD_SIZE) + response.LicenseInfo);
this.Logger.WriteLine("Compatible Runtimes:".PadRight(PAD_SIZE) + string.Join(", ", response.CompatibleRuntimes.ToArray()));
LayerDescriptionManifest manifest;
if (!LambdaUtilities.AttemptToParseLayerDescriptionManifest(response.Description, out manifest))
{
this.Logger.WriteLine("Description:".PadRight(PAD_SIZE) + response.Description);
}
else
{
switch (manifest.Nlt)
{
case LayerDescriptionManifest.ManifestType.RuntimePackageStore:
this.Logger.WriteLine("Layer Type:".PadRight(PAD_SIZE) + LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE_DISPLAY_NAME);
await GetRuntimePackageManifest(manifest);
break;
default:
this.Logger.WriteLine("Layer Type:".PadRight(PAD_SIZE) + manifest.Nlt);
break;
}
}
}
catch(Exception e)
{
throw new LambdaToolsException("Error getting layer version details: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaGetLayerVersionDetails, e);
}
return true;
}
19
View Source File : ListLayersCommand.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
protected override async Task<bool> PerformActionAsync()
{
this.Logger.WriteLine("Name".PadRight(LAYER_NAME_WIDTH) + " " +
"Description".PadRight(LAYER_DESCRIPTION_WIDTH) + " " +
"Compatible Runtimes".PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " +
"Created".PadRight(TIMESTAMP_WIDTH) + " " +
"Latest Version ARN".PadRight(LAYER_ARN_WIDTH)
);
this.Logger.WriteLine($"{new string('-', LAYER_NAME_WIDTH)} {new string('-', LAYER_DESCRIPTION_WIDTH)} {new string('-', LAYER_COMPATIBLE_RUNTIMES_WIDTH)} {new string('-', TIMESTAMP_WIDTH)} {new string('-', LAYER_ARN_WIDTH)}");
var request = new ListLayersRequest();
ListLayersResponse response = null;
do
{
if (response != null)
request.Marker = response.NextMarker;
try
{
response = await this.LambdaClient.ListLayersAsync(request);
}
catch (Exception e)
{
throw new LambdaToolsException("Error listing Lambda layers: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaListLayers, e);
}
foreach (var layer in response.Layers)
{
var latestVersion = layer.LatestMatchingVersion;
this.Logger.WriteLine(layer.LayerName.PadRight(LAYER_NAME_WIDTH) + " " +
LambdaUtilities.DetermineListDisplayLayerDescription(latestVersion.Description, LAYER_DESCRIPTION_WIDTH).PadRight(LAYER_DESCRIPTION_WIDTH) + " " +
string.Join(", ", latestVersion.CompatibleRuntimes.ToArray()).PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " +
DateTime.Parse(latestVersion.CreatedDate).ToString("g").PadRight(TIMESTAMP_WIDTH) + " " +
latestVersion.LayerVersionArn
);
}
} while (!string.IsNullOrEmpty(response.NextMarker));
return true;
}
19
View Source File : FileBlogService.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
[SuppressMessage(
"Globalization",
"CA1308:Normalize strings to uppercase",
Justification = "The slug should be lower case.")]
private void LoadPosts()
{
if (!Directory.Exists(this.folder))
{
Directory.CreateDirectory(this.folder);
}
// Can this be done in parallel to speed it up?
foreach (var file in Directory.EnumerateFiles(this.folder, "*.xml", SearchOption.TopDirectoryOnly))
{
var doc = XElement.Load(file);
var post = new Post
{
ID = Path.GetFileNameWithoutExtension(file),
replacedle = ReadValue(doc, "replacedle"),
Excerpt = ReadValue(doc, "excerpt"),
Content = ReadValue(doc, "content"),
Slug = ReadValue(doc, "slug").ToLowerInvariant(),
PubDate = DateTime.Parse(ReadValue(doc, "pubDate"), CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal),
LastModified = DateTime.Parse(
ReadValue(
doc,
"lastModified",
DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)),
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal),
IsPublished = bool.Parse(ReadValue(doc, "ispublished", "true")),
};
LoadCategories(post, doc);
LoadComments(post, doc);
this.cache.Add(post);
}
}
19
View Source File : FileBlogService.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
private static void LoadComments(Post post, XElement doc)
{
var comments = doc.Element("comments");
if (comments is null)
{
return;
}
foreach (var node in comments.Elements("comment"))
{
var comment = new Comment
{
ID = ReadAttribute(node, "id"),
Author = ReadValue(node, "author"),
Email = ReadValue(node, "email"),
IsAdmin = bool.Parse(ReadAttribute(node, "isAdmin", "false")),
Content = ReadValue(node, "content"),
PubDate = DateTime.Parse(ReadValue(node, "date", "2000-01-01"),
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal),
};
post.Comments.Add(comment);
}
}
19
View Source File : EventSource.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
public static void LoadCommonSourceConfig(IConfiguration config, EventSource<T> source)
{
InitialPositionEnum initialPosition = InitialPositionEnum.Bookmark;
string initialPositionConfig = config["InitialPosition"];
if (!string.IsNullOrEmpty(initialPositionConfig))
{
switch (initialPositionConfig.ToLower())
{
case "eos":
initialPosition = InitialPositionEnum.EOS;
break;
case "0":
initialPosition = InitialPositionEnum.BOS;
break;
case "bookmark":
initialPosition = InitialPositionEnum.Bookmark;
break;
case "timestamp":
initialPosition = InitialPositionEnum.Timestamp;
string initialPositionTimeStamp = config["InitialPositionTimestamp"];
if (string.IsNullOrWhiteSpace(initialPositionTimeStamp))
{
throw new Exception("Missing initial position timestamp.");
}
try
{
var timeZone = Utility.ParseTimeZoneKind(config["TimeZoneKind"]);
var timestamp = DateTime.Parse(initialPositionTimeStamp, null, System.Globalization.DateTimeStyles.RoundtripKind);
source.InitialPositionTimestamp = timeZone == DateTimeKind.Utc
? DateTime.SpecifyKind(timestamp, DateTimeKind.Utc)
: DateTime.SpecifyKind(timestamp, DateTimeKind.Local).ToUniversalTime();
}
catch
{
throw new Exception($"Invalid InitialPositionTimestamp {initialPositionTimeStamp}");
}
break;
default:
throw new Exception($"Invalid InitialPosition {initialPositionConfig}");
}
}
source.InitialPosition = initialPosition;
}
19
View Source File : AsyncW3SVCLogParser.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
protected override W3SVCRecord CreateRecord(DelimitedTextLogContext context, Dictionary<string, string> data)
{
var timestamp = DateTime.UtcNow;
if (data.TryGetValue("date", out var date) && data.TryGetValue("time", out var time))
{
// date and time field is UTC-based: https://docs.microsoft.com/en-us/windows/win32/http/w3c-logging
timestamp = DateTime.Parse(date + "T" + time + "Z", null, DateTimeStyles.RoundtripKind);
}
return new W3SVCRecord(timestamp, data);
}
19
View Source File : FileSystemFactory.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
private static DateTime ParseInitialPositionTimestamp(IConfiguration config)
{
var timeZoneKind = Utility.ParseTimeZoneKind(config["TimeZoneKind"]);
var spec = config["InitialPositionTimestamp"];
if (spec is null)
{
return DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Local);
}
return timeZoneKind == DateTimeKind.Utc
? DateTime.Parse(spec, null, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal)
: DateTime.Parse(spec, null, DateTimeStyles.replacedumeLocal);
}
19
View Source File : Utility.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
public static DateTime ParseDatetime(string datetimeString, string format)
{
if (format is null)
{
//format is unknown, we let DateTime try to figure out
return DateTime.Parse(datetimeString, CultureInfo.InvariantCulture, DateTimeStyles.replacedumeLocal);
}
if (ConfigConstants.EPOCH.Equals(format, StringComparison.OrdinalIgnoreCase))
{
return FromEpochTime(long.Parse(datetimeString));
}
return DateTime.ParseExact(datetimeString, format, CultureInfo.InvariantCulture);
}
19
View Source File : WindowsSourceFactory.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
private void LoadInitialPositionSettings(IConfiguration config, WindowsEventLogSourceOptions options)
{
var initialPositionConfig = config["InitialPosition"];
if (!string.IsNullOrEmpty(initialPositionConfig))
{
switch (initialPositionConfig.ToLower())
{
case "eos":
options.InitialPosition = InitialPositionEnum.EOS;
break;
case "0":
options.InitialPosition = InitialPositionEnum.BOS;
break;
case "bookmark":
options.InitialPosition = InitialPositionEnum.Bookmark;
break;
case "timestamp":
options.InitialPosition = InitialPositionEnum.Timestamp;
string initialPositionTimeStamp = config["InitialPositionTimestamp"];
if (string.IsNullOrWhiteSpace(initialPositionTimeStamp))
{
throw new Exception("Missing initial position timestamp.");
}
try
{
var timeZone = Utility.ParseTimeZoneKind(config["TimeZoneKind"]);
var timestamp = DateTime.Parse(initialPositionTimeStamp, null, System.Globalization.DateTimeStyles.RoundtripKind);
options.InitialPositionTimestamp = timeZone == DateTimeKind.Utc
? DateTime.SpecifyKind(timestamp, DateTimeKind.Utc)
: DateTime.SpecifyKind(timestamp, DateTimeKind.Local).ToUniversalTime();
}
catch
{
throw new Exception($"Invalid InitialPositionTimestamp {initialPositionTimeStamp}");
}
break;
default:
throw new Exception($"Invalid InitialPosition {initialPositionConfig}");
}
}
}
19
View Source File : AsyncULSLogParser.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
protected override KeyValueLogRecord CreateRecord(DelimitedTextLogContext context, Dictionary<string, string> data)
{
var timestamp = DateTime.Now;
if (data.TryGetValue("TimestampUtc", out var timestampText))
{
timestamp = DateTime.Parse(timestampText, null, DateTimeStyles.replacedumeUniversal);
}
else if (data.TryGetValue("Timestamp", out timestampText))
{
timestamp = DateTime.Parse(timestampText, null, DateTimeStyles.replacedumeLocal);
}
return new KeyValueLogRecord(timestamp, data);
}
See More Examples