System.DateTime.Parse(string)

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

4829 Examples 7

19 Source : AttributeMatcher.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static bool MatchDateTime(string policyAttribute, string decisionRequestAttribute)
        {
            DateTime policyValue = DateTime.Parse(policyAttribute);
            DateTime requestValue = DateTime.Parse(decisionRequestAttribute);

            return policyValue.Equals(requestValue);
        }

19 Source : AttributeMatcher.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static bool MatchTime(string policyAttribute, string decisionRequestAttribute)
        {
            DateTime policyValue = DateTime.Parse(policyAttribute);
            DateTime requestValue = DateTime.Parse(decisionRequestAttribute);

            return policyValue.Equals(requestValue);
        }

19 Source : AttributeMatcher.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static bool MatchDate(string policyAttribute, string decisionRequestAttribute)
        {
            DateTime policyValue = DateTime.Parse(policyAttribute);
            DateTime requestValue = DateTime.Parse(decisionRequestAttribute);

            if (policyValue.Date == requestValue.Date)
            {
                return true;
            }

            return false;
        }

19 Source : DataReaderExtensionsTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public void GetValue_ColumnIsDateTime_ColumnHasValue_ReadAsDateTime_ReturnsValue()
        {
            // Arrange
            var testValue = DateTime.Parse("2021-02-13T12:33:12.2313Z");
            var reader = GetDataReader(ColumnName, typeof(DateTime), testValue);
            reader.Read();

            // Act
            var actual = reader.GetValue<DateTime>(ColumnName);

            // replacedert
            replacedert.Equal(testValue, actual);
        }

19 Source : DataReaderExtensionsTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public void GetValue_ColumnIsDateTime_ColumnHasValue_ReadAsNullableDateTime_ReturnsValue()
        {
            // Arrange
            var testValue = DateTime.Parse("2021-02-13T12:33:12.2313Z");
            var reader = GetDataReader(ColumnName, typeof(DateTime), testValue);
            reader.Read();

            // Act
            var actual = reader.GetValue<DateTime?>(ColumnName);

            // replacedert
            replacedert.Equal(testValue, actual);
        }

19 Source : ProcessControllerTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async void PutProcess_EndProcess_EnsureArchivedStateIsSet()
        {
            // Arrange
            string requestUri = $"storage/api/v1/instances/1337/377efa97-80ee-4cc6-8d48-09de12cc273d/process/";
            Instance testInstance = TestDataUtil.GetInstance(1337, new Guid("377efa97-80ee-4cc6-8d48-09de12cc273d"));
            testInstance.Id = $"{testInstance.InstanceOwner.PartyId}/{testInstance.Id}";
            ProcessState state = new ProcessState
            {
                Started = DateTime.Parse("2020-04-29T13:53:01.7020218Z"),
                StartEvent = "StartEvent_1",
                Ended = DateTime.UtcNow,
                EndEvent = "EndEvent_1"
            };

            JsonContent jsonString = JsonContent.Create(state, new MediaTypeHeaderValue("application/json"));

            Mock<IInstanceRepository> repositoryMock = new Mock<IInstanceRepository>();
            repositoryMock.Setup(ir => ir.GetOne(It.IsAny<string>(), It.IsAny<int>())).ReturnsAsync(testInstance);
            repositoryMock.Setup(ir => ir.Update(It.IsAny<Instance>())).ReturnsAsync((Instance i) => i);

            HttpClient client = GetTestClient(repositoryMock.Object);
            string token = PrincipalUtil.GetToken(3, 1337, 3);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Act
            HttpResponseMessage response = await client.PutAsync(requestUri, jsonString);
            string responseContent = await response.Content.ReadreplacedtringAsync();
            Instance actual = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance));

            // replacedert
            replacedert.True(actual.Status.IsArchived);
        }

19 Source : InstanceHelperTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public void GetSBLStatusForCurrentTask_Confirmation()
        {
            Instance instance = new Instance
            {
                Process = new ProcessState
                {
                    Started = DateTime.Parse("2021-01-18T16:38:28.3776631Z"),
                    StartEvent = "StartEvent_1",
                    CurrentTask = new ProcessElementInfo
                    {
                        Flow = 3,
                        Started = DateTime.Parse("2021-01-18T16:41:24.6560293Z"),
                        ElementId = "Task_2",
                        Name = "Bekreft skjemadata",
                        AltinnTaskType = "confirmation"
                    }
                }
            };

            string sblStatus = InstanceHelper.GetSBLStatusForCurrentTask(instance);
            replacedert.Equal("Confirmation", sblStatus);
        }

19 Source : InstanceHelperTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public void GetSBLStatusForCurrentTask_Feedback()
        {
            Instance instance = new Instance
            {
                Process = new ProcessState
                {
                    Started = DateTime.Parse("2021-01-18T16:38:28.3776631Z"),
                    StartEvent = "StartEvent_1",
                    CurrentTask = new ProcessElementInfo
                    {
                        Flow = 3,
                        Started = DateTime.Parse("2021-01-18T16:41:24.6560293Z"),
                        ElementId = "Task_2",
                        Name = "Venter på tilbakemelding",
                        AltinnTaskType = "feedback"
                    }
                }
            };

            string sblStatus = InstanceHelper.GetSBLStatusForCurrentTask(instance);
            replacedert.Equal("Feedback", sblStatus);
        }

19 Source : AltinnAppGitRepositoryTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]        
        public async Task GetApplicationMetadata_FileExists_ShouldHaveCorrectValues()
        {
            var org = "ttd";
            var repository = "hvem-er-hvem";
            var developer = "testUser";

            string repositoriesRootDirectory = TestDataHelper.GetTestDataRepositoriesRootDirectory();
            string repositoryDirectory = TestDataHelper.GetTestDataRepositoryDirectory(org, repository, developer);
            var altinnAppGitRepository = new AltinnAppGitRepository(org, repository, developer, repositoriesRootDirectory, repositoryDirectory);

            var applicationMetadata = await altinnAppGitRepository.GetApplicationMetadata();
                        
            applicationMetadata.Id.Should().Be("yabbin/hvem-er-hvem");
            applicationMetadata.Org.Should().Be("yabbin");
            applicationMetadata.replacedle.Should().ContainValues("Hvem er hvem?", "who-is-who");
            applicationMetadata.replacedle.Should().ContainKeys("nb", "en");

            applicationMetadata.DataTypes.Should().HaveCount(2);
            applicationMetadata.DataTypes.First(d => d.Id == "ref-data-as-pdf").AllowedContentTypes.First().Should().Be("application/pdf");

            DataType mainDataType = applicationMetadata.DataTypes.First(d => d.Id == "Kursdomene_HvemErHvem_M_2021-04-08_5742_34627_SERES");
            mainDataType.AllowedContentTypes.First().Should().Be("application/xml");
            mainDataType.AppLogic.ClreplacedRef.Should().Be("Altinn.App.Models.HvemErHvem_M");
            mainDataType.AppLogic.AutoCreate.Should().BeTrue();
            mainDataType.MinCount.Should().Be(1);
            mainDataType.MaxCount.Should().Be(1);
            mainDataType.TaskId.Should().Be("Task_1");

            applicationMetadata.PartyTypesAllowed.Person.Should().BeFalse();
            applicationMetadata.PartyTypesAllowed.Organisation.Should().BeFalse();
            applicationMetadata.PartyTypesAllowed.SubUnit.Should().BeFalse();
            applicationMetadata.PartyTypesAllowed.BankruptcyEstate.Should().BeFalse();

            var dataField = applicationMetadata.DataFields.First(d => d.Id == "GeekType");
            dataField.Path.Should().Be("InnrapporterteData.geekType");
            dataField.DataTypeId.Should().Be("Kursdomene_HvemErHvem_M_2021-04-08_5742_34627_SERES");

            applicationMetadata.AutoDeleteOnProcessEnd.Should().BeFalse();
            applicationMetadata.Created.Should().BeSameDateAs(DateTime.Parse("2021-04-08T17:42:09.0883842Z"));
            applicationMetadata.CreatedBy.Should().Be("Ronny");
            applicationMetadata.LastChanged.Should().BeSameDateAs(DateTime.Parse("2021-04-08T17:42:09.08847Z"));
            applicationMetadata.LastChangedBy.Should().Be("Ronny");
        }

19 Source : CrmWorkflowBase.cs
with MIT License
from AndrewButenko

public Dictionary<string, object> DeserializeDictionary(string dictionaryString)
        {
            var result = new Dictionary<string, object>();

            if (string.IsNullOrEmpty(dictionaryString))
                return result;

            var request = XElement.Parse(dictionaryString);

            request.Elements().ToList().ForEach(e =>
            {
                object fieldValue;

                if (e.Attribute("IsNull")?.Value == "true")
                    fieldValue = null;
                else
                {
                    if (e.Attribute("Type") == null)
                        throw new InvalidPluginExecutionException(
                            $"Attribute {e.Name} is not null and doesn't contain field type, can't deserialize");

                    var typeName = e.Attribute("Type").Value;

                    switch (typeName)
                    {
                        case "System.Boolean":
                            fieldValue = bool.Parse(e.Value);
                            break;
                        case "System.String":
                            fieldValue = e.Value;
                            break;
                        case "System.Int32":
                            fieldValue = int.Parse(e.Value);
                            break;
                        case "System.DateTime":
                            fieldValue = DateTime.Parse(e.Value);
                            break;
                        case "System.Decimal":
                            fieldValue = decimal.Parse(e.Value);
                            break;
                        case "Microsoft.Xrm.Sdk.OptionSetValue":
                            fieldValue = new OptionSetValue(int.Parse(e.Value));
                            break;
                        case "Microsoft.Xrm.Sdk.Money":
                            fieldValue = new Money(decimal.Parse(e.Value));
                            break;
                        case "Microsoft.Xrm.Sdk.EnreplacedyReference":
                            if (e.Element("Id") == null)
                                throw new InvalidPluginExecutionException(
                                    $"Can't parse {e.Name} node with {typeName} type - Id node is not available");

                            if (e.Element("LogicalName") == null)
                                throw new InvalidPluginExecutionException(
                                    $"Can't parse {e.Name} node with {typeName} type - LogicalName node is not available");

                            fieldValue = new EnreplacedyReference(e.Element("LogicalName").Value,
                                new Guid(e.Element("Id").Value));
                            break;
                        default:
                            throw new InvalidPluginExecutionException(
                                $"Serialization is not implemented for {typeName} clreplaced");
                    }

                    result.Add(e.Name.ToString(), fieldValue);
                }
            });

            return result;
        }

19 Source : StripIntervals.cs
with MIT License
from AngeloCresta

private void FillData()
		{
			Random rand;
			// Use a number to calculate a starting value for 
			// the pseudo-random number sequence
			rand = new Random();
			
			// The number of days for stock data
			int period = 120;

			// The first High value
			double high = rand.NextDouble() * 40;

			// The first Close value
			double close = high - rand.NextDouble();

			// The first Low value
			double low = close - rand.NextDouble();

			// The first Open value
			double open = ( high - low ) * rand.NextDouble() + low;

			// The first day X and Y values
			Chart1.Series[0].Points.AddXY(DateTime.Parse("1/2/2002"), high);
			Chart1.Series[0].Points[0].YValues[1] = low;

			// The Open value is not used.
			Chart1.Series[0].Points[0].YValues[2] = open;
			Chart1.Series[0].Points[0].YValues[3] = close;
			
			// Days loop
			for( int day = 1; day <= period; day++ )
			{
			
				// Calculate High, Low and Close values
				high = Chart1.Series[0].Points[day-1].YValues[2]+rand.NextDouble();
				close = high - rand.NextDouble();
				low = close - rand.NextDouble();
				open = ( high - low ) * rand.NextDouble() + low;
				
				// The low cannot be less than yesterday close value.
				if( low > Chart1.Series[0].Points[day-1].YValues[2])
					low = Chart1.Series[0].Points[day-1].YValues[2];
							
				// Set data points values
				Chart1.Series[0].Points.AddXY(day, high);
				Chart1.Series[0].Points[day].XValue = Chart1.Series[0].Points[day-1].XValue+1;
				Chart1.Series[0].Points[day].YValues[1] = low;
				Chart1.Series[0].Points[day].YValues[2] = open;
				Chart1.Series[0].Points[day].YValues[3] = close;

			}
		}

19 Source : MultipagePrinting.cs
with MIT License
from AngeloCresta

private void FillData()
		{
			Random rand;
			// Use a number to calculate a starting value for 
			// the pseudo-random number sequence
			rand = new Random();
			
			// The number of days for stock data
			int period = 240;

			// The first High value
			double high = rand.NextDouble() * 40;

			// The first Close value
			double close = high - rand.NextDouble();

			// The first Low value
			double low = close - rand.NextDouble();

			// The first Open value
			double open = ( high - low ) * rand.NextDouble() + low;

			// The first Volume value
			double volume = 100 + 15 * rand.NextDouble();
						
			// The first day X and Y values
			chart1.Series["Price"].Points.AddXY(DateTime.Parse("1/2/2002"), high);
			chart1.Series["Price"].Points[0].YValues[1] = low;

			// The Open value is not used.
			chart1.Series["Price"].Points[0].YValues[2] = open;
			chart1.Series["Price"].Points[0].YValues[3] = close;
			
			// Days loop
			for( int day = 1; day <= period; day++ )
			{
			
				// Calculate High, Low and Close values
				high = chart1.Series["Price"].Points[day-1].YValues[2]+rand.NextDouble();
				close = high - rand.NextDouble();
				low = close - rand.NextDouble();
				open = ( high - low ) * rand.NextDouble() + low;
				
				// The low cannot be less than yesterday close value.
				if( low > chart1.Series["Price"].Points[day-1].YValues[2])
					low = chart1.Series["Price"].Points[day-1].YValues[2];
							
				// Set data points values
				chart1.Series["Price"].Points.AddXY(day, high);
				chart1.Series["Price"].Points[day].XValue = chart1.Series["Price"].Points[day-1].XValue+1;
				chart1.Series["Price"].Points[day].YValues[1] = low;
				chart1.Series["Price"].Points[day].YValues[2] = open;
				chart1.Series["Price"].Points[day].YValues[3] = close;
			}
		}

19 Source : MultiChartAreaCursor.cs
with MIT License
from AngeloCresta

private void Data( Series series )
		{
			Random rand;
			// Use a number to calculate a starting value for 
			// the pseudo-random number sequence
			rand = new Random(randSeed);
			
			// The number of days for stock data
			int period = 100;

			chart1.Series["Input"].Points.Clear();

			// The first High value
			double high = rand.NextDouble() * 40;

			// The first Close value
			double close = high - rand.NextDouble();

			// The first Low value
			double low = close - rand.NextDouble();

			// The first Open value
			double open = ( high - low ) * rand.NextDouble() + low;

			// The first Volume value
			double volume = 100 + 15 * rand.NextDouble();
						
			// The first day X and Y values
			chart1.Series["Input"].Points.AddXY(DateTime.Parse("1/2/2002"), high);
			chart1.Series["Volume"].Points.AddXY(DateTime.Parse("1/2/2002"), volume);
			chart1.Series["Input"].Points[0].YValues[1] = low;

			// The Open value is not used.
			chart1.Series["Input"].Points[0].YValues[2] = open;
			chart1.Series["Input"].Points[0].YValues[3] = close;
			
			// Days loop
			for( int day = 1; day <= period; day++ )
			{
			
				// Calculate High, Low and Close values
				high = chart1.Series["Input"].Points[day-1].YValues[2]+rand.NextDouble();
				close = high - rand.NextDouble();
				low = close - rand.NextDouble();
				open = ( high - low ) * rand.NextDouble() + low;

				// The Volume value
				volume = 100 + 50 * rand.NextDouble();
				
				// The low cannot be less than yesterday close value.
				if( low > chart1.Series["Input"].Points[day-1].YValues[2])
					low = chart1.Series["Input"].Points[day-1].YValues[2];
							
				// Set data points values
				chart1.Series["Input"].Points.AddXY(day, high);
				chart1.Series["Input"].Points[day].XValue = chart1.Series["Input"].Points[day-1].XValue+1;
				chart1.Series["Input"].Points[day].YValues[1] = low;
				chart1.Series["Input"].Points[day].YValues[2] = open;
				chart1.Series["Input"].Points[day].YValues[3] = close;

				chart1.Series["Volume"].Points.AddXY(chart1.Series["Input"].Points[day].XValue, volume);

			}

			chart1.Invalidate();
		}

19 Source : FinancialChartType.cs
with MIT License
from AngeloCresta

private void FillData()
		{
			Random rand;
			// Use a number to calculate a starting value for 
			// the pseudo-random number sequence
			rand = new Random();
			
			// The number of days for stock data
			int period = 60;

			// The first High value
			double high = rand.NextDouble() * 40;

			// The first Close value
			double close = high - rand.NextDouble();

			// The first Low value
			double low = close - rand.NextDouble();

			// The first Open value
			double open = ( high - low ) * rand.NextDouble() + low;

			// The first Volume value
			double volume = 100 + 15 * rand.NextDouble();
						
			// The first day X and Y values
			chart1.Series["Price"].Points.AddXY(DateTime.Parse("1/2/2002"), high);
			chart1.Series["Volume"].Points.AddXY(DateTime.Parse("1/2/2002"), volume);
			chart1.Series["Price"].Points[0].YValues[1] = low;

			// The Open value is not used.
			chart1.Series["Price"].Points[0].YValues[2] = open;
			chart1.Series["Price"].Points[0].YValues[3] = close;
			
			// Days loop
			for( int day = 1; day <= period; day++ )
			{
			
				// Calculate High, Low and Close values
				high = chart1.Series["Price"].Points[day-1].YValues[2]+rand.NextDouble();
				close = high - rand.NextDouble();
				low = close - rand.NextDouble();
				open = ( high - low ) * rand.NextDouble() + low;
				
				// Calculate volume
				volume = chart1.Series["Volume"].Points[day-1].YValues[0] + 10 * rand.NextDouble() - 5;

				// The low cannot be less than yesterday close value.
				if( low > chart1.Series["Price"].Points[day-1].YValues[2])
					low = chart1.Series["Price"].Points[day-1].YValues[2];
							
				// Set data points values
				chart1.Series["Price"].Points.AddXY(day, high);
				chart1.Series["Price"].Points[day].XValue = chart1.Series["Price"].Points[day-1].XValue+1;
				chart1.Series["Price"].Points[day].YValues[1] = low;
				chart1.Series["Price"].Points[day].YValues[2] = open;
				chart1.Series["Price"].Points[day].YValues[3] = close;

				// Set volume values
				chart1.Series["Volume"].Points.AddXY(day, volume);
				chart1.Series["Volume"].Points[day].XValue = chart1.Series["Volume"].Points[day-1].XValue+1;
			}
		}

19 Source : DateTimeExtensions.cs
with MIT License
from anoyetta

public static DateTime FromInt(
            decimal dateTime) => DateTime.Parse(dateTime.ToString("0000/00/00"));

19 Source : DateTimeExtensions.cs
with MIT License
from anoyetta

public static DateTime FromInt(
            int dateTime) => DateTime.Parse(dateTime.ToString("0000/00/00"));

19 Source : ChatLogger.cs
with MIT License
from anoyetta

public static void WriteLogCallback(
            string dateTime,
            string message)
        {
            try
            {
                if (OnWrite == null)
                {
                    return;
                }

                var arg = new AppLogOnWriteEventArgs()
                {
                    DateTime = dateTime,
                    DateTimeShort = DateTime.Parse(dateTime).ToString("HH:mm:ss"),
                    Message = message,
                };

                OnWrite.Invoke(
                    LazyLogger.Value,
                    arg);
            }
            catch (Exception)
            {
            }
        }

19 Source : DownloaderDateConverter.cs
with GNU General Public License v3.0
from antikmozib

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime date = DateTime.Parse(value.ToString());
            return date.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern);
        }

19 Source : ConvertUtil.cs
with Apache License 2.0
from Appdynamics

public static T GetTypedCellValue<T>(object value)
        {
            if (value == null)
                return default(T);

            var fromType = value.GetType();
            var toType = typeof(T);
            var toNullableUnderlyingType = (TypeCompat.IsGenericType(toType) && toType.GetGenericTypeDefinition() == typeof(Nullable<>))
                ? Nullable.GetUnderlyingType(toType)
                : null;

            if (fromType == toType || fromType == toNullableUnderlyingType)
                return (T)value;

            // if converting to nullable struct and input is blank string, return null
            if (toNullableUnderlyingType != null && fromType == typeof(string) && ((string)value).Trim() == string.Empty)
                return default(T);

            toType = toNullableUnderlyingType ?? toType;

            if (toType == typeof(DateTime))
            {
                if (value is double)
                    return (T)(object)(DateTime.FromOADate((double)value));

                if (fromType == typeof(TimeSpan))
                    return ((T)(object)(new DateTime(((TimeSpan)value).Ticks)));

                if (fromType == typeof(string))
                    return (T)(object)DateTime.Parse(value.ToString());
            }
            else if (toType == typeof(TimeSpan))
            {
                if (value is double)
                    return (T)(object)(new TimeSpan(DateTime.FromOADate((double)value).Ticks));

                if (fromType == typeof(DateTime))
                    return ((T)(object)(new TimeSpan(((DateTime)value).Ticks)));

                if (fromType == typeof(string))
                    return (T)(object)TimeSpan.Parse(value.ToString());
            }

            return (T)Convert.ChangeType(value, toType);
        }

19 Source : DateTimeFormulaTests.cs
with Apache License 2.0
from Appdynamics

[TestMethod]
        public void DateTimeFormula_FormulaValueIsSetFromXmlNodeInConstructor()
        {
            // Arrange
            var date = DateTime.Parse("2011-01-08");
            var datereplacedtring = date.ToOADate().ToString(_cultureInfo);
            LoadXmlTestData("A1", "decimal", datereplacedtring);
            // Act
            var validation = new ExcelDataValidationDateTime(_sheet, "A1", ExcelDataValidationType.Decimal, _dataValidationNode, _namespaceManager);
            // replacedert
            replacedert.AreEqual(date, validation.Formula.Value);
        }

19 Source : DateTimeFormulaTests.cs
with Apache License 2.0
from Appdynamics

[TestMethod]
        public void DateTimeFormula_FormulasFormulaIsSetFromXmlNodeInConstructor()
        {
            // Arrange
            var date = DateTime.Parse("2011-01-08");
            LoadXmlTestData("A1", "decimal", "A1");

            // Act
            var validation = new ExcelDataValidationDateTime(_sheet, "A1", ExcelDataValidationType.Decimal, _dataValidationNode, _namespaceManager);

            // replacedert
            replacedert.AreEqual("A1", validation.Formula.ExcelFormula);
        }

19 Source : Ext.Convert.cs
with MIT License
from aprilyush

public static DateTime ToDate(this string data)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(data))
                {
                    return DateTime.MinValue;
                }
                if (data.Contains("-") || data.Contains("/"))
                {
                    return DateTime.Parse(data);
                }
                else
                {
                    int length = data.Length;
                    switch (length)
                    {
                        case 4:
                            return DateTime.ParseExact(data, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
                        case 6:
                            return DateTime.ParseExact(data, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
                        case 8:
                            return DateTime.ParseExact(data, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                        case 10:
                            return DateTime.ParseExact(data, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
                        case 12:
                            return DateTime.ParseExact(data, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
                        case 14:
                            return DateTime.ParseExact(data, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                        default:
                            return DateTime.ParseExact(data, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                    }
                }
            }
            catch
            {
                return DateTime.MinValue;
            }
        }

19 Source : Utility.cs
with MIT License
from aprilyush

public static object ConvertTo(string value, Type type)
        {
            object result = value;
            if (value != null)
            {
                try
                {
                    if (type.IsEnum)
                    {
                        //枚举类型
                        result = Enum.Parse(type, value, true);
                    }
                    else if (Type.GetTypeCode(type) == TypeCode.DateTime)
                    {
                        //日期型
                        result = DateTime.Parse(value);
                    }
                    else
                    {
                        //其它值
                        result = (value as IConvertible).ToType(type, null);
                    }
                }
                catch
                {
                    result = null;
                }
            }
            return result;
        }

19 Source : EntityTime.cs
with MIT License
from araditc

public DateTime GetTime(Jid jid) {
			jid.ThrowIfNull("jid");
			if (!ecapa.Supports(jid, Extension.EnreplacedyTime)) {
				throw new NotSupportedException("The XMPP enreplacedy does not support " +
					"the 'Enreplacedy Time' extension.");
			}
			Iq iq = im.IqRequest(IqType.Get, jid, im.Jid,
				Xml.Element("time", "urn:xmpp:time"));
			if (iq.Type == IqType.Error)
				throw Util.ExceptionFromError(iq, "The time could not be retrieved.");
			var time = iq.Data["time"];
			if (time == null || time["tzo"] == null || time["utc"] == null)
				throw new XmppException("Erroneous IQ response.");
			string tzo = time["tzo"].InnerText;
			string utc = time["utc"].InnerText;
			// Try to parse utc into datetime, tzo into timespan.
			try {
				DateTime dt = DateTime.Parse(utc).ToUniversalTime();
				TimeSpan sp = TimeSpan.Parse(tzo.TrimStart('+'));
				return dt.Add(sp);
			} catch (FormatException e) {
				throw new XmppException("Invalid tzo or utc value.", e);
			}
		}

19 Source : UpdateChecker.cs
with MIT License
from Archomeda

private static async Task<string> GetUpdateFor(string branch)
        {
            if (string.IsNullOrWhiteSpace(AppDate))
                return null;

            var appDate = DateTime.Parse(AppDate);
            var uri = new Uri(AppVeyorApiUrl + $"?recordsNumber=50&branch={branch}");
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("User-Agent", "AutoSaliens/1.0 (https://github.com/Archomeda/AutoAliens)");
                webClient.Headers.Add(HttpRequestHeader.Accept, "application/json");
                try
                {
                    var json = await webClient.DownloadStringTaskAsync(uri);
                    var builds = JObject.Parse(json)["builds"].AsJEnumerable();
                    foreach (JObject build in builds)
                    {
                        var buildDate = build["committed"].Value<DateTime>();
                        if (buildDate <= appDate)
                            break;
                        if (build.ContainsKey("pullRequestId"))
                            continue;
                        if (build["status"].Value<string>() == "success")
                            return build["version"].Value<string>();
                    }
                } catch (Exception) { }
            }
            return null;
        }

19 Source : AuditableAsyncDocumentSessionDecorator.cs
with MIT License
from ARKlab

private void _fillAudit(Audit audit, string enreplacedyId, string cv, string collectionName, string lastMod = null, string operation = null)
		{
			_audit.LastUpdatedUtc = DateTime.UtcNow;
			//_audit.UserId = _principalProvider.Current?.Idenreplacedy?.Name;
			_audit.UserId = _principalProvider.Current?.FindFirst(ClaimTypes.NameIdentifier)?.Value
				?? throw new InvalidOperationException("UserId not found: audit requires an identified claims principal");

			if (!_audit.EnreplacedyInfo.Any(s => s.EnreplacedyId == enreplacedyId))
			{
				_audit.EnreplacedyInfo.Add(new EnreplacedyInfo
				{
					EnreplacedyId = enreplacedyId,
					PrevChangeVector = cv,
					CollectionName = collectionName,
					Operation = operation,
					LastModified = operation == "Delete" ? DateTime.Parse(lastMod) : default
				});
			}
		}

19 Source : ProjectManager.cs
with GNU General Public License v3.0
from armandoalonso

private static void ReadMetadataJson(C3Addon addon, string fullpath)
        {
            try
            {
                var text = File.ReadAllLines(fullpath);
                addon.Id = Guid.Parse(text[1].Split('|')[1].Trim());
                addon.Name = text[2].Split('|')[1].Trim();
                addon.Clreplaced = text[3].Split('|')[1].Trim();
                addon.Company = text[4].Split('|')[1].Trim();
                addon.Author = text[5].Split('|')[1].Trim();

                addon.MajorVersion = int.Parse(text[6].Split('|')[1].Trim());
                addon.MinorVersion = int.Parse(text[7].Split('|')[1].Trim());
                addon.RevisionVersion = int.Parse(text[8].Split('|')[1].Trim());
                addon.BuildVersion = int.Parse(text[9].Split('|')[1].Trim());

                addon.Description = text[10].Split('|')[1].Trim();
                addon.AddonCategory = text[11].Split('|')[1].Trim();
                addon.Type = (PluginType)Enum.Parse(typeof(PluginType), text[12].Split('|')[1].Trim());
                addon.CreateDate = DateTime.Parse(text[13].Split('|')[1].Trim());
                addon.LastModified = DateTime.Parse(text[14].Split('|')[1].Trim());

                if (text.Length == 16)
                {
                    addon.AddonId = text[15].Split('|')[1].Trim();
                }
                else
                {
                    addon.AddonId = $"{addon.Author}_{addon.Clreplaced}";
                }

            }
            catch (Exception ex)
            {
                LogManager.AddErrorLog(ex);
                throw;
            }
        }

19 Source : Check.cs
with MIT License
from arttonoyan

public static DateTime AsDateTime(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return default(DateTime);

            return DateTime.Parse(obj.ToString());
        }

19 Source : Check.cs
with MIT License
from arttonoyan

public static DateTime? AsNullableDateTime(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return null;
            
            return DateTime.Parse(obj.ToString());
        }

19 Source : BomberjamContext.cs
with GNU General Public License v3.0
from asimmon

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            foreach (var enreplacedyType in modelBuilder.Model.GetEnreplacedyTypes())
            {
                enreplacedyType.SetTableName(TablePrefix + enreplacedyType.GetTableName());
            }

            modelBuilder.Enreplacedy<DbGameUser>().HasKey(x => new { GameID = x.GameId, UserID = x.UserId });

            modelBuilder.Enreplacedy<DbUser>().HasIndex(x => x.GithubId).IsUnique();
            modelBuilder.Enreplacedy<DbUser>().HasIndex(x => x.UserName).IsUnique();
            modelBuilder.Enreplacedy<DbUser>().HasIndex(x => x.GlobalRank);
            modelBuilder.Enreplacedy<DbUser>().HasIndex(x => x.Points);

            modelBuilder.Enreplacedy<DbBot>().HasIndex(x => x.Created);
            modelBuilder.Enreplacedy<DbBot>().HasIndex(x => x.Updated);
            modelBuilder.Enreplacedy<DbBot>().HasIndex(x => x.Status);
            modelBuilder.Enreplacedy<DbBot>().Property(x => x.Status).HasConversion<int>();

            modelBuilder.Enreplacedy<DbGame>().HasIndex(x => x.Created);
            modelBuilder.Enreplacedy<DbGame>().HasIndex(x => x.Origin);
            modelBuilder.Enreplacedy<DbGame>().Property(x => x.Origin).HasConversion<int>();
            modelBuilder.Enreplacedy<DbGame>().Property(x => x.SeasonId).HasDefaultValue(FirstSeasonId);

            modelBuilder.Enreplacedy<DbQueuedTask>().HasIndex(x => x.Status);
            modelBuilder.Enreplacedy<DbQueuedTask>().HasIndex(x => x.Type);
            modelBuilder.Enreplacedy<DbQueuedTask>().HasIndex(x => x.Created);
            modelBuilder.Enreplacedy<DbQueuedTask>().Property(x => x.Type).HasConversion<int>();
            modelBuilder.Enreplacedy<DbQueuedTask>().Property(x => x.Status).HasConversion<int>();

            modelBuilder.Enreplacedy<DbWorker>().HasIndex(x => x.Created);

            modelBuilder.Enreplacedy<DbSeasonSummary>().HasKey(x => new { UserId = x.UserId, SeasonId = x.SeasonId });

            // Foreign keys with specific behavior
            modelBuilder.Enreplacedy<DbGameUser>().HasOne(gu => gu.Bot).WithMany().OnDelete(DeleteBehavior.NoAction);

            // Initial season
            modelBuilder.Enreplacedy<DbSeason>().HasData(new DbSeason
            {
                Id = FirstSeasonId,
                Created = DateTime.Parse("2021-03-01T00:00:00.0000000Z"),
                Updated = DateTime.Parse("2021-03-01T00:00:00.0000000Z"),
                Name = "S" + FirstSeasonId.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0')
            });
        }

19 Source : AzureAlertContextTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AlertContext_Roundtrips()
        {
            // Arrange
            var data = EmbeddedResource.ReadAsJObject("Microsoft.AspNet.WebHooks.Messages.AlertMessage1.json");
            var expected = new AzureAlertContext
            {
                Id = "/subscriptions/aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee/resourceGroups/tests123/providers/microsoft.insights/alertrules/HenriknTest02",
                Name = "HenriknTest02",
                Description = "Test",
                ConditionType = "Metric",
                Condition = new AzureAlertCondition
                {
                    MetricName = "CPU percentage",
                    MetricUnit = "Count",
                    MetricValue = "2.716631",
                    Threshold = "10",
                    WindowSize = "5",
                    TimeAggregation = "Average",
                    Operator = "LessThan",
                },
                SubscriptionId = "aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee",
                ResourceGroupName = "tests123",
                Timestamp = DateTime.Parse("2015-09-30T03:55:30.7037012Z").ToUniversalTime(),
                ResourceName = "testmachine",
                ResourceType = "microsoft.clreplacediccompute/virtualmachines",
                ResourceRegion = "West US",
                ResourceId = "/subscriptions/aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee/resourceGroups/tests123/providers/Microsoft.ClreplacedicCompute/virtualMachines/testmachine",
                PortalLink = "https://portal.azure.com/#resource/subscriptions/aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee/resourceGroups/tests123/providers/Microsoft.ClreplacedicCompute/virtualMachines/testmachine",
            };

            // Act
            var actual = data["context"].ToObject<AzureAlertContext>();

            // replacedert
            var expectedJson = JsonConvert.SerializeObject(expected, _serializerSettings);
            var actualJson = JsonConvert.SerializeObject(actual, _serializerSettings);
            replacedert.Equal(expectedJson, actualJson);
        }

19 Source : AzureAlertContextTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AlertContextForWebTest_Roundtrips()
        {
            // Arrange
            var expectedContext = new AzureAlertContext
            {
                Condition = new AzureAlertCondition
                {
                    FailureDetails = string.Empty,
                    MetricName = "Failed Locations",
                    MetricUnit = "locations",
                    MetricValue = "0",
                    Operator = "GreaterThan",
                    Threshold = "3",
                    TimeAggregation = "Sum",
                    WebTestName = "testazuretestaboutpage-azuretest20170922040158",
                    WindowSize = "5",
                },
                ConditionType = "Webtest",
                Description = string.Empty,
                Id = "/subscriptions/6e0cb82e-37c4-473b-bb45-8b546cfc01b6/resourceGroups/resources/providers/" +
                "microsoft.insights/alertrules/testazuretestaboutpage-azuretest20170922040158-47970367-464e-" +
                "4bf0-b870-b72aa668b591",

                Name = "testazuretestaboutpage-azuretest20170922040158-47970367-464e-4bf0-b870-b72aa668b591",
                PortalLink = "https://go.microsoft.com/fwlink/?LinkID=615149&subscriptionId=6e0cb82e-37c4-473b-" +
                "bb45-8b546cfc01b6&resourceGroup=resources&resourceType=webtests&resourceName=" +
                "testazuretestaboutpage-azuretest20170922040158&tc=ZAMAAB-LCAAAAAAABADFkltLw0AQhc-fcV8kJdlN2-" +
                "RRBEH0SQuCb5umN7xEelHw1_vtpNY-FJ8EWWYye-ZyJieJcrrQtR40U6OlOs4TWMR6bIvf4B1xVK6pagXiRhlRVKWSqCQzk" +
                "idq8LXGRC21cxVU5xpiDbcZGUem004LkJ3xf_Jck5vsuTzVBZU5k7zdSkOGsLnDRvHQ94M0NnmrN-IFaHai6v-" +
                "mZ4aXRB4NKpTJTJvWciX3wtSsUKrlpPrInDnW0hPJFzbL6QO7AlnpGeZW57pluynIFqzTK9s4bEXujMkR75nU-7_" +
                "6lgO9w7BBg8ge6f131Cb-AR2dXvZ8HR0bOtbUH2-YkJUp19fdMPv4FFja5A7mALO3-5gzsr0moBVxbT7wzO0dLk_iv-_" +
                "SZye6N95gOvc8iTXYn_v9dTO8Nx9QPqG9xkNjCfalvB7pcPoC4ncYlWQDAAA1&aadTenantId=h",

                ResourceGroupName = "resources",
                ResourceId = "/subscriptions/6e0cb82e-37c4-473b-bb45-8b546cfc01b6/resourceGroups/resources/" +
                "providers/microsoft.insights/components/AzureTest20170922040158",

                ResourceName = "AzureTest20170922040158",
                ResourceType = "components",
                SubscriptionId = "6e0cb82e-37c4-473b-bb45-8b546cfc01b6",
                Timestamp = DateTime.Parse("12/13/2017 20:53:57Z"),
            };
            var expectedString = JsonConvert.SerializeObject(expectedContext, _serializerSettings);
            var json = EmbeddedResource.ReadAsJObject("Microsoft.AspNet.WebHooks.Messages.AzureAlert.WebTest.json");

            // Act
            var actualContext = json["context"].ToObject<AzureAlertContext>();

            // replacedert
            var actualString = JsonConvert.SerializeObject(actualContext, _serializerSettings);
            replacedert.Equal(expectedString, actualString);
        }

19 Source : AzureAlertNotificationTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void AlertNotification_Roundtrips()
        {
            // Arrange
            var data = EmbeddedResource.ReadAsJObject("Microsoft.AspNet.WebHooks.Messages.AlertMessage2.json");
            var expected = new AzureAlertNotification
            {
                Status = "Activated",
                Context = new AzureAlertContext
                {
                    Id = "/subscriptions/aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee/resourceGroups/WebHookReceivers/providers/microsoft.insights/alertrules/henrikntest01",
                    Name = "henrikntest01",
                    Description = "Requests",
                    ConditionType = "Metric",
                    Condition = new AzureAlertCondition
                    {
                        MetricName = "Http 2xx",
                        MetricUnit = "Count",
                        MetricValue = "8",
                        Threshold = "1",
                        WindowSize = "5",
                        TimeAggregation = "Total",
                        Operator = "GreaterThan",
                    },
                    SubscriptionId = "aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee",
                    ResourceGroupName = "WebHookReceivers",
                    Timestamp = DateTime.Parse("2015-09-30T03:02:33.4147662Z").ToUniversalTime(),
                    ResourceName = "webhookreceivers",
                    ResourceType = "microsoft.web/sites",
                    ResourceId = "/subscriptions/aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee/resourceGroups/WebHookReceivers/providers/Microsoft.Web/sites/WebHookReceivers",
                    ResourceRegion = "West US",
                    PortalLink = "https://portal.azure.com/#resource/subscriptions/aaaaaaa-bbbb-cccc-ddd-eeeeeeeeeeeee/resourceGroups/WebHookReceivers/providers/Microsoft.Web/sites/WebHookReceivers",
                }
            };
            expected.Properties.Add("prop1", "value1");
            expected.Properties.Add("prop2", 12345.00);

            // Act
            var actual = data.ToObject<AzureAlertNotification>();

            // replacedert
            var expectedJson = JsonConvert.SerializeObject(expected, _serializerSettings);
            var actualJson = JsonConvert.SerializeObject(actual, _serializerSettings);
            replacedert.Equal(expectedJson, actualJson);
        }

19 Source : KuduNotificationTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void KuduNotification_Roundtrips()
        {
            // Arrange
            JObject data = EmbeddedResource.ReadAsJObject("Microsoft.AspNet.WebHooks.Messages.KuduMessage.json");
            KuduNotification expected = new KuduNotification
            {
                Id = "ff17489fbcb7e2dda9012ec285811b9b751ebb5e",
                Status = "success",
                StatusText = string.Empty,
                Autreplacedmail = "[email protected]",
                Author = "Henrik Frystyk Nielsen",
                Message = "initial commit\n",
                Progress = string.Empty,
                Deployer = "HenrikN",
                ReceivedTime = DateTime.Parse("2015-09-26T04:26:53.8736751Z"),
                StartTime = DateTime.Parse("2015-09-26T04:26:54.2486694Z"),
                EndTime = DateTime.Parse("2015-09-26T04:26:55.6393049Z"),
                LastSuccessEndTime = DateTime.Parse("2015-09-26T04:26:55.6393049Z"),
                Complete = true,
                SiteName = "test",
            };

            // Act
            KuduNotification actual = data.ToObject<KuduNotification>();

            // replacedert
            string expectedJson = JsonConvert.SerializeObject(expected, _serializerSettings);
            string actualJson = JsonConvert.SerializeObject(actual, _serializerSettings);
            replacedert.Equal(expectedJson, actualJson);
        }

19 Source : BitbucketTargetTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void BitbucketTarget_Roundtrips()
        {
            // Arrange
            JObject data = EmbeddedResource.ReadAsJObject("Microsoft.AspNet.WebHooks.Messages.PushMessage.json");
            BitbucketUser expectedUser = new BitbucketUser
            {
                UserType = "user",
                DisplayName = "HenrikN",
                UserName = "HenrikN",
                UserId = "{534d978b-53c8-401b-93b7-ee1f98716edd}",
            };
            expectedUser.Links.Add("html", new BitbucketLink { Reference = "https://bitbucket.org/HenrikN/" });
            expectedUser.Links.Add("avatar", new BitbucketLink { Reference = "https://bitbucket.org/account/HenrikN/avatar/32/" });
            expectedUser.Links.Add("self", new BitbucketLink { Reference = "https://api.bitbucket.org/2.0/users/HenrikN" });

            BitbucketAuthor expectedAuthor = new BitbucketAuthor
            {
                User = expectedUser,
                Raw = "Henrik Frystyk Nielsen <[email protected]>",
            };

            BitbucketTarget expectedTarget = new BitbucketTarget
            {
                Message = "update\n",
                Operation = "commit",
                Hash = "8339b7affbd7c70bbacd0276f581d1ca44df0853",
                Author = expectedAuthor,
                Date = DateTime.Parse("2015-09-30T18:48:38+00:00").ToUniversalTime(),
            };

            BitbucketParent expectedParent = new BitbucketParent
            {
                Operation = "commit",
                Hash = "b05057cd04921697c0f119ca40fe4a5afa481074",
            };
            expectedParent.Links.Add("html", new BitbucketLink { Reference = "https://bitbucket.org/henrikfrystyknielsen/henrikntest01/commits/b05057cd04921697c0f119ca40fe4a5afa481074" });
            expectedParent.Links.Add("self", new BitbucketLink { Reference = "https://api.bitbucket.org/2.0/repositories/henrikfrystyknielsen/henrikntest01/commit/b05057cd04921697c0f119ca40fe4a5afa481074" });

            expectedTarget.Parents.Add(expectedParent);
            expectedTarget.Links.Add("html", new BitbucketLink { Reference = "https://bitbucket.org/henrikfrystyknielsen/henrikntest01/commits/8339b7affbd7c70bbacd0276f581d1ca44df0853" });
            expectedTarget.Links.Add("self", new BitbucketLink { Reference = "https://api.bitbucket.org/2.0/repositories/henrikfrystyknielsen/henrikntest01/commit/8339b7affbd7c70bbacd0276f581d1ca44df0853" });

            // Act
            BitbucketTarget actualTarget = data["push"]["changes"][0]["new"]["target"].ToObject<BitbucketTarget>();

            // replacedert
            string expectedJson = JsonConvert.SerializeObject(expectedTarget, _serializerSettings);
            string actualJson = JsonConvert.SerializeObject(actualTarget, _serializerSettings);
            replacedert.Equal(expectedJson, actualJson);
        }

19 Source : WebHookReceiverTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task ReadAsJsonAsync_Handles_UtcDateTime()
        {
            // Arrange
            var expectedDateTime = DateTime.Parse("2015-09-26T04:26:55.6393049Z").ToUniversalTime();
            Initialize(TestSecret);
            _request.Content = new StringContent("{ \"datetime\": \"2015-09-26T04:26:55.6393049Z\" }", Encoding.UTF8, "application/json");

            // Act
            var actual = await _receiverMock.ReadAsJsonAsync(_request);
            var actualDateTime = actual["datetime"].ToObject<DateTime>();

            // replacedert
            replacedert.Equal(expectedDateTime, actualDateTime);
        }

19 Source : WebHookReceiverTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task ReadAsJsonTokenAsync_Handles_UtcDateTime()
        {
            // Arrange
            var expectedDateTime = DateTime.Parse("2015-09-26T04:26:55.6393049Z").ToUniversalTime();
            Initialize(TestSecret);
            _request.Content = new StringContent("{ \"datetime\": \"2015-09-26T04:26:55.6393049Z\" }", Encoding.UTF8, "application/json");

            // Act
            var actual = await _receiverMock.ReadAsJsonTokenAsync(_request);
            var actualDateTime = actual["datetime"].ToObject<DateTime>();

            // replacedert
            replacedert.Equal(expectedDateTime, actualDateTime);
        }

19 Source : TimeStrategyTests.cs
with Apache License 2.0
from asynkron

[Fact]
        public void TimeStrategy_ShouldSnapshotAccordingToTheInterval()
        {
            var now = DateTime.Parse("2000-01-01 12:00:00");
            var strategy = new TimeStrategy(TimeSpan.FromSeconds(10), () => now);
            replacedert.False(strategy.ShouldTakeSnapshot(new PersistedEvent(null, 0)));
            now = now.AddSeconds(5);
            replacedert.False(strategy.ShouldTakeSnapshot(new PersistedEvent(null, 0)));
            now = now.AddSeconds(5);
            replacedert.True(strategy.ShouldTakeSnapshot(new PersistedEvent(null, 0)));
            now = now.AddSeconds(5);
            replacedert.False(strategy.ShouldTakeSnapshot(new PersistedEvent(null, 0)));
            now = now.AddSeconds(5);
            replacedert.True(strategy.ShouldTakeSnapshot(new PersistedEvent(null, 0)));
        }

19 Source : DateTimePropertyData.cs
with MIT License
from atenfyr

public override void FromString(string[] d, Ureplacedet replacedet)
        {
            Value = DateTime.Parse(d[0]);
        }

19 Source : OAuthController.cs
with MIT License
from Autodesk-Forge

public static async Task<Credentials> FromDatabaseAsync(string userId)
        {
            var doc = await OAuthDB.GetCredentials(userId);

            Credentials credentials = new Credentials();
            credentials.TokenInternal = (string)doc["TokenInternal"];
            credentials.TokenPublic = (string)doc["TokenPublic"];
            credentials.RefreshToken = (string)doc["RefreshToken"];
            credentials.ExpiresAt = DateTime.Parse((string)doc["ExpiresAt"]);
            credentials.UserId = userId;

            if (credentials.ExpiresAt < DateTime.Now)
            {
                await credentials.RefreshAsync();
            }

            return credentials;
        }

19 Source : ParseExtensions.cs
with Apache License 2.0
from AutomateThePlanet

public static DateTime ToDateTime(this string value)
        {
            return DateTime.Parse(value);
        }

19 Source : WeekControlDataHandler.cs
with Apache License 2.0
from AutomateThePlanet

public void SetData(Week element, string data)
        {
            DateTime valueToSet = DateTime.Parse(data);
            element.SetWeek(valueToSet.Year, CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(valueToSet, CalendarWeekRule.FirstDay, DayOfWeek.Monday));
        }

19 Source : UtcToHumanizedLocalDateTimeConverter.cs
with MIT License
from awaescher

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var date = DateTime.SpecifyKind(DateTime.Parse(value.ToString()), DateTimeKind.Utc).ToLocalTime();
			return Humanizer.HumanizeTimestamp(date);
		}

19 Source : UtcToLocalDateTimeConverter.cs
with MIT License
from awaescher

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return DateTime.SpecifyKind(DateTime.Parse(value.ToString()), DateTimeKind.Utc).ToLocalTime();
		}

19 Source : Extention.DateTime.cs
with MIT License
from awesomedotnetcore

public static DateTime Default(this DateTime dt)
        {
            return DateTime.Parse("1970-01-01");
        }

19 Source : AyTypeConvertAndIf.cs
with MIT License
from ay2015

[Pure]
    public static DateTime ToDateTime(this object obj)
    {
        try
        {
            DateTime dt = DateTime.Parse(ToObjectString(obj));
            if (dt > DateTime.MinValue && DateTime.MaxValue > dt)
                return dt;
            return DateTime.Now;
        }
        catch
        { return DateTime.Now; }
    }

19 Source : MakeMKV.cs
with MIT License
from AyrA

public static int ToUnixTime(DateTime T)
        {
            return (int)T.ToUniversalTime().Subtract(DateTime.Parse(UNIX_EPOCH).ToUniversalTime()).TotalSeconds;
        }

19 Source : AyCommonConvert.cs
with MIT License
from ay2015

[Pure]
        public static DateTime ToDateTime(this object obj)
        {
            try
            {
                DateTime dt = DateTime.Parse(ToObjectString(obj));
                if (dt > DateTime.MinValue && DateTime.MaxValue > dt)
                    return dt;
                return DateTime.Now;
            }
            catch
            { return DateTime.Now; }
        }

19 Source : MakeMKV.cs
with MIT License
from AyrA

public static DateTime FromUnixTime(int UnixTime)
        {
            return DateTime.Parse(UNIX_EPOCH).ToUniversalTime().AddSeconds(UnixTime);
        }

19 Source : WebDAV.cs
with MIT License
from azist

private static IEnumerable<Version> createVersionsFromXML(string xml)
      {
        XDoreplacedent doc = XDoreplacedent.Parse(xml);

        var q = doc
          .Elements().Where(e => e.Name.LocalName == "log-report")
          .Elements().Where(e => e.Name.LocalName == "log-item");

        foreach (var e in q)
        {
          var versionEl = e.Elements().First(e1 => e1.Name.LocalName == "version-name");
          var commentEl = e.Elements().First(e1 => e1.Name.LocalName == "comment");
          var creatorEl = e.Elements().First(e1 => e1.Name.LocalName == "creator-displayname");
          var dateEl = e.Elements().First(e1 => e1.Name.LocalName == "date");

          DateTime date = DateTime.Parse(dateEl.Value);

          yield return new Version(versionEl.Value, commentEl.Value, creatorEl.Value, date);
        }
      }

See More Examples