Here are the examples of the csharp api System.DateTime.ToUniversalTime() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3688 Examples
19
View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static long ToTimestamp(this DateTime time, TimestampUnit timestampUnit = TimestampUnit.Second)
{
var span = (time.ToUniversalTime() - Jan1St1970);
return (long)(timestampUnit == TimestampUnit.Second ? span.TotalSeconds : span.TotalMilliseconds);
}
19
View Source File : BssomBinaryPrimitives.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteDateTime(IBssomBufferWriter writer, DateTime value)
{
if (value.Kind == DateTimeKind.Local)
{
value = value.ToUniversalTime();
}
long utcTicks = value.Ticks - DateTimeConstants.UnixSeconds;
long utcSeconds = utcTicks / TimeSpan.TicksPerSecond;
long utcNanoseconds = utcTicks % TimeSpan.TicksPerSecond;
ref byte destination = ref writer.GetRef(StandardDateTimeSize);
WriteInt64LittleEndian(ref destination, utcSeconds);
WriteUInt32LittleEndian(ref Unsafe.Add(ref destination, 8), (uint)utcNanoseconds);
writer.Advance(StandardDateTimeSize);
}
19
View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static long ToTimestamp(this DateTime dateTime, bool milliseconds = false)
{
var ts = dateTime.ToUniversalTime() - DateTimeHelper.TimestampStart;
return (long)(milliseconds ? ts.TotalMilliseconds : ts.TotalSeconds);
}
19
View Source File : ExtensionMethod.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
public static DateTime UnixTimeStampToDateTimeUtc(this double unixTimeStamp)
{
// Unix timestamp is seconds past epoch
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(unixTimeStamp).ToUniversalTime();
return dateTime;
}
19
View Source File : RedisDate.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static TimeSpan ToTimestamp(DateTime date)
{
return date.ToUniversalTime().Subtract(_epoch);
}
19
View Source File : GlobalExtensions.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
public static string ToGmtISO8601(this DateTime time) {
return time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
}
19
View Source File : GlobalExtensions.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
public static long GetTime(this DateTime time) {
return (long)time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
}
19
View Source File : GlobalExtensions.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
public static long GetTimeMilliseconds(this DateTime time) {
return (long)time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
private static async Task RunAsync()
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
var pageid = await GetPageID(result.AccessToken);
while (true)
{
Console.Write("#> ");
string input = null;
input = Console.ReadLine().Trim();
while (input != null && input != "")
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await CreateTask(result.AccessToken, pageid,input);
input = null;
Thread.Sleep(2000);
}
}
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
string userid = await GetUserID(result.AccessToken, ConfigurationManager.AppSettings["User"].ToString());
string mailfolderid = await GetFolderID(result.AccessToken, userid, ConfigurationManager.AppSettings["FolderName"].ToString());
while (true)
{
Console.Write("#> ");
string input = null;
input = Console.ReadLine().Trim();
while (input != null && input != "")
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await SendMessage(result.AccessToken, userid, mailfolderid, input);
Thread.Sleep(2000);
string output = null;
while (output == null)
{
output = await ReadMessage(result.AccessToken, userid, mailfolderid);
if (output != null & output != "")
{
Console.WriteLine(output);
}
}
input = null;
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
var pageid = await GetPageID(result.AccessToken);
while (true)
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await GetTask(result.AccessToken, pageid);
Thread.Sleep(2000);
}
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
var httpClient = new HttpClient();
var apiCaller = new ProtectedApiCallHelper(httpClient);
string userid = await GetUserID(result.AccessToken, ConfigurationManager.AppSettings["User"].ToString());
string mailfolderid = await GetFolderID(result.AccessToken, userid, ConfigurationManager.AppSettings["FolderName"].ToString());
while (true)
{
string input = null;
while (input == null)
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
input = await ReadMessage(result.AccessToken, userid, mailfolderid);
if (input != null & input != "")
{
try
{
var output = ShellExecuteWithPath(input, @"c:\\windows\system32\");
await SendMessage(result.AccessToken, userid, mailfolderid, output);
}
catch(Exception ex)
{
await SendMessage(result.AccessToken, userid, mailfolderid, ex.Message);
//Console.WriteLine(ex.Message);
}
}
Thread.Sleep(2000);
}
}
}
}
catch(Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
string groupid = await GetGroupDetails(result.AccessToken, ConfigurationManager.AppSettings["GroupName"].ToString());
string channelid = await GetChannelDetails(result.AccessToken, groupid);
while (true)
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await GetMessage(result.AccessToken, groupid, channelid);
Thread.Sleep(2000);
}
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
19
View Source File : Common.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static long UnixTimeStampUtc()
{
var currentTime = DateTime.Now;
var dt = currentTime.ToUniversalTime();
var unixEpoch = new DateTime(1970, 1, 1);
var unixTimeStamp = (Int32)(dt.Subtract(unixEpoch)).TotalSeconds;
return unixTimeStamp;
}
19
View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public static void SerializeTo(ref TupleWriter writer, DateTime value)
{
// The problem of serializing DateTime: TimeZone? Precision?
// - Since we are going to lose the TimeZone infos anyway, we can just store everything in UTC and let the caller deal with it
// - DateTime in .NET uses Ticks which produce numbers too large to fit in the 56 bits available in JavaScript
// - Most other *nix uses the number of milliseconds since 1970-Jan-01 UTC, but if we store as an integer we will lose some precision (rounded to nearest millisecond)
// - We could store the number of milliseconds as a floating point value, which would require support of Floating Points in the Tuple Encoding (currently a Draft)
// - Other database engines store dates as a number of DAYS since Epoch, using a floating point number. This allows for quickly extracting the date by truncating the value, and the time by using the decimal part
// Right now, we will store the date as the number of DAYS since Epoch, using a 64-bit float.
// => storing a number of ticks would be MS-only anyway (56-bit limit in JS)
// => JS binding MAY support decoding of 64-bit floats in the future, in which case the value would be preserved exactly.
const long UNIX_EPOCH_EPOCH = 621355968000000000L;
double ms = (value.ToUniversalTime().Ticks - UNIX_EPOCH_EPOCH) / (double)TimeSpan.TicksPerDay;
FdbTupleParser.WriteDouble(ref writer, ms);
}
19
View Source File : EventSQLWriter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void CreateSQLINSERTStatement(Event input, StreamWriter writer)
{
writer.WriteLine("INSERT INTO `event` (`name`, `start_Time`, `end_Time`, `state`, `last_Modified`)");
var output = "VALUES (" +
$"{GetSQLString(input.Name)}, " +
$"{(input.StartTime == -1 ? $"{input.StartTime}" : $"{input.StartTime} /* {DateTimeOffset.FromUnixTimeSeconds(input.StartTime).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture)} */")}, " +
$"{(input.EndTime == -1 ? $"{input.EndTime}" : $"{input.EndTime} /* {DateTimeOffset.FromUnixTimeSeconds(input.EndTime).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture)} */")}, " +
$"{input.State}, " +
$"'{input.LastModified:yyyy-MM-dd HH:mm:ss}'" +
");";
output = FixNullFields(output);
writer.WriteLine(output);
}
19
View Source File : PropertyInt.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static string GetValueEnumName(this PropertyInt property, int value)
{
switch (property)
{
case PropertyInt.ActivationResponse:
return System.Enum.GetName(typeof(ActivationResponse), value);
case PropertyInt.AetheriaBitfield:
return System.Enum.GetName(typeof(AetheriaBitfield), value);
case PropertyInt.AttackHeight:
return System.Enum.GetName(typeof(AttackHeight), value);
case PropertyInt.AttackType:
return System.Enum.GetName(typeof(AttackType), value);
case PropertyInt.Attuned:
return System.Enum.GetName(typeof(AttunedStatus), value);
case PropertyInt.AmmoType:
return System.Enum.GetName(typeof(AmmoType), value);
case PropertyInt.Bonded:
return System.Enum.GetName(typeof(BondedStatus), value);
case PropertyInt.ChannelsActive:
case PropertyInt.ChannelsAllowed:
return System.Enum.GetName(typeof(Channel), value);
case PropertyInt.CombatMode:
return System.Enum.GetName(typeof(CombatMode), value);
case PropertyInt.DefaultCombatStyle:
case PropertyInt.AiAllowedCombatStyle:
return System.Enum.GetName(typeof(CombatStyle), value);
case PropertyInt.CombatUse:
return System.Enum.GetName(typeof(CombatUse), value);
case PropertyInt.ClothingPriority:
return System.Enum.GetName(typeof(CoverageMask), value);
case PropertyInt.CreatureType:
case PropertyInt.SlayerCreatureType:
case PropertyInt.FoeType:
case PropertyInt.FriendType:
return System.Enum.GetName(typeof(CreatureType), value);
case PropertyInt.DamageType:
return System.Enum.GetName(typeof(DamageType), value);
case PropertyInt.CurrentWieldedLocation:
case PropertyInt.ValidLocations:
return System.Enum.GetName(typeof(EquipMask), value);
case PropertyInt.EquipmentSetId:
return System.Enum.GetName(typeof(EquipmentSet), value);
case PropertyInt.Gender:
return System.Enum.GetName(typeof(Gender), value);
case PropertyInt.GeneratorDestructionType:
case PropertyInt.GeneratorEndDestructionType:
return System.Enum.GetName(typeof(GeneratorDestruct), value);
case PropertyInt.GeneratorTimeType:
return System.Enum.GetName(typeof(GeneratorTimeType), value);
case PropertyInt.GeneratorType:
return System.Enum.GetName(typeof(GeneratorType), value);
case PropertyInt.HeritageGroup:
case PropertyInt.HeritageSpecificArmor:
return System.Enum.GetName(typeof(HeritageGroup), value);
case PropertyInt.HookType:
return System.Enum.GetName(typeof(HookType), value);
case PropertyInt.HouseType:
return System.Enum.GetName(typeof(HouseType), value);
case PropertyInt.ImbuedEffect:
case PropertyInt.ImbuedEffect2:
case PropertyInt.ImbuedEffect3:
case PropertyInt.ImbuedEffect4:
case PropertyInt.ImbuedEffect5:
return System.Enum.GetName(typeof(ImbuedEffectType), value);
case PropertyInt.HookItemType:
case PropertyInt.ItemType:
case PropertyInt.MerchandiseItemTypes:
case PropertyInt.TargetType:
return System.Enum.GetName(typeof(ItemType), value);
case PropertyInt.ItemXpStyle:
return System.Enum.GetName(typeof(ItemXpStyle), value);
case PropertyInt.MaterialType:
return System.Enum.GetName(typeof(MaterialType), value);
case PropertyInt.PaletteTemplate:
return System.Enum.GetName(typeof(PaletteTemplate), value);
case PropertyInt.PhysicsState:
return System.Enum.GetName(typeof(PhysicsState), value);
case PropertyInt.HookPlacement:
case PropertyInt.Placement:
case PropertyInt.PCAPRecordedPlacement:
return System.Enum.GetName(typeof(Placement), value);
case PropertyInt.PortalBitmask:
return System.Enum.GetName(typeof(PortalBitmask), value);
case PropertyInt.PlayerKillerStatus:
return System.Enum.GetName(typeof(PlayerKillerStatus), value);
case PropertyInt.BoosterEnum:
return System.Enum.GetName(typeof(PropertyAttribute2nd), value);
case PropertyInt.ShowableOnRadar:
return System.Enum.GetName(typeof(RadarBehavior), value);
case PropertyInt.RadarBlipColor:
return System.Enum.GetName(typeof(RadarColor), value);
case PropertyInt.WeaponSkill:
case PropertyInt.WieldSkillType:
case PropertyInt.WieldSkillType2:
case PropertyInt.WieldSkillType3:
case PropertyInt.WieldSkillType4:
case PropertyInt.AppraisalItemSkill:
return System.Enum.GetName(typeof(Skill), value);
case PropertyInt.AccountRequirements:
return System.Enum.GetName(typeof(SubscriptionStatus), value);
case PropertyInt.SummoningMastery:
return System.Enum.GetName(typeof(SummoningMastery), value);
case PropertyInt.UiEffects:
return System.Enum.GetName(typeof(UiEffects), value);
case PropertyInt.ItemUseable:
return System.Enum.GetName(typeof(Usable), value);
case PropertyInt.WeaponType:
return System.Enum.GetName(typeof(WeaponType), value);
case PropertyInt.WieldRequirements:
case PropertyInt.WieldRequirements2:
case PropertyInt.WieldRequirements3:
case PropertyInt.WieldRequirements4:
return System.Enum.GetName(typeof(WieldRequirement), value);
case PropertyInt.GeneratorStartTime:
case PropertyInt.GeneratorEndTime:
return DateTimeOffset.FromUnixTimeSeconds(value).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
case PropertyInt.ArmorType:
return System.Enum.GetName(typeof(ArmorType), value);
case PropertyInt.ParentLocation:
return System.Enum.GetName(typeof(ParentLocation), value);
case PropertyInt.PlacementPosition:
return System.Enum.GetName(typeof(Placement), value);
case PropertyInt.HouseStatus:
return System.Enum.GetName(typeof(HouseStatus), value);
case PropertyInt.UseCreatesContractId:
return System.Enum.GetName(typeof(ContractId), value);
case PropertyInt.Faction1Bits:
case PropertyInt.Faction2Bits:
case PropertyInt.Faction3Bits:
case PropertyInt.Hatred1Bits:
case PropertyInt.Hatred2Bits:
case PropertyInt.Hatred3Bits:
return System.Enum.GetName(typeof(FactionBits), value);
case PropertyInt.UseRequiresSkill:
case PropertyInt.UseRequiresSkillSpec:
case PropertyInt.SkillToBeAltered:
return System.Enum.GetName(typeof(Skill), value);
case PropertyInt.HookGroup:
return System.Enum.GetName(typeof(HookGroupType), value);
//case PropertyInt.TypeOfAlteration:
// return System.Enum.GetName(typeof(SkillAlterationType), value);
}
return null;
}
19
View Source File : ServerManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static DateTime LogStatusUpdate(DateTime logUpdateTS, string logMessage)
{
if (logUpdateTS == DateTime.MinValue || DateTime.UtcNow > logUpdateTS.ToUniversalTime())
{
log.Info(logMessage);
logUpdateTS = DateTime.UtcNow.AddSeconds(10);
}
return logUpdateTS;
}
19
View Source File : GameActionQueryBirth.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[GameAction(GameActionType.QueryBirth)]
public static void Handle(ClientMessage message, Session session)
{
var target = message.Payload.ReadString16L();
DateTime playerDOB = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
playerDOB = playerDOB.AddSeconds(session.Player.CreationTimestamp.Value).ToUniversalTime();
var dobEvent = new GameMessages.Messages.GameMessageSystemChat($"You were born on {playerDOB:G}.", ChatMessageType.Broadcast);
session.Network.EnqueueSend(dobEvent);
}
19
View Source File : PrimitiveExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Int64 ToUnixEpochTime(this DateTime dateTime)
{
return Convert.ToInt64((dateTime.ToUniversalTime() - UnixEpoch).TotalSeconds);
}
19
View Source File : PropertyValidation.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static void ValidateDateTime(String propertyName, DateTime propertyValue)
{
// Let users get an out of range error for MinValue and MaxValue, not a DateTimeKind unspecified error.
if (propertyValue != DateTime.MinValue
&& propertyValue != DateTime.MaxValue)
{
if (propertyValue.Kind == DateTimeKind.Unspecified)
{
throw new VssPropertyValidationException("value", CommonResources.DateTimeKindMustBeSpecified());
}
// Make sure the property value is in Universal time.
if (propertyValue.Kind != DateTimeKind.Utc)
{
propertyValue = propertyValue.ToUniversalTime();
}
}
CheckRange(propertyValue, s_minAllowedDateTime, s_maxAllowedDateTime, propertyName, "value");
}
19
View Source File : JsonWebToken.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static JsonWebToken Create(string issuer, string audience, DateTime validFrom, DateTime validTo, DateTime issuedAt, IEnumerable<Claim> additionalClaims, JsonWebToken actor, string actorToken, VssSigningCredentials credentials, bool allowExpiredCertificate)
{
ArgumentUtility.CheckStringForNullOrEmpty(issuer, nameof(issuer));
ArgumentUtility.CheckStringForNullOrEmpty(audience, nameof(audience)); // Audience isn't actually required...
validFrom = validFrom == default(DateTime) ? DateTime.UtcNow : validFrom.ToUniversalTime();
validTo = validTo == default(DateTime) ? DateTime.UtcNow + TimeSpan.FromSeconds(DefaultLifetime) : validTo.ToUniversalTime();
//issuedAt is optional, and breaks certain scenarios if it is present, and breaks others if it is not.
//so only include it if it is explicitly set.
issuedAt = issuedAt == default(DateTime) ? default(DateTime) : issuedAt.ToUniversalTime();
JWTHeader header = GetHeader(credentials, allowExpiredCertificate);
JWTPayload payload = new JWTPayload(additionalClaims) { Issuer = issuer, Audience = audience, ValidFrom = validFrom, ValidTo = validTo, IssuedAt = issuedAt };
if (actor != null)
{
payload.Actor = actor;
}
else if (actorToken != null)
{
payload.ActorToken = actorToken;
}
byte[] signature = GetSignature(header, payload, header.Algorithm, credentials);
return new JsonWebToken(header, payload, signature);
}
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 : EntityFormFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static string TryConvertAttributeValueToString(OrganizationServiceContext context, Dictionary<string, AttributeTypeCode?> attributeTypeCodeDictionary, string enreplacedyName, string attributeName, object value)
{
if (context == null || string.IsNullOrWhiteSpace(enreplacedyName) || string.IsNullOrWhiteSpace(attributeName))
{
return string.Empty;
}
var newValue = string.Empty;
var attributeTypeCode = attributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;
if (attributeTypeCode == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Unable to recognize the attribute specified.");
return string.Empty;
}
try
{
switch (attributeTypeCode)
{
case AttributeTypeCode.BigInt:
newValue = value == null ? string.Empty : Convert.ToInt64(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Boolean:
newValue = value == null ? string.Empty : Convert.ToBoolean(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Customer:
if (value is EnreplacedyReference)
{
var enreplacedyref = value as EnreplacedyReference;
newValue = enreplacedyref.Id.ToString();
}
break;
case AttributeTypeCode.DateTime:
newValue = value == null ? string.Empty : Convert.ToDateTime(value).ToUniversalTime().ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Decimal:
newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Double:
newValue = value == null ? string.Empty : Convert.ToDouble(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Integer:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Lookup:
if (value is EnreplacedyReference)
{
var enreplacedyref = value as EnreplacedyReference;
newValue = enreplacedyref.Id.ToString();
}
break;
case AttributeTypeCode.Memo:
newValue = value as string;
break;
case AttributeTypeCode.Money:
newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Picklist:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.State:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Status:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.String:
newValue = value as string;
break;
case AttributeTypeCode.Uniqueidentifier:
if (value is Guid)
{
var id = (Guid)value;
newValue = id.ToString();
}
break;
default:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute type '{0}' is unsupported.", attributeTypeCode));
break;
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute specified is expecting a {0}. The value provided is not valid.", attributeTypeCode));
}
return newValue;
}
19
View Source File : EntityFormFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static dynamic TryConvertAttributeValue(OrganizationServiceContext context, string enreplacedyName, string attributeName, object value, Dictionary<string, AttributeTypeCode?> AttributeTypeCodeDictionary)
{
if (context == null || string.IsNullOrWhiteSpace(enreplacedyName) || string.IsNullOrWhiteSpace(attributeName)) return null;
if (AttributeTypeCodeDictionary == null || !AttributeTypeCodeDictionary.Any())
{
AttributeTypeCodeDictionary = MetadataHelper.BuildAttributeTypeCodeDictionary(context, enreplacedyName);
}
object newValue = null;
var attributeTypeCode = AttributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;
if (attributeTypeCode == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Unable to recognize the attribute '{0}' specified.", attributeName));
return null;
}
try
{
switch (attributeTypeCode)
{
case AttributeTypeCode.BigInt:
newValue = value == null ? (object)null : Convert.ToInt64(value);
break;
case AttributeTypeCode.Boolean:
newValue = value == null ? (object)null : Convert.ToBoolean(value);
break;
case AttributeTypeCode.Customer:
if (value is EnreplacedyReference)
{
newValue = value as EnreplacedyReference;
}
else if (value is Guid)
{
var metadata = MetadataHelper.GetEnreplacedyMetadata(context, enreplacedyName);
var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
if (attribute != null)
{
var lookupAttribute = attribute as LookupAttributeMetadata;
if (lookupAttribute != null && lookupAttribute.Targets.Length == 1)
{
var lookupEnreplacedyType = lookupAttribute.Targets[0];
newValue = new EnreplacedyReference(lookupEnreplacedyType, (Guid)value);
}
}
}
break;
case AttributeTypeCode.DateTime:
newValue = value == null ? (object)null : Convert.ToDateTime(value).ToUniversalTime();
break;
case AttributeTypeCode.Decimal:
newValue = value == null ? (object)null : Convert.ToDecimal(value);
break;
case AttributeTypeCode.Double:
newValue = value == null ? (object)null : Convert.ToDouble(value);
break;
case AttributeTypeCode.Integer:
newValue = value == null ? (object)null : Convert.ToInt32(value);
break;
case AttributeTypeCode.Lookup:
if (value is EnreplacedyReference)
{
newValue = value as EnreplacedyReference;
}
else if (value is Guid)
{
var metadata = MetadataHelper.GetEnreplacedyMetadata(context, enreplacedyName);
var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
if (attribute != null)
{
var lookupAttribute = attribute as LookupAttributeMetadata;
if (lookupAttribute != null && lookupAttribute.Targets.Length == 1)
{
var lookupEnreplacedyType = lookupAttribute.Targets[0];
newValue = new EnreplacedyReference(lookupEnreplacedyType, (Guid)value);
}
}
}
break;
case AttributeTypeCode.Memo:
newValue = value as string;
break;
case AttributeTypeCode.Money:
newValue = value == null ? (object)null : Convert.ToDecimal(value);
break;
case AttributeTypeCode.Picklist:
var plMetadata = MetadataHelper.GetEnreplacedyMetadata(context, enreplacedyName);
var plAttribute = plMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);
if (plAttribute != null)
{
var picklistAttribute = plAttribute as PicklistAttributeMetadata;
if (picklistAttribute != null)
{
int picklistInt;
OptionMetadata picklistValue;
if (int.TryParse(string.Empty + value, out picklistInt))
{
picklistValue = picklistAttribute.OptionSet.Options.FirstOrDefault(o => o.Value == picklistInt);
}
else
{
picklistValue = picklistAttribute.OptionSet.Options.FirstOrDefault(o => o.Label.GetLocalizedLabelString() == string.Empty + value);
}
if (picklistValue != null && picklistValue.Value.HasValue)
{
newValue = value == null ? null : new OptionSetValue(picklistValue.Value.Value);
}
}
}
break;
case AttributeTypeCode.State:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute '{0}' type '{1}' is unsupported. The state attribute is created automatically when the enreplacedy is created. The options available for this attribute are read-only.", attributeName, attributeTypeCode));
break;
case AttributeTypeCode.Status:
if (value == null)
{
return false;
}
var optionSetValue = new OptionSetValue(Convert.ToInt32(value));
newValue = optionSetValue;
break;
case AttributeTypeCode.String:
newValue = value as string;
break;
default:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute '{0}' type '{1}' is unsupported.", attributeName, attributeTypeCode));
break;
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute '{0}' specified is expecting a {1}. The value provided is not valid.", attributeName, attributeTypeCode));
}
return newValue;
}
19
View Source File : VCalendar.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AppendDateField(StringBuilder vevent, string name, DateTime? value)
{
if (value == null)
{
return;
}
AppendField(vevent, name, value.Value.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));
}
19
View Source File : IdeaForumDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual IEnumerable<IIdea> SelectIdeas(int startRowIndex = 0, int maximumRows = -1)
{
if (startRowIndex < 0)
{
throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
}
if (maximumRows == 0)
{
return new IIdea[] { };
}
var serviceContext = Dependencies.GetServiceContext();
var includeUnapprovedIdeas = TryreplacedertIdeaPreviewPermission(serviceContext);
var filter = new Filter
{
Conditions = new List<Condition>
{
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_ideaforumid", ConditionOperator.Equal, IdeaForum.Id)
}
};
var pageInfo = Cms.OrganizationServiceContextExtensions.GetPageInfo(startRowIndex, maximumRows);
var orders = new List<Order>
{
new Order(this.OrderAttribute, OrderType.Descending),
};
if (this.OrderAttribute != "adx_date")
{
orders.Add(new Order("adx_date", OrderType.Descending));
}
var fetch = new Fetch()
{
Enreplacedy = new FetchEnreplacedy
{
Name = "adx_idea",
Attributes = FetchAttribute.All,
Orders = orders,
Filters = new List<Filter>
{
filter
},
},
PageNumber = pageInfo.PageNumber,
PageSize = pageInfo.Count,
};
if (MaxDate.HasValue)
{
filter.Conditions.Add(new Condition("adx_date", ConditionOperator.LessThan, MaxDate.Value.ToUniversalTime().ToString(CultureInfo.InvariantCulture)));
}
if (MinDate.HasValue)
{
filter.Conditions.Add(new Condition("adx_date", ConditionOperator.GreaterThan, MinDate.Value.ToUniversalTime().ToString(CultureInfo.InvariantCulture)));
}
if (!includeUnapprovedIdeas)
{
filter.Conditions.Add(new Condition("adx_approved", ConditionOperator.Equal, "true"));
}
if (Status.HasValue)
{
filter.Conditions.Add(new Condition("statuscode", ConditionOperator.Equal, (int)Status.Value));
}
var collection = serviceContext.RetrieveMultiple(fetch, expiration: this.ExpirationDuration);
var query = collection.Enreplacedies.AsEnumerable();
if (!query.Any())
{
return new IIdea[] { };
}
return new IdeaFactory(serviceContext, Dependencies.GetHttpContext(), Dependencies.GetPortalUser()).Create(query);
}
19
View Source File : IdeaForumDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual int SelectIdeaCount()
{
var serviceContext = Dependencies.GetServiceContext();
var includeUnapprovedIdeas = TryreplacedertIdeaPreviewPermission(serviceContext);
return serviceContext.FetchCount("adx_idea", "adx_ideaid", addCondition =>
{
addCondition("adx_ideaforumid", "eq", IdeaForum.Id.ToString());
addCondition("statecode", "eq", "0");
if (!includeUnapprovedIdeas)
{
addCondition("adx_approved", "eq", "true");
}
if (Status.HasValue)
{
addCondition("statuscode", "eq", "{0}".FormatWith((int)Status.Value));
}
if (MaxDate.HasValue)
{
addCondition("adx_date", "le", MaxDate.Value.ToUniversalTime().ToString(CultureInfo.InvariantCulture));
}
if (MinDate.HasValue)
{
addCondition("adx_date", "ge", MinDate.Value.ToUniversalTime().ToString(CultureInfo.InvariantCulture));
}
});
}
19
View Source File : CmsEntitySetHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected JToken GetValueJson(object value)
{
var optionSetValue = value as OptionSetValue;
if (optionSetValue != null)
{
return new JValue(optionSetValue.Value);
}
var crmEnreplacedyReference = value as CrmEnreplacedyReference;
if (crmEnreplacedyReference != null)
{
return new JObject
{
{
"__metadata", new JObject
{
{ "type", new JValue(crmEnreplacedyReference.GetType().FullName) }
}
},
{ "Id", new JValue(crmEnreplacedyReference.Id) },
{ "LogicalName", new JValue(crmEnreplacedyReference.LogicalName) },
{ "Name", new JValue(crmEnreplacedyReference.Name) },
};
}
var enreplacedyReference = value as EnreplacedyReference;
if (enreplacedyReference != null)
{
return new JObject
{
{
"__metadata", new JObject
{
{ "type", new JValue(enreplacedyReference.GetType().FullName) }
}
},
{ "Id", new JValue(enreplacedyReference.Id) },
{ "LogicalName", new JValue(enreplacedyReference.LogicalName) },
{ "Name", new JValue(enreplacedyReference.Name) },
};
}
var dateTime = value as DateTime?;
if (dateTime != null)
{
return new JRaw(JsonConvert.SerializeObject(dateTime.Value.ToUniversalTime(), new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
}));
}
var money = value as Money;
if (money != null)
{
return new JValue(money.Value);
}
return new JValue(value);
}
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 : MetadataEntityAttributeUpdate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected object GetValue(JToken token, AttributeTypeCode attributeType)
{
var value = token.ToObject<object>();
if (value == null)
{
return null;
}
if (attributeType == AttributeTypeCode.Customer || attributeType == AttributeTypeCode.Lookup || attributeType == AttributeTypeCode.Owner)
{
EnreplacedyReference enreplacedyReference;
if (TryGetEnreplacedyReference(value, out enreplacedyReference))
{
return enreplacedyReference;
}
throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.LogicalName, typeof(EnreplacedyReference)));
}
// Option set values will be in Int64 form from the JSON deserialization -- convert those to OptionSetValues
// for option set attributes.
if (attributeType == AttributeTypeCode.EnreplacedyName || attributeType == AttributeTypeCode.Picklist || attributeType == AttributeTypeCode.State || attributeType == AttributeTypeCode.Status)
{
return new OptionSetValue(Convert.ToInt32(value));
}
if (attributeType == AttributeTypeCode.Memo || attributeType == AttributeTypeCode.String)
{
return value is string ? value : value.ToString();
}
if (attributeType == AttributeTypeCode.BigInt)
{
return Convert.ToInt64(value);
}
if (attributeType == AttributeTypeCode.Boolean)
{
return Convert.ToBoolean(value);
}
if (attributeType == AttributeTypeCode.DateTime)
{
var dateTimeValue = Convert.ToDateTime(value);
return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
}
if (attributeType == AttributeTypeCode.Decimal)
{
return Convert.ToDecimal(value);
}
if (attributeType == AttributeTypeCode.Double)
{
return Convert.ToDouble(value);
}
if (attributeType == AttributeTypeCode.Integer)
{
return Convert.ToInt32(value);
}
if (attributeType == AttributeTypeCode.Money)
{
return new Money(Convert.ToDecimal(value));
}
if (attributeType == AttributeTypeCode.Uniqueidentifier)
{
return value is Guid ? value : new Guid(value.ToString());
}
return value;
}
19
View Source File : ReflectionEntityAttributeUpdate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected object GetValue(JToken token, Type propertyType)
{
var value = token.ToObject<object>();
if (value == null)
{
return null;
}
if (propertyType == typeof(bool?))
{
return Convert.ToBoolean(value);
}
if (propertyType == typeof(CrmEnreplacedyReference))
{
EnreplacedyReference enreplacedyReference;
if (TryGetEnreplacedyReference(value, out enreplacedyReference))
{
return new CrmEnreplacedyReference(enreplacedyReference.LogicalName, enreplacedyReference.Id);
}
throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
}
if (propertyType == typeof(DateTime?))
{
var dateTimeValue = value is DateTime ? (DateTime)value : Convert.ToDateTime(value);
return dateTimeValue.Kind == DateTimeKind.Utc ? dateTimeValue : dateTimeValue.ToUniversalTime();
}
if (propertyType == typeof(double?))
{
return Convert.ToDouble(value);
}
if (propertyType == typeof(decimal))
{
return Convert.ToDecimal(value);
}
if (propertyType == typeof(EnreplacedyReference))
{
EnreplacedyReference enreplacedyReference;
if (TryGetEnreplacedyReference(value, out enreplacedyReference))
{
return enreplacedyReference;
}
throw new FormatException("Unable to convert value {0} for attribute {1} to {2}.".FormatWith(value, Attribute.CrmPropertyAttribute.LogicalName, typeof(EnreplacedyReference)));
}
if (propertyType == typeof(Guid?))
{
return value is Guid ? value : new Guid(value.ToString());
}
if (propertyType == typeof(int?))
{
return Convert.ToInt32(value);
}
if (propertyType == typeof(long?))
{
return Convert.ToInt64(value);
}
if (propertyType == typeof(string))
{
return value is string ? value : value.ToString();
}
if (propertyType.IsreplacedignableFrom(value.GetType()))
{
return value;
}
throw new InvalidOperationException("Unable to convert value of type".FormatWith(value.GetType(), propertyType, Attribute.CrmPropertyAttribute.LogicalName));
}
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 : DateFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static DateTime? DateToUtc(DateTime? date)
{
return date.HasValue
? date.Value.ToUniversalTime()
: (DateTime?)null;
}
19
View Source File : CrmProfileProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private Expression<Func<Enreplacedy, bool>> GetUserNameInactiveProfilePredicate(string usernameToMatch, DateTime userInactiveSinceDate)
{
if (!string.IsNullOrWhiteSpace(_attributeMapStateCode))
{
return enreplacedy => enreplacedy.GetAttributeValue<int>(_attributeMapStateCode) == 0
&& enreplacedy.GetAttributeValue<string>(_attributeMapUsername) == usernameToMatch
&& (
enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) == null
|| enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) <= userInactiveSinceDate.ToUniversalTime());
}
else if (!string.IsNullOrWhiteSpace(_attributeMapIsDisabled))
{
return enreplacedy => enreplacedy.GetAttributeValue<bool>(_attributeMapIsDisabled) == false
&& enreplacedy.GetAttributeValue<string>(_attributeMapUsername) == usernameToMatch
&& (
enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) == null
|| enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) <= userInactiveSinceDate.ToUniversalTime());
}
else
{
return enreplacedy => enreplacedy.GetAttributeValue<string>(_attributeMapUsername) == usernameToMatch
&& (
enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) == null
|| enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) <= userInactiveSinceDate.ToUniversalTime());
}
}
19
View Source File : CrmProfileProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private Expression<Func<Enreplacedy, bool>> GetInactiveProfilePredicate(DateTime userInactiveSinceDate)
{
if (!string.IsNullOrWhiteSpace(_attributeMapStateCode))
{
return enreplacedy => enreplacedy.GetAttributeValue<int>(_attributeMapStateCode) == 0
&& enreplacedy.GetAttributeValue<string>(_attributeMapUsername) != null
&& (
enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) == null
|| enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) <= userInactiveSinceDate.ToUniversalTime());
}
else if (!string.IsNullOrWhiteSpace(_attributeMapIsDisabled))
{
return enreplacedy => enreplacedy.GetAttributeValue<bool>(_attributeMapIsDisabled) == false
&& enreplacedy.GetAttributeValue<string>(_attributeMapUsername) != null
&& (
enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) == null
|| enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) <= userInactiveSinceDate.ToUniversalTime());
}
else
{
return enreplacedy => enreplacedy.GetAttributeValue<string>(_attributeMapUsername) != null
&& (
enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) == null
|| enreplacedy.GetAttributeValue<DateTime?>(_attributeMapLastActivityDate) <= userInactiveSinceDate.ToUniversalTime());
}
}
19
View Source File : Expression.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected bool Evaluate(Expression left, Expression right, Func<object, object, bool> compare, Func<object, Type, object> convert)
{
object testValue;
var attributeName = ((LeftLiteralExpression)left).Value as string;
var expressionValue = ((RightLiteralExpression)right).Value;
if (EvaluateEnreplacedy == null)
{
throw new NullReferenceException("EvaluateEnreplacedy is null.");
}
if (string.IsNullOrWhiteSpace(attributeName))
{
throw new InvalidOperationException(string.Format("Unable to recognize the attribute {0} specified in the expression.", attributeName));
}
var attributeTypeCode = AttributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;
if (attributeTypeCode == null)
{
throw new InvalidOperationException(string.Format("Unable to recognize the attribute {0} specified in the expression.", attributeName));
}
var attributeValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? EvaluateEnreplacedy.Attributes[attributeName] : null;
switch (attributeTypeCode)
{
case AttributeTypeCode.BigInt:
if (expressionValue != null && !(expressionValue is long | expressionValue is double))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToInt64(expressionValue);
break;
case AttributeTypeCode.Boolean:
if (expressionValue != null && !(expressionValue is bool))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : (bool)expressionValue;
break;
case AttributeTypeCode.Customer:
var enreplacedyReference = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (EnreplacedyReference)EvaluateEnreplacedy.Attributes[attributeName] : null;
attributeValue = enreplacedyReference != null ? (object)enreplacedyReference.Id : null;
if (expressionValue != null && !(expressionValue is Guid))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : (Guid)expressionValue;
break;
case AttributeTypeCode.DateTime:
if (expressionValue != null && !(expressionValue is DateTime))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : ((DateTime)expressionValue).ToUniversalTime();
break;
case AttributeTypeCode.Decimal:
if (expressionValue != null && !(expressionValue is int | expressionValue is double | expressionValue is decimal))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToDecimal(expressionValue);
break;
case AttributeTypeCode.Double:
if (expressionValue != null && !(expressionValue is int | expressionValue is double))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToDouble(expressionValue);
break;
case AttributeTypeCode.Integer:
if (expressionValue != null && !(expressionValue is int | expressionValue is double))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
break;
case AttributeTypeCode.Lookup:
var lookupEnreplacedyReference = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (EnreplacedyReference)EvaluateEnreplacedy.Attributes[attributeName] : null;
attributeValue = lookupEnreplacedyReference != null ? (object)lookupEnreplacedyReference.Id : null;
if (expressionValue != null && !(expressionValue is Guid))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : (Guid)expressionValue;
break;
case AttributeTypeCode.Memo:
if (expressionValue != null && !(expressionValue is string))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue as string;
break;
case AttributeTypeCode.Money:
var money = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (Money)EvaluateEnreplacedy.Attributes[attributeName] : null;
attributeValue = money != null ? (object)Convert.ToDecimal(money.Value) : null;
if (expressionValue != null && !(expressionValue is int | expressionValue is double | expressionValue is decimal))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToDecimal(expressionValue);
break;
case AttributeTypeCode.Picklist:
var optionSetValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEnreplacedy.Attributes[attributeName] : null;
attributeValue = optionSetValue != null ? (object)optionSetValue.Value : null;
if (expressionValue != null && !(expressionValue is int | expressionValue is double))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
break;
case AttributeTypeCode.State:
var stateOptionSetValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEnreplacedy.Attributes[attributeName] : null;
attributeValue = stateOptionSetValue != null ? (object)stateOptionSetValue.Value : null;
if (expressionValue != null && !(expressionValue is int | expressionValue is double))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
break;
case AttributeTypeCode.Status:
var statusOptionSetValue = EvaluateEnreplacedy.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEnreplacedy.Attributes[attributeName] : null;
attributeValue = statusOptionSetValue != null ? (object)statusOptionSetValue.Value : null;
if (expressionValue != null && !(expressionValue is int | expressionValue is double))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue);
break;
case AttributeTypeCode.String:
if (expressionValue != null && !(expressionValue is string))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue as string;
break;
case AttributeTypeCode.Uniqueidentifier:
if (expressionValue != null && !(expressionValue is Guid))
{
throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode));
}
testValue = expressionValue == null ? (object)null : (Guid)expressionValue;
break;
default:
throw new InvalidOperationException(string.Format("Unsupported type of attribute {0} specified in the expression.", attributeName));
}
return compare(attributeValue, testValue);
}
19
View Source File : LiveIdUser.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void Update()
{
var user = GetUserEnreplacedy(UserId, _context);
user.SetAttributeValue(AttributeMapApproved, Approved);
user.SetAttributeValue(AttributeMapLastLogin, LastLogin.ToUniversalTime());
_context.Attach(user);
_context.UpdateObject(user);
_context.SaveChanges();
_context.Detach(user);
}
19
View Source File : ScheduleService.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void FindTimes_Click(object sender, EventArgs args)
{
var startTimeInMinutesFromMidnight = int.Parse(StartTime.SelectedValue);
var startDate = StartDate.SelectedDate.AddMinutes(startTimeInMinutesFromMidnight);
var endTimeInMinutesFromMidnight = int.Parse(EndTime.SelectedValue);
var endDate = EndDate.SelectedDate.AddMinutes(endTimeInMinutesFromMidnight);
if (!SelectedDatesAndTimesAreValid(startDate, endDate, startTimeInMinutesFromMidnight, endTimeInMinutesFromMidnight))
{
return;
}
// Add the timezone selected to the CRM Contact for next time.
var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == Contact.Id);
if (contact == null)
{
throw new ApplicationException(string.Format("Couldn't find the user contact where contactid equals {0}.", Contact.Id));
}
contact.SetAttributeValue("adx_timezone", int.Parse(TimeZoneSelection.SelectedValue));
XrmContext.UpdateObject(contact);
XrmContext.SaveChanges();
var usersMinutesFromGmt = GetUsersMinutesFromGmt(contact.GetAttributeValue<int?>("adx_timezone"), XrmContext);
var appointmentRequest = new AppointmentRequest
{
AnchorOffset = Service.GetAttributeValue<int?>("anchoroffset").GetValueOrDefault(),
Direction = SearchDirection.Forward,
Duration = Service.GetAttributeValue<int?>("duration").GetValueOrDefault(60),
NumberOfResults = 10,
RecurrenceDuration = endTimeInMinutesFromMidnight - startTimeInMinutesFromMidnight,
RecurrenceTimeZoneCode = contact.GetAttributeValue<int?>("adx_timezone").GetValueOrDefault(),
SearchRecurrenceRule = "FREQ=DAILY;INTERVAL=1",
SearchRecurrenceStart = new DateTime(startDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc),
SearchWindowEnd = new DateTime(endDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc),
ServiceId = Service.GetAttributeValue<Guid>("serviceid")
};
var service = XrmContext;
var searchRequest = new OrganizationRequest("Search");
searchRequest.Parameters["AppointmentRequest"] = appointmentRequest;
var searchResults = (SearchResults)service.Execute(searchRequest).Results["SearchResults"];
var schedules = searchResults.Proposals.Select(proposal => new
{
ScheduledStart = proposal.Start.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
ScheduledStartUniversalTime = proposal.Start.GetValueOrDefault().ToUniversalTime(),
ScheduledEnd = proposal.End.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
ScheduledEndUniversalTime = proposal.End.GetValueOrDefault().ToUniversalTime(),
AvailableResource = proposal.ProposalParties.First().ResourceId
}).Where(proposal => proposal.ScheduledStartUniversalTime >= DateTime.UtcNow);
if (!schedules.Any())
{
SearchPanel.Visible = true;
NoTimesMessage.Visible = true;
ResultsDisplay.Visible = false;
return;
}
AvailableTimes.DataSource = schedules;
AvailableTimes.DataBind();
SearchPanel.Visible = false;
ResultsDisplay.Visible = true;
ScheduleServiceButton.Enabled = false;
}
19
View Source File : ViewScheduledServices.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void Page_Load(object sender, EventArgs e)
{
RedirectToLoginIfAnonymous();
if (Page.IsPostBack) return;
if (Contact == null) return;
if (Contact.GetAttributeValue<int?>("adx_timezone") == null) return;
var appointmentFetchXml = string.Format(AppointmentFetchXmlFormat, AppointmentStatusScheduled, DateTime.UtcNow, Contact.GetAttributeValue<Guid>("contactid"));
var response = (RetrieveMultipleResponse)ServiceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(appointmentFetchXml)
});
if (response == null || response.EnreplacedyCollection == null || response.EnreplacedyCollection.Enreplacedies == null)
{
return;
}
var usersMinutesFromGmt = GetUsersMinutesFromGmt(Contact.GetAttributeValue<int?>("adx_timezone").GetValueOrDefault(), ServiceContext);
var appointments = response.EnreplacedyCollection.Enreplacedies.Select(a => new
{
scheduledStart = a.GetAttributeValue<DateTime?>("scheduledstart").GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
scheduledEnd = a.GetAttributeValue<DateTime?>("scheduledend").GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt),
serviceType = a.GetAttributeValue<EnreplacedyReference>("serviceid") == null ? string.Empty : a.GetAttributeValue<EnreplacedyReference>("serviceid").Name,
dateBooked = a.GetAttributeValue<DateTime>("createdon").ToUniversalTime().AddMinutes(usersMinutesFromGmt),
serviceId = a.GetAttributeValue<Guid>("activityid")
});
BookedAppointments.DataSource = appointments;
BookedAppointments.DataBind();
}
19
View Source File : CalendarHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static void AppendDateField(StringBuilder vevent, string name, DateTime? value)
{
if (value == null)
{
return;
}
AppendField(vevent, name, value.Value.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));
}
19
View Source File : GitHubJwtFactory.cs
License : MIT License
Project Creator : adriangodong
License : MIT License
Project Creator : adriangodong
private static long ToUtcSeconds(DateTime dt)
{
return (dt.ToUniversalTime().Ticks - TicksSince197011) / TimeSpan.TicksPerSecond;
}
19
View Source File : DateConverter.cs
License : MIT License
Project Creator : afaniuolo
License : MIT License
Project Creator : afaniuolo
public override string ConvertValue(string sourceValue)
{
DateTime sourceDate;
if (DateTime.TryParseExact(sourceValue, "yyyyMMddThhmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out sourceDate))
{
return sourceDate.ToUniversalTime().ToString("yyyyMMddThhmmssZ");
}
return sourceValue;
}
19
View Source File : StationCounter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
static long GetTime(DateTime time)
{
return (time.ToUniversalTime().Ticks - 621355968000000000) / 10000;
}
19
View Source File : DiscordMember.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public Task TimeOutAsync(DateTime until, string reason = null) => this.TimeOutAsync(until.ToUniversalTime() - DateTime.UtcNow, reason);
19
View Source File : Formatter.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public static string Timestamp(DateTime time, TimestampFormat format = TimestampFormat.RelativeTime)
=> Timestamp(time.ToUniversalTime() - DateTime.UtcNow, format);
19
View Source File : FileService.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
private static (string etag, long length) GetFileHTTPProperties(string path)
{
var fileInfo = new FileInfo(path);
long etagHash = fileInfo.LastWriteTime.ToUniversalTime().ToFileTime() ^ fileInfo.Length;
var etag = Convert.ToString(etagHash, 16);
return (etag, fileInfo.Length);
}
19
View Source File : DateGetDateComponents.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected override void Execute(System.Activities.CodeActivityContext context)
{
var workflowContext = context.GetExtension<IWorkflowContext>();
var service = this.RetrieveOrganizationService(context);
DateTime utcDateTime = this.DateToEvaluate.Get(context);
if (utcDateTime.Kind != DateTimeKind.Utc)
{
utcDateTime = utcDateTime.ToUniversalTime();
}
TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = utcDateTime, TimeZoneCode = timeZone.MicrosoftIndex };
LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
DateTime adjustedDateTime = timeZoneResponse.LocalTime;
switch (adjustedDateTime.DayOfWeek)
{
case System.DayOfWeek.Sunday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540000));
break;
case System.DayOfWeek.Monday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540001));
break;
case System.DayOfWeek.Tuesday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540002));
break;
case System.DayOfWeek.Wednesday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540003));
break;
case System.DayOfWeek.Thursday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540004));
break;
case System.DayOfWeek.Friday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540005));
break;
case System.DayOfWeek.Saturday:
this.DayOfWeekPick.Set(context, new OptionSetValue(222540006));
break;
}
this.DayOfWeekName.Set(context, adjustedDateTime.DayOfWeek.ToString());
this.DayOfMonth.Set(context, adjustedDateTime.Day);
this.DayOfYear.Set(context, adjustedDateTime.DayOfYear);
this.HourOfDay023.Set(context, adjustedDateTime.Hour);
this.Minute.Set(context, adjustedDateTime.Minute);
this.MonthOfYearInt.Set(context, adjustedDateTime.Month);
this.MonthOfYearPick.Set(context, new OptionSetValue(222540000 + adjustedDateTime.Month - 1));
this.MonthOfYearName.Set(context, System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(adjustedDateTime.Month));
this.Year.Set(context, adjustedDateTime.Year);
}
19
View Source File : RetrieveActivityBase.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected List<Enreplacedy> RetrieveAnnotationEnreplacedy(CodeActivityContext context, ColumnSet noteColumns, int maxRecords = 1)
{
double miunutesOld = 0;
List<Enreplacedy> returnValue = new List<Enreplacedy>();
IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);
int? objectTypeCode = this.RetrieveEnreplacedyObjectTypeCode(workflowContext, service);
if (objectTypeCode == null)
{
throw new ArgumentException($"Objecttypecode not found in metadata for enreplacedy {workflowContext.PrimaryEnreplacedyName}");
}
ExecuteFetchResponse fetchResponse = null;
ExecuteFetchRequest request = new ExecuteFetchRequest();
try
{
if (String.IsNullOrWhiteSpace(this.FileName.Get(context)))
{
request.FetchXml =
$@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
<enreplacedy name=""annotation"">
<attribute name=""annotationid"" />
<attribute name=""createdon"" />
<filter type=""and"">
<condition attribute=""isdoreplacedent"" operator=""eq"" value=""1"" />
<condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEnreplacedyId}"" />
<condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
</filter>
<order attribute=""createdon"" descending=""true"" />
</enreplacedy>
</fetch>";
}
else
{
request.FetchXml =
$@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
<enreplacedy name=""annotation"">
<attribute name=""annotationid"" />
<attribute name=""createdon"" />
<filter type=""and"">
<condition attribute=""filename"" operator=""like"" value=""%{this.FileName.Get(context)}%"" />
<condition attribute=""isdoreplacedent"" operator=""eq"" value=""1"" />
<condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEnreplacedyId}"" />
<condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
</filter>
<order attribute=""createdon"" descending=""true"" />
</enreplacedy>
</fetch>";
}
fetchResponse = service.Execute(request) as ExecuteFetchResponse;
XmlDoreplacedent queryResults = new XmlDoreplacedent();
queryResults.LoadXml(fetchResponse.FetchXmlResult);
int days = 0;
int minutes = 0;
for (int i = 0; i < queryResults["resultset"].ChildNodes.Count; i++)
{
if (queryResults["resultset"].ChildNodes[i]["createdon"] != null && !String.IsNullOrWhiteSpace(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText))
{
DateTime createdon = DateTime.Parse(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText);
if (createdon.Kind == DateTimeKind.Local)
{
createdon = createdon.ToUniversalTime();
}
TimeSpan difference = DateTime.Now.ToUniversalTime() - createdon;
miunutesOld = difference.TotalMinutes;
switch (this.TimeSpanOption.Get(context).Value)
{
case 222540000:
minutes = this.TimeSpanValue.Get(context);
break;
case 222540001:
minutes = this.TimeSpanValue.Get(context) * 60;
break;
case 222540002:
days = this.TimeSpanValue.Get(context);
break;
case 222540003:
days = this.TimeSpanValue.Get(context) * 7;
break;
case 222540004:
days = this.TimeSpanValue.Get(context) * 365;
break;
}
TimeSpan allowedDifference = new TimeSpan(days, 0, minutes, 0);
if (difference <= allowedDifference)
{
returnValue.Add(service.Retrieve("annotation", Guid.Parse(queryResults["resultset"].ChildNodes[i]["annotationid"].InnerText), noteColumns));
}
}
if (returnValue.Count >= maxRecords)
{
break;
}
}
}
catch (System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
throw new ArgumentException("There was an error executing the FetchXML. Message: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
return returnValue;
}
See More Examples