Here are the examples of the csharp api System.DateTime.TryParse(string, out System.DateTime) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
570 Examples
19
View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static DateTime ToDateTime(this object s)
{
if (s == null || s == DBNull.Value)
return DateTime.MinValue;
DateTime.TryParse(s.ToString(), out DateTime result);
return result;
}
19
View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
{
if (valueRaw == null) return default(T);
var type = typeof(T);
var typename = type.ToString().TrimEnd(']');
if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
if (valueRaw.Length == 0) return default(T);
string valueStr = null;
if (type.IsValueType)
{
valueStr = encoding.GetString(valueRaw);
bool isNullable = typename.StartsWith("System.Nullable`1[");
var basename = isNullable ? typename.Substring(18) : typename;
bool isElse = false;
object obj = null;
switch (basename)
{
case "System.Boolean":
if (valueStr == "1") obj = true;
else if (valueStr == "0") obj = false;
break;
case "System.Byte":
if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
break;
case "System.Char":
if (valueStr.Length > 0) obj = valueStr[0];
break;
case "System.Decimal":
if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
break;
case "System.Double":
if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
break;
case "System.Single":
if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
break;
case "System.Int32":
if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
break;
case "System.Int64":
if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
break;
case "System.SByte":
if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
break;
case "System.Int16":
if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
break;
case "System.UInt32":
if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
break;
case "System.UInt64":
if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
break;
case "System.UInt16":
if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
break;
case "System.DateTime":
if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
break;
case "System.DateTimeOffset":
if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
break;
case "System.TimeSpan":
if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
break;
case "System.Guid":
if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
break;
default:
isElse = true;
break;
}
if (isElse == false)
{
if (obj == null) return default(T);
return (T)obj;
}
}
if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));
if (valueStr == null) valueStr = encoding.GetString(valueRaw);
if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
return valueStr.ConvertTo<T>();
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
if (value is Array valueArr)
{
var targetElementType = targetType.GetElementType();
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
//if (value is IList valueList)
//{
// var targetElementType = targetType.GetElementType();
// var sourceArrLen = valueList.Count;
// var target = Array.CreateInstance(targetElementType, sourceArrLen);
// for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
// return target;
//}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
return func(valueStr);
}
19
View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public string GetColumnDefaultValue(DbColumnInfo col, bool isInsertValueSql)
{
var defval = col.DefaultValue?.Trim();
if (string.IsNullOrEmpty(defval)) return null;
var cstype = col.CsType.NullableTypeOrThis();
if (fsql.Ado.DataType == DataType.SqlServer || fsql.Ado.DataType == DataType.OdbcSqlServer)
{
if (defval.StartsWith("((") && defval.EndsWith("))")) defval = defval.Substring(2, defval.Length - 4);
else if (defval.StartsWith("('") && defval.EndsWith("')")) defval = defval.Substring(2, defval.Length - 4).Replace("''", "'");
else if(defval.StartsWith("(") && defval.EndsWith(")")) defval = defval.Substring(1, defval.Length - 2);
else return null;
}
else if ((cstype == typeof(string) && defval.StartsWith("'") && defval.EndsWith("'::character varying") ||
cstype == typeof(Guid) && defval.StartsWith("'") && defval.EndsWith("'::uuid")
) && (fsql.Ado.DataType == DataType.PostgreSQL || fsql.Ado.DataType == DataType.OdbcPostgreSQL ||
fsql.Ado.DataType == DataType.OdbcKingbaseES ||
fsql.Ado.DataType == DataType.ShenTong))
{
defval = defval.Substring(1, defval.LastIndexOf("'::") - 1).Replace("''", "'");
}
else if (defval.StartsWith("'") && defval.EndsWith("'"))
{
defval = defval.Substring(1, defval.Length - 2).Replace("''", "'");
if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql) defval = defval.Replace("\\\\", "\\");
}
if (cstype.IsNumberType() && decimal.TryParse(defval, out var trydec))
{
if (isInsertValueSql) return defval;
if (cstype == typeof(float)) return defval + "f";
if (cstype == typeof(double)) return defval + "d";
if (cstype == typeof(decimal)) return defval + "M";
return defval;
}
if (cstype == typeof(Guid) && Guid.TryParse(defval, out var tryguid)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"Guid.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(DateTime) && DateTime.TryParse(defval, out var trydt)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"DateTime.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(TimeSpan) && TimeSpan.TryParse(defval, out var tryts)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"TimeSpan.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(string)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\"";
if (cstype == typeof(bool)) return isInsertValueSql ? defval : (defval == "1" || defval == "t" ? "true" : "false");
if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql)
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
if (isInsertValueSql) return (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval);
return isInsertValueSql ? defval : null; //sql function or exp
}
19
View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
public static DateTime FromSQLDate(this string pDate)
{
DateTime.TryParse(pDate, out DateTime result);
return result;
}
19
View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
public static DateTime FromSQLDateTime(this string pDate)
{
DateTime.TryParse(pDate, out DateTime result);
return result;
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public static DateTime? CastToDate(string strDateTime)
{
DateTime? dtFinalDateTime = null;
DateTime dtTempDateTime;
if (DateTime.TryParse(strDateTime, out dtTempDateTime))
{
dtFinalDateTime = dtTempDateTime;
}
return dtFinalDateTime;
}
19
View Source File : EntityListDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected static Condition GetSearchFilterConditionForAttribute(string attribute, string query, EnreplacedyMetadata enreplacedyMetadata)
{
var attributeMetadata = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute);
if (attributeMetadata == null)
{
return null;
}
switch (attributeMetadata.AttributeType)
{
case AttributeTypeCode.String:
return new Condition(attribute, ConditionOperator.Like, "{0}%".FormatWith(query));
case AttributeTypeCode.Lookup:
case AttributeTypeCode.Customer:
case AttributeTypeCode.Picklist:
case AttributeTypeCode.State:
case AttributeTypeCode.Status:
case AttributeTypeCode.Owner:
return new Condition("{0}name".FormatWith(attribute), ConditionOperator.Like, "{0}%".FormatWith(query));
case AttributeTypeCode.BigInt:
long parsedLong;
return long.TryParse(query, out parsedLong)
? new Condition(attribute, ConditionOperator.Equal, parsedLong)
: null;
case AttributeTypeCode.Integer:
int parsedInt;
return int.TryParse(query, out parsedInt)
? new Condition(attribute, ConditionOperator.Equal, parsedInt)
: null;
case AttributeTypeCode.Double:
double parsedDouble;
return double.TryParse(query, out parsedDouble)
? new Condition(attribute, ConditionOperator.Equal, parsedDouble)
: null;
case AttributeTypeCode.Decimal:
case AttributeTypeCode.Money:
decimal parsedDecimal;
return decimal.TryParse(query, out parsedDecimal)
? new Condition(attribute, ConditionOperator.Equal, parsedDecimal)
: null;
case AttributeTypeCode.DateTime:
DateTime parsedDate;
return DateTime.TryParse(query, out parsedDate)
? new Condition(attribute, ConditionOperator.On, parsedDate.ToString("yyyy-MM-dd"))
: null;
default:
return null;
}
}
19
View Source File : SharePointFileHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void ProcessRequest(HttpContext context)
{
if (!string.Equals(context.Request.HttpMethod, "GET", StringComparison.InvariantCultureIgnoreCase)
|| SharePointFileUrl == null
|| string.IsNullOrWhiteSpace(FileName))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
try
{
var spConnection = new SharePointConnection("SharePoint");
var factory = new ClientFactory();
var request = factory.CreateHttpWebRequest(spConnection, SharePointFileUrl) as HttpWebRequest;
// make sure SharePoint receives the cache control headers from the browser
var requestHeaders = _headersToRequest
.Select(name => new { Name = name, Value = context.Request.Headers[name] })
.Where(header => !string.IsNullOrWhiteSpace(header.Value))
.ToList();
foreach (var header in requestHeaders)
{
request.Headers[header.Name] = header.Value;
}
request.Accept = context.Request.Headers["Accept"];
request.UserAgent = context.Request.Headers["User-Agent"];
DateTime ifModifiedSince;
if (DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out ifModifiedSince))
{
request.IfModifiedSince = ifModifiedSince;
}
WebResponse response;
try
{
response = request.GetResponse();
}
catch (WebException we)
{
// handle non-200 response from SharePoint
var hwr = we.Response as HttpWebResponse;
if (hwr != null && hwr.StatusCode == HttpStatusCode.NotModified)
{
context.Response.StatusCode = (int)HttpStatusCode.NotModified;
return;
}
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception thrown trying to download {0}", SharePointFileUrl));
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ProcessRequest", "Exception details: {0}", we.ToString()));
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return;
}
using (var stream = response.GetResponseStream())
{
// forward SharePoint response headers back to the browser
var responseHeaders = _headersToRespond
.Select(name => new { Name = name, Value = response.Headers[name] })
.Where(header => !string.IsNullOrWhiteSpace(header.Value))
.ToList();
foreach (var header in responseHeaders)
{
context.Response.AppendHeader(header.Name, header.Value);
}
context.Response.AppendHeader("Content-Disposition", @"attachment; filename=""{0}""".FormatWith(FileName));
int contentLength;
if (!int.TryParse(response.Headers["Content-Length"], out contentLength))
{
// indeterminant length
contentLength = -1;
}
if (contentLength == 0)
{
context.Response.StatusCode = (int)HttpStatusCode.NoContent;
return;
}
// start streaming file
context.Response.StatusCode = (int)HttpStatusCode.OK;
const int bufferSize = 65536;
var buffer = new byte[bufferSize];
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, bufferSize);
context.Response.OutputStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception thrown trying to download {0}", SharePointFileUrl));
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception details: {0}", e.ToString()));
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
19
View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static bool IsNotModified(HttpContextBase context, string eTag, DateTime? modifiedOn)
{
var ifNoneMatch = context.Request.Headers["If-None-Match"];
DateTime ifModifiedSince;
// check the etag and last modified
if (ifNoneMatch != null && ifNoneMatch == eTag)
{
return true;
}
return modifiedOn != null
&& DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out ifModifiedSince)
&& ifModifiedSince.ToUniversalTime() >= modifiedOn.Value.ToUniversalTime();
}
19
View Source File : SalesAttachmentHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static bool IsNotModified(HttpContext context, string eTag, DateTime? modifiedOn)
{
var ifNoneMatch = context.Request.Headers["If-None-Match"];
DateTime ifModifiedSince;
// check the etag and last modified
if (ifNoneMatch != null && ifNoneMatch == eTag)
{
return true;
}
if (modifiedOn != null
&& DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out ifModifiedSince)
&& ifModifiedSince.ToUniversalTime() >= modifiedOn.Value.ToUniversalTime())
{
return true;
}
return false;
}
19
View Source File : EventOccurrencesDrop.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override object BeforeMethod(string method)
{
if (method == null || !EventsEnabled)
{
return null;
}
DateTime dateTime;
if (DateTime.TryParse(method, out dateTime))
{
if (_isMin)
{
_min = dateTime;
if (_max != null) //there is a minimum value
{
if (_max < _min)
{
throw new ArgumentOutOfRangeException("_max", ResourceManager.GetString("MaxDate_LessThan_MinDate_Exception"));
}
_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(_min.Value, _max.Value)
.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);
return All;
}
_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(_min.Value, DateTime.Today.AddYears(2))
.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);
return new EventOccurrencesDrop(this, _dependencies, false, false, _min, _max);
}
if (_isMax)
{
_max = dateTime;
if (_min != null) //there is a minimum value
{
if (_max < _min)
{
throw new ArgumentOutOfRangeException("_max", ResourceManager.GetString("MaxDate_LessThan_MinDate_Exception"));
}
_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(_min.Value, _max.Value)
.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);
return All;
}
//there is no minimum value
_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(DateTime.Today.AddYears(-2), _max.Value)
.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);
return new EventOccurrencesDrop(this, _dependencies, false, false, _min, _max);
}
}
return null;
}
19
View Source File : DateTimeControlTemplate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override void InstantiateControlIn(Control container)
{
RegisterClientSideDependencies(container);
var textbox = new TextBox
{
ID = ControlID,
TextMode = TextBoxMode.SingleLine,
CssClreplaced = "datetime",
ToolTip = Metadata.ToolTip // MSBug #120060: Encode will be handled by TextBox control.
};
container.Controls.Add(textbox);
var dateTextBoxID = "{0}_Date".FormatWith(ControlID);
var dateTextBox = new TextBox
{
ID = dateTextBoxID,
TextMode = TextBoxMode.SingleLine,
CssClreplaced = "date",
ToolTip = Metadata.ToolTip // MSBug #120060: Encode will be handled by TextBox control.
};
dateTextBox.Attributes["style"] = "display:none;";
container.Controls.Add(dateTextBox);
var timeDropDown = GetTimeDropDown();
if (IncludesTime)
{
timeDropDown.Attributes["style"] = "display:none;";
container.Controls.Add(timeDropDown);
}
Bindings[Metadata.DataFieldName] = new CellBinding
{
Get = () =>
{
DateTime value;
return DateTime.TryParse(textbox.Text, out value) ? new DateTime?(value) : null;
},
Set = obj =>
{
var dateTime = obj as DateTime?;
textbox.Text = dateTime.HasValue
? dateTime.Value.ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'")
: string.Empty;
}
};
}
19
View Source File : DateTimeControlTemplate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static void OnDateFormatValidate(object source, ServerValidateEventArgs args)
{
DateTime value;
args.IsValid = DateTime.TryParse(args.Value, out value);
}
19
View Source File : MapController.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
[AcceptVerbs(HttpVerbs.Post)]
[AjaxValidateAntiForgeryToken, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "Handled with the custom attribute AjaxValidateAntiForgeryToken")]
public ActionResult Search(int dateFilterCode, string dateFrom, string dateTo, int statusFilterCode, int priorityFilterCode, string[] types, bool includeAlerts)
{
dateFilterCode = (dateFilterCode >= 0) ? dateFilterCode : 0;
var status = (statusFilterCode > 0) ? statusFilterCode : 999;
var priority = (priorityFilterCode >= 0) ? priorityFilterCode : 0;
DateTime fromDate;
DateTime.TryParse(dateFrom, out fromDate);
DateTime toDate;
DateTime.TryParse(dateTo, out toDate);
var typesGuids = types == null || types.Length < 1 ? null : Array.ConvertAll(types, Guid.Parse);
var context = PortalCrmConfigurationManager.CreateServiceContext();
var serviceRequests = context.CreateQuery("adx_servicerequest").Where(s => s.GetAttributeValue<decimal?>("adx_lareplacedude") != null && s.GetAttributeValue<decimal?>("adx_longitude") != null)
.FilterServiceRequestsByPriority(priority)
.FilterServiceRequestsByStatus(status)
.FilterServiceRequestsByDate(dateFilterCode, fromDate, toDate.AddDays(1))
.FilterServiceRequestsByType(typesGuids)
.ToList();
var serviceRequestMapNodes = new List<MapNode>();
if (serviceRequests.Any())
{
serviceRequestMapNodes =
serviceRequests.Select(
s =>
new MapNode(
MapNode.NodeType.ServiceRequest,
s.GetAttributeValue<string>("adx_servicerequestnumber"),
s.GetAttributeValue<string>("adx_name"),
s.GetAttributeValue<string>("adx_location"),
string.Empty,
s.GetAttributeValue<OptionSetValue>("adx_servicestatus") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_servicestatus").Value,
s.GetAttributeValue<OptionSetValue>("adx_priority") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_priority").Value,
s.GetAttributeValue<DateTime>("adx_incidentdate"),
s.GetAttributeValue<DateTime>("adx_scheduleddate"),
s.GetAttributeValue<DateTime>("adx_closeddate"),
s.GetAttributeValue<decimal?>("adx_lareplacedude").GetValueOrDefault(0),
s.GetAttributeValue<decimal?>("adx_longitude").GetValueOrDefault(0),
ServiceRequestHelpers.GetPushpinImageUrl(context, s),
ServiceRequestHelpers.GetCheckStatusUrl(s))).ToList();
}
var alertMapNodes = new List<MapNode>();
if (includeAlerts)
{
var alerts = context.CreateQuery("adx_311alert").Where(a =>
a.GetAttributeValue<decimal?>("adx_lareplacedude") != null && a.GetAttributeValue<decimal?>("adx_longitude") != null && a.GetAttributeValue<bool?>("adx_publishtoweb").GetValueOrDefault(false) == true)
.FilterAlertsByDate(dateFilterCode, fromDate, toDate.AddDays(1)).ToList();
if (alerts.Any())
{
var alertIconImageUrl = ServiceRequestHelpers.GetAlertPushpinImageUrl();
alertMapNodes = alerts.Select(a => new MapNode(MapNode.NodeType.Alert, a.GetAttributeValue<string>("adx_name"), a.GetAttributeValue<string>("adx_address1_line1"), a.GetAttributeValue<string>("adx_description"), a.GetAttributeValue<DateTime?>("adx_scheduledstartdate"), a.GetAttributeValue<DateTime?>("adx_scheduledenddate"), a.GetAttributeValue<decimal?>("adx_lareplacedude") ?? 0, a.GetAttributeValue<decimal?>("adx_longitude") ?? 0, alertIconImageUrl)).ToList();
}
}
var mapNodes = serviceRequestMapNodes.Union(alertMapNodes).ToList();
var json = Json(mapNodes);
return json;
}
19
View Source File : AduCalendar.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private DateTime TryParseToDateTime(string str)
{
DateTime dt = DateTime.MinValue;
if(DateTime.TryParse(str, out dt))
{
}
return dt;
}
19
View Source File : AduDateTimePicker.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
AduDateTimePicker dateTimePicker = (AduDateTimePicker)sender;
if (e.Property == ValueProperty)
{
DateTime dt = DateTime.Now;
if (DateTime.TryParse(Convert.ToString(e.NewValue), out dt))
{
dateTimePicker.SelectedDate = dt;
dateTimePicker.DisplayDate = dt;
dateTimePicker.PART_TimePicker.Value = dt;
string datetime = dt.ToString(dateTimePicker.DateFormat);
if (dateTimePicker.PART_TextBox != null)
{
dateTimePicker.PART_TextBox.Text = datetime;
if (string.IsNullOrEmpty(datetime))
{
dateTimePicker.PART_Calendar.SelectedDate = null;
dateTimePicker.Value = null;
}
else
{
dateTimePicker.PART_Calendar.SelectedDate = DateTime.Parse(datetime);
dateTimePicker.PART_Calendar.DisplayDate = DateTime.Parse(datetime);
}
}
}
}
else
{
dateTimePicker.PART_TextBox.Text = string.Empty;
dateTimePicker.PART_Calendar.SelectedDate = null;
dateTimePicker.Value = null;
}
}
19
View Source File : AduDateTimePicker.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private void SetCurrentData(string text)
{
DateTime dt = DateTime.Now;
if (DateTime.TryParse(text, out dt))
{
this.Value = dt;
}
else
{
this.Value = null;
}
}
19
View Source File : DateValidator.cs
License : MIT License
Project Creator : afucher
License : MIT License
Project Creator : afucher
public bool Validate(string value)
{
return DateTime.TryParse(value, out _);
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime ToDateTime(string name)
{
if (string.IsNullOrWhiteSpace(GetValue(name)))
{
AddMessage(name, "值不能为空");
Failed = true;
return DateTime.MinValue;
}
DateTime vl;
if (!DateTime.TryParse(GetValue(name), out vl))
{
AddMessage(name, "值无法转为日期");
Failed = true;
return DateTime.MinValue;
}
return vl;
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime ToDateTime(string name, DateTime def)
{
if (string.IsNullOrWhiteSpace(GetValue(name)))
{
return def;
}
DateTime vl;
if (!DateTime.TryParse(GetValue(name), out vl))
{
AddMessage(name, "值无法转为日期");
Failed = true;
return DateTime.MinValue;
}
return vl;
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime? ToNullDateTime(string name)
{
if (string.IsNullOrWhiteSpace(GetValue(name)))
{
return null;
}
DateTime vl;
if (!DateTime.TryParse(GetValue(name), out vl))
{
AddMessage(name, "值无法转为日期");
Failed = true;
return null;
}
return vl;
}
19
View Source File : ConfigurationManager.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime? GetDateTime(string key)
{
if (key == null)
{
return null;
}
var value = this[key];
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
if (DateTime.TryParse(value, out var vl)) return vl;
return null;
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime ToDateTime(string name)
{
if (string.IsNullOrWhiteSpace(GetValue(name)))
{
AddMessage(name, "值不能为空");
Failed = true;
return DateTime.MinValue;
}
if (!DateTime.TryParse(GetValue(name), out var vl))
{
AddMessage(name, "值无法转为日期");
Failed = true;
return DateTime.MinValue;
}
return vl;
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime ToDateTime(string name, DateTime def)
{
if (string.IsNullOrWhiteSpace(GetValue(name))) return def;
if (!DateTime.TryParse(GetValue(name), out var vl))
{
AddMessage(name, "值无法转为日期");
Failed = true;
return def;
}
return vl;
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public DateTime? ToNullDateTime(string name)
{
if (string.IsNullOrWhiteSpace(GetValue(name))) return null;
if (!DateTime.TryParse(GetValue(name), out var vl))
{
AddMessage(name, "值无法转为日期");
Failed = true;
return null;
}
return vl;
}
19
View Source File : PlanController.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
protected DateTime? GetDateArg(string name)
{
var value = GetArgValue(name);
if (string.IsNullOrEmpty(value) || value == "-" || value == "undefined" || value == "null" || !DateTime.TryParse(value, out var date))
{
return null;
}
return DateTime.Parse(value);
}
19
View Source File : PlanController.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
protected DateTime GetDateArg2(string name)
{
var value = GetArgValue(name);
if (string.IsNullOrEmpty(value) || value == "-" || value == "undefined" || value == "null" || !DateTime.TryParse(value,out var date))
{
return DateTime.MinValue;
}
return date;
}
19
View Source File : DateTimeConverter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DateTime.MinValue;
if (value is DateTime)
return value;
if (value is string)
{
if (DateTime.TryParse((string)value, out DateTime date))
return date;
}
return DateTime.MinValue;
}
19
View Source File : ParserBase.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
protected virtual DateTime ParseDate(string date, string[] formats)
{
if (!DateTime.TryParse(date, out var parsedDate))
DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate);
return parsedDate;
}
19
View Source File : ThePirateBayParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
protected override DateTime ParseDate(string date, string[] formats)
{
var yesterdayFormat = "'Y-day' HH:mm";
if (DateTime.TryParseExact(date, yesterdayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDate))
return parsedDate.AddDays(-1);
if (!DateTime.TryParse(date, out parsedDate))
DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate);
return parsedDate;
}
19
View Source File : GetValueFromJsonString.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected override void Execute(CodeActivityContext context)
{
var workflowContext = context.GetExtension<IWorkflowContext>();
if (!string.IsNullOrEmpty(JsonString.Get<string>(context)) && !string.IsNullOrEmpty(JsonPath.Get<string>(context)))
{
JObject jsonObject = JObject.Parse(JsonString.Get<string>(context));
JToken token = jsonObject.SelectToken(JsonPath.Get<string>(context));
if(token != null)
{
string value = (string)token;
Result_Text.Set(context, value);
Guid id = new Guid();
if (Guid.TryParse(value, out id))
{
this.Result_Guid.Set(context, value);
}
DateTime dateTime = new DateTime();
if (DateTime.TryParse(value, out dateTime))
{
this.Result_DateTime.Set(context, dateTime);
}
decimal decimalValue = new decimal();
if (decimal.TryParse(value, out decimalValue))
{
this.Result_Decimal.Set(context, decimalValue);
try
{
this.Result_Money.Set(context, new Money(decimalValue));
}
catch { }
}
double doubleValue = new double();
if (double.TryParse(value, out doubleValue))
{
this.Result_Double.Set(context, doubleValue);
}
int intValue = 0;
if (int.TryParse(value, out intValue))
{
this.Result_WholeNumber.Set(context, intValue);
}
}
}
}
19
View Source File : QueryGetResults.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected virtual void SetSingleValueResults(DataTable table, CodeActivityContext context)
{
string innerValue = String.Empty;
if (table.Rows.Count > 0)
{
this.QueryResult_Text.Set(context, table.Rows[0][0].ToString());
innerValue = table.Rows[0][1].ToString();
}
Guid id = new Guid();
if (Guid.TryParse(innerValue, out id))
{
this.QueryResult_Guid.Set(context, innerValue);
}
DateTime dateTime = new DateTime();
if (DateTime.TryParse(innerValue, out dateTime))
{
this.QueryResult_DateTime.Set(context, dateTime);
}
decimal decimalValue = new decimal();
if (decimal.TryParse(innerValue, out decimalValue))
{
this.QueryResult_Decimal.Set(context, decimalValue);
try
{
this.QueryResult_Money.Set(context, new Money(decimalValue));
}
catch { }
}
double doubleValue = new double();
if (double.TryParse(innerValue, out doubleValue))
{
this.QueryResult_Double.Set(context, doubleValue);
}
int intValue = 0;
if (int.TryParse(innerValue, out intValue))
{
this.QueryResult_WholeNumber.Set(context, intValue);
}
}
19
View Source File : ChineseIdCardNumberAttribute.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
private static bool CheckIDCard15(string id)
{
if (!long.TryParse(id, out var n) || n < Math.Pow(10, 14))
{
return false;//数字验证
}
if (AddressCode.IndexOf(id.Remove(2)) == -1)
{
return false;//省份验证
}
var birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
if (!DateTime.TryParse(birth, out var _))
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
19
View Source File : ChineseIdCardNumberAttribute.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
private static bool CheckIDCard18(string id)
{
if (!long.TryParse(id.Remove(17), out var n) || n < Math.Pow(10, 16) || !long.TryParse(id.Replace('x', '0').Replace('X', '0'), out _))
{
return false;//数字验证
}
if (AddressCode.IndexOf(id.Remove(2)) == -1)
{
return false;//省份验证
}
var birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
if (!DateTime.TryParse(birth, out _))
{
return false;//生日验证
}
var varifyCodes = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
var wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
var ai = id.Remove(17).ToCharArray();
var sum = 0;
for (var i = 0; i < 17; i++)
{
sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
}
Math.DivRem(sum, 11, out int y);
if (varifyCodes[y] != id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
19
View Source File : DateTimeRangeAttribute.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public override bool IsValid(object value)
{
if (value == null) return true;
var stringValue = value.ToString();
if (stringValue.IsNullOrWhiteSpace()) return true;
if (DateTime.TryParse(stringValue, out var nativeValue))
{
return nativeValue >= Minimum && nativeValue <= Maximum;
}
return false;
}
19
View Source File : DHLProvider.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
private void ParseRates(IEnumerable<XElement> rates)
{
var includedServices = _configuration.ServicesIncluded;
var excludedServices = _configuration.ServicesExcluded;
foreach (var rateNode in rates)
{
var serviceCode = rateNode.Element("GlobalProductCode")?.Value;
if (string.IsNullOrEmpty(serviceCode) || !AvailableServices.ContainsKey(serviceCode[0]))
{
AddInternalError($"Unknown DHL Global Product Code: {serviceCode}");
continue;
}
if ((includedServices.Any() && !includedServices.Contains(serviceCode[0])) ||
(excludedServices.Any() && excludedServices.Contains(serviceCode[0])))
{
continue;
}
var name = rateNode.Element("ProductShortName")?.Value;
var description = AvailableServices[serviceCode[0]];
var totalCharges = Convert.ToDecimal(rateNode.Element("ShippingCharge")?.Value, CultureInfo.InvariantCulture);
var currencyCode = rateNode.Element("CurrencyCode")?.Value;
var deliveryDateValue = rateNode.XPathSelectElement("DeliveryDate")?.Value;
var deliveryTimeValue = rateNode.XPathSelectElement("DeliveryTime")?.Value;
if (!DateTime.TryParse(deliveryDateValue, out DateTime deliveryDate))
deliveryDate = DateTime.MaxValue;
if (!string.IsNullOrEmpty(deliveryTimeValue) && deliveryTimeValue.Length >= 4)
{
// Parse PTxxH or PTxxHyyM to time
var indexOfH = deliveryTimeValue.IndexOf('H');
if (indexOfH >= 3)
{
var hours = int.Parse(deliveryTimeValue.Substring(2, indexOfH - 2), CultureInfo.InvariantCulture);
var minutes = 0;
var indexOfM = deliveryTimeValue.IndexOf('M');
if (indexOfM > indexOfH)
{
minutes = int.Parse(deliveryTimeValue.Substring(indexOfH + 1, indexOfM - indexOfH - 1), CultureInfo.InvariantCulture);
}
deliveryDate = deliveryDate.Date + new TimeSpan(hours, minutes, 0);
}
}
AddRate(name, description, totalCharges, deliveryDate, new RateOptions()
{
SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
},
currencyCode);
}
}
19
View Source File : USPSProvider.cs
License : MIT License
Project Creator : alexeybusygin
License : MIT License
Project Creator : alexeybusygin
private void ParseResult(string response, IList<SpecialServices> includeSpecialServiceCodes = null)
{
var doreplacedent = XElement.Parse(response, LoadOptions.None);
var rates = from item in doreplacedent.Descendants("Postage")
group item by (string) item.Element("MailService")
into g
select new {Name = g.Key,
TotalCharges = g.Sum(x => decimal.Parse((string) x.Element("Rate"))),
TotalCommercialCharges = g.Sum(x => decimal.Parse((string) x.Element("CommercialRate") ?? "0")),
DeliveryDate = g.Select(x => (string) x.Element("CommitmentDate")).FirstOrDefault(),
SpecialServices = g.Select(x => x.Element("SpecialServices")).FirstOrDefault() };
foreach (var r in rates)
{
//string name = r.Name.Replace(REMOVE_FROM_RATE_NAME, string.Empty);
var name = Regex.Replace(r.Name, "<.*>", "");
var additionalCharges = 0.0m;
if (includeSpecialServiceCodes != null && includeSpecialServiceCodes.Count > 0 && r.SpecialServices != null)
{
var specialServices = r.SpecialServices.XPathSelectElements("SpecialService").ToList();
if (specialServices.Count > 0)
{
foreach (var specialService in specialServices)
{
var serviceId = (int)specialService.Element("ServiceID");
var price = decimal.Parse((string) specialService.Element("Price"));
if (includeSpecialServiceCodes.Contains((SpecialServices)serviceId))
additionalCharges += price;
}
}
}
var isNegotiatedRate = _service == Services.Online && r.TotalCommercialCharges > 0;
var totalCharges = isNegotiatedRate ? r.TotalCommercialCharges : r.TotalCharges;
if (r.DeliveryDate != null && DateTime.TryParse(r.DeliveryDate, out DateTime deliveryDate))
{
var rateOptions = new RateOptions()
{
SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
};
AddRate(name, string.Concat("USPS ", name), totalCharges + additionalCharges, deliveryDate, rateOptions, USPSCurrencyCode);
}
else
{
AddRate(name, string.Concat("USPS ", name), totalCharges + additionalCharges, DateTime.Now.AddDays(30), null, USPSCurrencyCode);
}
}
//check for errors
ParseErrors(doreplacedent);
}
19
View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public static DateTime ToDate(this object thisValue, DateTime errorValue)
{
DateTime reval;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
19
View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public static DateTime ToDate(this object thisValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
reval = Convert.ToDateTime(thisValue);
}
return reval;
}
19
View Source File : SessionController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[HttpGet]
[Route("remaining")]
public int GetRemainingSessionTime()
{
HttpContext ctx = _httpContextAccessor.HttpContext;
ctx.Request.Cookies.TryGetValue(_settings.SessionTimeoutCookieName, out string remainingString);
if (string.IsNullOrEmpty(remainingString) || !DateTime.TryParse(remainingString, out DateTime timeout))
{
return -1;
}
return (int)Math.Floor((timeout - DateTime.UtcNow).TotalMinutes);
}
19
View Source File : SessionController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[HttpGet]
[Route("keepalive")]
[Authorize]
public async Task<ActionResult> KeepAlive()
{
HttpContext ctx = _httpContextAccessor.HttpContext;
ctx.Request.Cookies.TryGetValue(_settings.SessionTimeoutCookieName, out string remainingString);
if (!DateTime.TryParse(remainingString, out DateTime timeout))
{
return Unauthorized();
}
if (DateTime.UtcNow >= timeout.AddMinutes(-2))
{
return Unauthorized();
}
HttpContext.Response.Cookies.Append(_settings.SessionTimeoutCookieName, DateTime.UtcNow.AddMinutes(_sessingExtensionInMinutes - 5).ToString());
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
HttpContext.User,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(_sessingExtensionInMinutes),
IsPersistent = false,
AllowRefresh = false,
});
return Ok(_sessingExtensionInMinutes);
}
19
View Source File : Response.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public static Response Get(ResourceRef res, NameValueCollection param = null, AccessToken token = null, string responseType = "application/json", Response previous = null, CancellationToken ct = default)
{
// Create request.
var request = WebRequest.Create(res.Uri);
request.CachePolicy = CachePolicy;
request.Proxy = null;
if (token != null)
token.AddToRequest(request);
if (request is HttpWebRequest httpRequest)
{
httpRequest.UserAgent = UserAgent;
httpRequest.Accept = responseType;
if (previous != null && param != null)
{
httpRequest.IfModifiedSince = previous.Timestamp;
if (previous.ETag != null)
httpRequest.Headers.Add("If-None-Match", previous.ETag);
}
}
if (param != null)
{
// Send data.
UTF8Encoding utf8 = new UTF8Encoding();
var binBody = Encoding.ASCII.GetBytes(string.Join("&", param.Cast<string>().Select(e => string.Format("{0}={1}", HttpUtility.UrlEncode(e, utf8), HttpUtility.UrlEncode(param[e], utf8)))));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = binBody.Length;
try
{
using (var requestStream = request.GetRequestStream())
requestStream.Write(binBody, 0, binBody.Length, ct);
}
catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorUploading, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
}
ct.ThrowIfCancellationRequested();
// Wait for data to start comming in.
WebResponse response;
try { response = request.GetResponse(); }
catch (WebException ex)
{
// When the content was not modified, return the previous one.
if (ex.Response is HttpWebResponse httpResponse)
{
if (httpResponse.StatusCode == HttpStatusCode.NotModified)
{
previous.IsFresh = false;
return previous;
}
throw new WebExceptionEx(ex, ct);
}
throw new AggregateException(Resources.Strings.ErrorDownloading, ex);
}
ct.ThrowIfCancellationRequested();
using (response)
{
// Read the data.
var data = new byte[0];
using (var stream = response.GetResponseStream())
{
var buffer = new byte[1048576];
for (; ; )
{
// Read data chunk.
var count = stream.Read(buffer, 0, buffer.Length, ct);
if (count == 0)
break;
// Append it to the data.
var newData = new byte[data.LongLength + count];
Array.Copy(data, newData, data.LongLength);
Array.Copy(buffer, 0, newData, data.LongLength, count);
data = newData;
}
}
if (res.PublicKeys != null)
{
// Generate signature URI.
var uriBuilderSig = new UriBuilder(res.Uri);
uriBuilderSig.Path += ".minisig";
// Create signature request.
request = WebRequest.Create(uriBuilderSig.Uri);
request.CachePolicy = CachePolicy;
request.Proxy = null;
if (token != null)
token.AddToRequest(request);
if (request is HttpWebRequest httpRequestSig)
{
httpRequestSig.UserAgent = UserAgent;
httpRequestSig.Accept = "text/plain";
}
// Read the Minisign signature.
byte[] signature = null;
try
{
using (var responseSig = request.GetResponse())
using (var streamSig = responseSig.GetResponseStream())
{
ct.ThrowIfCancellationRequested();
using (var readerSig = new StreamReader(streamSig))
{
foreach (var l in readerSig.ReadToEnd(ct).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (l.Trim().StartsWith($"untrusted comment:"))
continue;
signature = Convert.FromBase64String(l);
break;
}
if (signature == null)
throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
}
}
}
catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorDownloadingSignature, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
ct.ThrowIfCancellationRequested();
// Verify Minisign signature.
using (var s = new MemoryStream(signature, false))
using (var r = new BinaryReader(s))
{
if (r.ReadChar() != 'E')
throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
byte[] payload;
switch (r.ReadChar())
{
case 'd': // PureEdDSA
payload = data;
break;
case 'D': // HashedEdDSA
payload = new eduEd25519.BLAKE2b(512).ComputeHash(data);
break;
default:
throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
}
ulong keyId = r.ReadUInt64();
if (!res.PublicKeys.ContainsKey(keyId))
throw new SecurityException(Resources.Strings.ErrorUntrustedMinisignPublicKey);
var sig = new byte[64];
if (r.Read(sig, 0, 64) != 64)
throw new ArgumentException(Resources.Strings.ErrorInvalidMinisignSignature);
using (eduEd25519.ED25519 key = new eduEd25519.ED25519(res.PublicKeys[keyId]))
if (!key.VerifyDetached(payload, sig))
throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
}
}
return
response is HttpWebResponse webResponse ?
new Response()
{
Value = Encoding.UTF8.GetString(data),
Timestamp = DateTime.TryParse(webResponse.GetResponseHeader("Last-Modified"), out var timestamp) ? timestamp : default,
ETag = webResponse.GetResponseHeader("ETag"),
IsFresh = true
} :
new Response()
{
Value = Encoding.UTF8.GetString(data),
IsFresh = true
};
}
}
19
View Source File : Response.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public void ReadXml(XmlReader reader)
{
string v;
Value = reader[nameof(Value)];
Timestamp = DateTime.TryParse(reader[nameof(Timestamp)], out var timestamp) ? timestamp : default;
ETag = reader[nameof(ETag)];
IsFresh = (v = reader[nameof(IsFresh)]) != null && bool.TryParse(v, out var isFresh) && isFresh;
}
19
View Source File : UtilConvert.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static DateTime ObjToDate(this object thisValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
reval = Convert.ToDateTime(thisValue);
}
return reval;
}
19
View Source File : UtilConvert.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static DateTime ObjToDate(this object thisValue, DateTime errorValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
19
View Source File : StatisticsDatabase.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 Task LoadRankingsAsync()
{
const string TimestampFileUri = @"https://drive.google.com/uc?id=1bauam699-r3vfVgFLsUOSrVUnUy2BWsc&export=download";
const string DatabaseFileUri = @"https://drive.google.com/uc?id=1PZ8oPbk0XLgODI_PwoEXjAZllY2upzbm&export=download";
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls;
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
var timestamp = $"{this.RankingDatabaseFileName}.timestamp.txt";
var timestampTemp = $"{this.RankingDatabaseFileName}.timestamp_temp.txt";
var database = this.RankingDatabaseFileName;
var databaseTemp = this.RankingDatabaseFileName + ".temp";
try
{
using (var client = new WebClient())
{
deleteFile(timestampTemp);
await client.DownloadFileTaskAsync(new Uri(TimestampFileUri), timestampTemp);
DateTime oldTimestamp = DateTime.MinValue, newTimestamp = DateTime.MinValue;
if (File.Exists(timestamp))
{
DateTime.TryParse(File.ReadAllText(timestamp), out oldTimestamp);
}
DateTime.TryParse(File.ReadAllText(timestampTemp), out newTimestamp);
if (oldTimestamp >= newTimestamp)
{
this.Log("[FFLogs] statistics database is up-to-date.");
return;
}
deleteFile(databaseTemp);
await client.DownloadFileTaskAsync(new Uri(DatabaseFileUri), databaseTemp);
lock (DatabaseAccessLocker)
{
File.Copy(databaseTemp, database, true);
File.Copy(timestampTemp, timestamp, true);
}
this.Log("[FFLogs] statistics database is updated.");
}
}
catch (Exception ex)
{
Logger.Error(ex, "[FFLogs] error downloding statistics database.");
}
finally
{
deleteFile(timestampTemp);
deleteFile(databaseTemp);
}
void deleteFile(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
}
19
View Source File : TickerModel.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
private void Sync(
string logline,
string syncTarget)
{
if (logline.Length < 14)
{
return;
}
var text = logline.Substring(0, 14)
.Replace("[", string.Empty)
.Replace("]", string.Empty);
if (!DateTime.TryParse(text, out DateTime timestamp))
{
return;
}
var nextTick = timestamp.AddSeconds(TickerGlobalInterval);
if (nextTick <= DateTime.Now)
{
return;
}
this.lastSyncTimestamp = DateTime.Now;
Task.Run(() =>
{
Thread.Sleep(nextTick - DateTime.Now);
this.RestartTickerCallback?.Invoke();
this.AppLogger.Trace($"3s ticker synced to {syncTarget}.");
});
}
19
View Source File : AppLog.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public static void AppendLog(
string dateTime,
string level,
string callsite,
string message)
{
DateTime d;
DateTime.TryParse(dateTime, out d);
var entry = new AppLogEntry()
{
DateTime = d,
Level = level,
CallSite = callsite,
Message = message,
};
lock (AppLog.locker)
{
if (AppLog.logBuffer.Count > LogBufferSize)
{
AppLog.logBuffer.RemoveRange(0, LogBufferMargin);
}
AppLog.logBuffer.Add(entry);
}
WPFHelper.BeginInvoke(() =>
AppLog.OnAppendedLog(new AppendedLogEventArgs(entry)));
}
19
View Source File : BufferedWavePlayer.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public static void LoadTTSHistory()
{
var file = TTSHistoryFileName;
if (!File.Exists(file))
{
return;
}
lock (WaveBuffer)
{
var lines = File.ReadAllLines(file, new UTF8Encoding(false));
foreach (var line in lines)
{
var values = line.Split('\t');
if (values.Length < 2)
{
continue;
}
var key = values[0];
if (!DateTime.TryParse(values[1], out DateTime timestamp))
{
continue;
}
var keySplits = key.Split('-');
if (keySplits.Length < 2)
{
continue;
}
var waveFile = keySplits[0];
if (!File.Exists(waveFile))
{
continue;
}
WaveBuffer[key] = new WaveDataContainer()
{
LastAccessTimestamp = timestamp
};
}
}
}
See More Examples