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 View Source File : InstructorsControllerTests.cs
License : MIT License
Project Creator : alimon808

private List<Student> Students()
        {
            return new List<Student>
                {
                    new Student{ ID = 1, FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
                    new Student{ ID = 2, FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
                    new Student{ ID = 3, FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
                    new Student{ ID = 4, FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
                    new Student{ ID = 5, FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
                    new Student{ ID = 6, FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
                    new Student{ ID = 7, FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
                    new Student{ ID = 8, FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
            };
        }

19 View Source File : DepartmentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task HttpPut_ReturnsANotFoundResult()
        {
            var departmentToUpdate = new Department { ID = 0, Name = "English 2", Budget = 350000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID = 1, RowVersion = new byte[] { } };
            var dto = _mapper.Map<DepartmentDTO>(departmentToUpdate);

            var result = await _sut.Update(departmentToUpdate.ID, dto);

            replacedert.IsType<NotFoundResult>(result);
        }

19 View Source File : RetrieveActivityBase.cs
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 =
                        [email protected]"<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 =
                            [email protected]"<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;
        }

19 View Source File : DepartmentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task HttpPost_ReturnsCreatedAtRouteResult_WithDepartmentEnreplacedy()
        {
            var department = new Department { ID = 5, Name = "Physics", Budget = 100000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID = 1 };

            var departmentToAdd = _mapper.Map<CreateDepartmentDTO>(department);
            var result = await _sut.Create(departmentToAdd);

            replacedert.NotNull(result);
            replacedert.IsType<CreatedAtRouteResult>(result);
            replacedert.Equal(201, ((CreatedAtRouteResult)result).StatusCode);

            var departmentCreated = _mapper.Map<DepartmentDTO>(((CreatedAtRouteResult)result).Value);
            replacedert.Equal(department.ID, departmentCreated.ID);
            replacedert.Equal(departmentToAdd.Name, department.Name);
        }

19 View Source File : PostSubdirectoryHelperTests.cs
License : MIT License
Project Creator : AlexCSDev

[Fact]
        public async Task CreateNameFromPattern_CrawledUrlIsProperlyFilled_ProperStringIsReturned()
        {
            PatreonCrawledUrl crawledUrl = new PatreonCrawledUrl
            {
                PostId = "123456",
                replacedle = "Test Post",
                PublishedAt = DateTime.Parse("07.07.2020 20:00:15"),
                Url = "http://google.com",
                Filename = "test.png",
                UrlType = PatreonCrawledUrlType.PostMedia
            };

            replacedert.Equal("[123456] 2020-07-07 Test Post", PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, "[%PostId%] %PublishedAt% %Postreplacedle%"));
        }

19 View Source File : PackageServiceTests.cs
License : MIT License
Project Creator : ai-traders

[Fact]
        public async Task GetPackageWithDependencies() {
            var packageService = server.Host.Services.GetRequiredService<IPackageService>();

            var result = await packageService.AddAsync(new Package() {
                Id = "Dummy",
                replacedle = "Dummy",
                Listed = true,
                Version = NuGetVersion.Parse("1.0.0"),
                Authors = new [] { "Anton Setiawan" },
                LicenseUrl = new Uri("https://github.com/antonmaju/dummy/blob/master/LICENSE"),
                MinClientVersion = null,
                Published = DateTime.Parse("1900-01-01T00:00:00"),
                Dependencies = new List<Enreplacedies.PackageDependency>() {
                    new Enreplacedies.PackageDependency() { Id="Consul", VersionRange="[0.7.2.6, )", TargetFramework=".NETStandard2.0" }
                }
            });
            replacedert.Equal(PackageAddResult.Success, result);

            var found = await packageService.FindOrNullAsync(new NuGet.Packaging.Core.PackageIdenreplacedy("dummy", NuGetVersion.Parse("1.0.0")), false, true);
            replacedert.NotNull(found.Dependencies);
            replacedert.NotEmpty(found.Dependencies);
            var one = found.Dependencies.Single();
            replacedert.Equal("Consul", one.Id);
            replacedert.Equal("[0.7.2.6, )", one.VersionRange);
        }

19 View Source File : DepartmentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task HttpPost_ReturnsABadRequestResult_WhenInstructorIdDoesNotExist()
        {
            var department = new Department
            {
                ID = 5,
                Name = "Physics",
                Budget = 100000,
                AddedDate = DateTime.UtcNow,
                ModifiedDate = DateTime.UtcNow,
                StartDate = DateTime.Parse("2007-09-01"),
                InstructorID = 99
            };
            var departmentToAdd = _mapper.Map<CreateDepartmentDTO>(department);
            var result = await _sut.Create(departmentToAdd);

            replacedert.NotNull(result);
            replacedert.IsType<BadRequestObjectResult>(result);
            replacedert.Equal(400, ((BadRequestObjectResult)result).StatusCode);

            var value = ((BadRequestObjectResult)result).Value as SerializableError;
            replacedert.True(value.Count == 1);
            replacedert.True(value.ContainsKey("InstructorID"));
        }

19 View Source File : MockOpenInvoicePayment.cs
License : MIT License
Project Creator : Adyen

public static PaymentRequest CreateOpenInvoicePaymentRequest()
        {

            DateTime dateOfBirth = DateTime.Parse("1970-07-10");

            PaymentRequest paymentRequest = MockPaymentData.CreateFullPaymentRequest();

            // Set Shopper Data
            paymentRequest.ShopperEmail = "[email protected]";
            paymentRequest.DateOfBirth = dateOfBirth;
            paymentRequest.TelephoneNumber = "0612345678";
            paymentRequest.ShopperReference = "4";

            // Set Shopper Info
            Name shopperName = new Name
            {
                FirstName = "Testperson-nl",
                LastName = "Approved",
                Gender = GenderEnum.MALE
            };
            paymentRequest.ShopperName = shopperName;

            // Set Billing and Delivery address
            Address address = new Address
            {
                City = "Gravenhage",
                Country = "NL",
                HouseNumberOrName = "1",
                PostalCode = "2521VA",
                StateOrProvince = "Zuid-Holland",
                Street = "Neherkade"
            };
            paymentRequest.DeliveryAddress = address;
            paymentRequest.BillingAddress = address;

            // Use OpenInvoice Provider (klarna, ratepay)
            paymentRequest.SelectedBrand = "klarna";

            long itemAmount = long.Parse("9000");
            long itemVatAmount = long.Parse("1000");
            long itemVatPercentage = long.Parse("1000");

            List<InvoiceLine> invoiceLines = new List<InvoiceLine>();

            // invoiceLine1
            InvoiceLine invoiceLine = new InvoiceLine
            {
                CurrencyCode = ("EUR"),
                Description = ("Test product"),
                VatAmount = (itemVatAmount),
                ItemAmount = (itemAmount),
                ItemVatPercentage = (itemVatPercentage),
                VatCategory = (VatCategory.None),
                NumberOfItems = (1),
                ItemId = ("1234")
            };

            // invoiceLine2
            // invoiceLine1
            InvoiceLine invoiceLine2 = new InvoiceLine
            {
                CurrencyCode = ("EUR"),
                Description = ("Test product2"),
                VatAmount = (itemVatAmount),
                ItemAmount = (itemAmount),
                ItemVatPercentage = (itemVatPercentage),
                VatCategory = (VatCategory.None),
                NumberOfItems = (1),
                ItemId = ("456")
            };
            
            invoiceLines.Add(invoiceLine);
            invoiceLines.Add(invoiceLine2);

            paymentRequest.InvoiceLines(invoiceLines);

            return paymentRequest;
        }

19 View Source File : AppBaseTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private async Task<Instance> CreateInstance(string org, string app)
        {
            string token = PrincipalUtil.GetToken(1337);

            Instance instanceTemplate = new Instance
            {
                InstanceOwner = new InstanceOwner
                {
                    PartyId = "1337",
                },
                DueBefore = DateTime.Parse("2020-01-01"),
            };

            HttpClient client = SetupUtil.GetTestClient(_factory, org, app);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            StringContent content = new StringContent(instanceTemplate.ToString(), Encoding.UTF8);
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, $"/{org}/{app}/instances")
            {
                Content = content,
            };

            HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
            string responseContent = await response.Content.ReadreplacedtringAsync();

            Instance result = JsonConvert.DeserializeObject<Instance>(responseContent);

            return result;
        }

19 View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime? GetDateArg(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
            {
                return null;
            }
            return DateTime.Parse(value);
        }

19 View Source File : QuikDde.cs
License : Apache License 2.0
Project Creator : AlexWan

private void TradesUpdated(long id, object[,] table)
        {
            try
            {
                int countElem = table.GetLength(0);

                if (countElem == 0)
                {
                    return;
                }

                Trade[] trades = new Trade[countElem];

                for (int i = 0; i < countElem; i++)
                {
                    trades[i] = new Trade();
                    trades[i].Id = table[i, 0].ToString();
                    string[] time = DateTime.Parse(table[i, 2].ToString()).ToString("HH:mm:ss").Split(':');

                    string[] date = table[i, 1].ToString().Split('.');


                    if (date.Length == 1)
                    {
                        date = table[i, 1].ToString().Split('/');
                        trades[i].Time = new DateTime(Convert.ToInt32(date[2]),
                            Convert.ToInt32(date[0]), Convert.ToInt32(date[1]),
                            Convert.ToInt32(time[0]), Convert.ToInt32(time[1]),
                            Convert.ToInt32(time[2])
                        );
                    }
                    else
                    {
                        trades[i].Time = new DateTime(Convert.ToInt32(date[2]),
                            Convert.ToInt32(date[1]), Convert.ToInt32(date[0]),
                            Convert.ToInt32(time[0]), Convert.ToInt32(time[1]),
                            Convert.ToInt32(time[2])
                        );
                    }

                    



                    trades[i].SecurityNameCode = table[i, 3].ToString();
                    trades[i].Price = ToDecimal(table[i, 4]);
                    trades[i].Volume = Convert.ToInt32(table[i, 5]);

                    string operation = table[i, 6].ToString().ToLower();

                    if (!string.IsNullOrWhiteSpace(operation))
                    {
                        if (operation == "купля" || operation == "b" || operation == "buy")
                        {
                            trades[i].Side = Side.Buy;
                        }
                        else if (operation == "продажа" || operation == "s" || operation == "sell")
                        {
                            trades[i].Side = Side.Sell;
                        }
                        else
                        {
                            trades[i].Side = Side.None;
                        }
                    }
                    else
                    {
                        trades[i].Side = Side.None;
                    }

                }

                List<Trade> newTrade = new List<Trade>(trades);

                if (UpdateTrade != null)
                {
                    UpdateTrade(newTrade);
                }
            }
            catch (Exception error)
            {

                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : PostSubdirectoryHelperTests.cs
License : MIT License
Project Creator : AlexCSDev

[Fact]
        public async Task CreateNameFromPattern_CrawledUrlreplacedleIsNull_replacedleIsReplacedWithNoreplacedle()
        {
            PatreonCrawledUrl crawledUrl = new PatreonCrawledUrl
            {
                PostId = "123456",
                replacedle = null,
                PublishedAt = DateTime.Parse("07.07.2020 20:00:15"),
                Url = "http://google.com",
                Filename = "test.png",
                UrlType = PatreonCrawledUrlType.PostMedia
            };

            replacedert.Equal("[123456] 2020-07-07 No replacedle", PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, "[%PostId%] %PublishedAt% %Postreplacedle%"));
        }

19 View Source File : ApiControlerEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime GetDateArg(string name, DateTime def)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null") return def;
            return DateTime.Parse(value);
        }

19 View Source File : CoursesControllerTests.cs
License : MIT License
Project Creator : alimon808

private List<Department> Departments()
        {
            return new List<Department>
            {
                    new Department { ID = 1, Name = "English",     Budget = 350000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID  = 1 },
                    new Department { ID = 2, Name = "Mathematics", Budget = 100000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID  = 2 },
                    new Department { ID = 3, Name = "Engineering", Budget = 350000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID  = 3 },
                    new Department { ID = 4, Name = "Economics",   Budget = 100000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID  = 4 }
            };
        }

19 View Source File : AduDateTimePicker.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            AduDateTimePicker dateTimePicker = (AduDateTimePicker)sender;
            if (e.Property == ValueProperty)
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(Convert.ToString(e.NewValue), out dt))
                {
                    dateTimePicker.SelectedDate = dt;
                    dateTimePicker.DisplayDate = dt;
                    dateTimePicker.PART_TimePicker.Value = dt;

                    string datetime = dt.ToString(dateTimePicker.DateFormat);
                    if (dateTimePicker.PART_TextBox != null)
                    {
                        dateTimePicker.PART_TextBox.Text = datetime;
                        if (string.IsNullOrEmpty(datetime))
                        {
                            dateTimePicker.PART_Calendar.SelectedDate = null;
                            dateTimePicker.Value = null;
                        }
                        else
                        {
                            dateTimePicker.PART_Calendar.SelectedDate = DateTime.Parse(datetime);
                            dateTimePicker.PART_Calendar.DisplayDate = DateTime.Parse(datetime);
                        }
                    }
                }
            }
            else
            {
                dateTimePicker.PART_TextBox.Text = string.Empty;
                dateTimePicker.PART_Calendar.SelectedDate = null;
                dateTimePicker.Value = null;
            }
        }

19 View Source File : IntegrationTests.cs
License : MIT License
Project Creator : alimon808

[Theory(Skip = "Local Test Only")]
        [InlineData("Departments")]
        //todo: integration testing on Courses, Instructors, and Students
        //[InlineData("Courses")]
        //[InlineData("Instructors")]
        //[InlineData("Students")]
        public async Task CRUD(string controller)
        {

            var url = $"/{controller}/Create";
            using (var th = InitTestServer())
            {
                // get create form to retrieve antiforgery token
                var client = th.CreateClient();
                var response = await client.GetAsync(url);
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);

                // create enreplacedy 
                var cookieVal = response.GetAntiForgeryCookie(AntiForgeryCookieName).ToString();
                var formTokenVal = await response.GetAntiForgeryFormToken(AntiForgeryFormTokenName);
                client.DefaultRequestHeaders.Add("Cookie", cookieVal);

                var departmentToAdd = new DepartmentCreateViewModel { Name = "Economics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = 4 };
                response = await client.PostFormDataAsync<DepartmentCreateViewModel>(url, departmentToAdd, formTokenVal);

                replacedert.Equal(HttpStatusCode.Redirect, response.StatusCode);
                replacedert.Contains("newid", response.Headers.Location.ToString());

                // verify enreplacedy was added
                var uri = new Uri(client.BaseAddress, response.Headers.Location.ToString());
                var queryDictionary = QueryHelpers.ParseQuery(uri.Query);
                var newid = queryDictionary["newid"];

                response = await client.GetAsync($"/{controller}/Details/{newid}");
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);

                //edit new enreplacedy
                url = $"/{controller}/Edit/{newid}";
                response = await client.GetAsync(url);
                formTokenVal = await response.GetAntiForgeryFormToken(AntiForgeryFormTokenName);
                var rowVersion = await response.GetRowVersion();
                var departmentToEdit = new DepartmentEditViewModel { ID = int.Parse(newid), Name = "Economics 2", Budget = 999, StartDate = DateTime.UtcNow, RowVersion = rowVersion };
                response = await client.PostFormDataAsync<DepartmentEditViewModel>(url, departmentToEdit, formTokenVal);

                replacedert.Equal(HttpStatusCode.Redirect, response.StatusCode);

                // delete new enreplacedy
                url = $"/{controller}/delete/{newid}";
                response = await client.GetAsync(url);
                replacedert.Equal(HttpStatusCode.OK, response.StatusCode);

                formTokenVal = await response.GetAntiForgeryFormToken(AntiForgeryFormTokenName);
                var departmentToDelete = new DepartmentDetailsViewModel { ID = int.Parse(newid) };
                response = await client.PostFormDataAsync<DepartmentDetailsViewModel>(url, departmentToDelete, formTokenVal);
                replacedert.Equal(HttpStatusCode.Redirect, response.StatusCode);

            }
        }

19 View Source File : AiurUrl.Tests.cs
License : MIT License
Project Creator : AiursoftWeb

[TestMethod]
        public void TestComplicated()
        {
            var url = new AiurUrl("https://www.bing.com", "Home", "Search", new TestAddressModel
            {
                Question = "MyQuestion",
                Count = 10,
                Email = "[email protected]",
                MyNull = null,
                CreateTime = DateTime.Parse("2020-01-01 14:15:16")
            });
            var result = url.ToString();
            replacedert.AreEqual("https://www.bing.com/Home/Search?question=MyQuestion&count=10&emailaddress=aaa%40bbb.com&createtime=2020-01-01T14%3A15%3A16.0000000", result);
        }

19 View Source File : DepartmentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task CreatePost_ReturnsRedirectToActionResult_Index()
        {
            var vm = new DepartmentCreateViewModel
            {
                Name = "Biology",
                Budget = 100,
                StartDate = DateTime.Parse("2007-09-01"),
                InstructorID = 1
            };

            var result = await sut.Create(vm);

            replacedert.IsType<RedirectToActionResult>(result);
            replacedert.Equal("Index", ((RedirectToActionResult)result).ActionName);
        }

19 View Source File : SqlServerJobRepository_UpdateStatusAsync_Test.cs
License : MIT License
Project Creator : AdemCatamak

[Fact]
        public async Task When_UpdateAsyncExecuted__Status_LastOperationInfo_LastOperationTime_ShouldBeChanged()
        {
            var jobId = Guid.NewGuid();
            DateTime lastOperationTime = DateTime.Parse("2021-01-01");
            const string lastOperationInfo = "last-operation-info";

            Job job = new Job(jobId, new Message("some-payload"), "some-handler", JobStatus.Queued, DateTime.UtcNow, lastOperationTime, lastOperationInfo, 5, DateTime.UtcNow);
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            await jobRepository.AddAsync(job);

            job.SetCompleted();
            await jobRepository.UpdateJobStatusAsync(job);

            await using var connection = new SqlConnection(_sqlServerInfraFixture.ConnectionString);
            string jobCountScript = $"select * from {SCHEMA}.jobs where id = @id";
            dynamic? jobFromDb = await connection.QueryFirstAsync(jobCountScript, param: new {id = job.Id});

            replacedert.Equal(jobId, jobFromDb.Id);
            replacedert.Equal((int) JobStatus.Completed, jobFromDb.JobStatus);
            replacedert.Equal(JobStatus.Completed.ToString(), jobFromDb.LastOperationInfo);
            replacedertThat.LessThan((DateTime) jobFromDb.LastOperationTime, lastOperationTime);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

private static bool IsThereCertificateAndIsItToBeRenewed(List<string> domains)
        {
            string certificateExpirationDate = _config.ReadStringParameter("certExpDate" + Utils.DomainsToHostId(domains));
            _logger.Debug($"Current certificate expiration date is: {certificateExpirationDate}");
            if ((certificateExpirationDate == null) || (certificateExpirationDate.Length == 0)) return true;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            DateTime expirationDate = DateTime.Parse(certificateExpirationDate);
            DateTime futureThresold = DateTime.Now.AddDays(_config.ReadIntParameter("renewalDays", 30));
            _logger.Debug($"Expiration Thresold Date after delay: {futureThresold.ToString()}");
            if (futureThresold > expirationDate) return true;
            _logger.Debug("Certificate exists and does not need to be renewed");
            return false;
        }

19 View Source File : PatreonCrawledUrlProcessorTests.cs
License : MIT License
Project Creator : AlexCSDev

[Fact]
        public async Task ProcessCrawledUrl_MediaFileNameIsUrl_IsTruncatedAndNoExtension()
        {
            PatreonDownloaderSettings settings = new PatreonDownloaderSettings
            {
                CookieContainer = new CookieContainer(),
                DownloadDirectory = "c:\\downloads",
                MaxDownloadRetries = 10,
                OverwriteFiles = false,
                RemoteFileSizeNotAvailableAction = RemoteFileSizeNotAvailableAction.KeepExisting,
                RetryMultiplier = 1,
                SaveAvatarAndCover = true,
                SaveDescriptions = true,
                SaveEmbeds = true,
                SaveJson = true,
                UseSubDirectories = true,
                SubDirectoryPattern = "[%PostId%] %PublishedAt% %Postreplacedle%",
                MaxFilenameLength = 50
            };

            settings.Consumed = true;

            PatreonCrawledUrl crawledUrl = new PatreonCrawledUrl
            {
                PostId = "123456",
                replacedle = "Test Post",
                PublishedAt = DateTime.Parse("07.07.2020 20:00:15"),
                Url = "https://www.patreon.com/media-u/Z0FBQUFBQmhXZDd3LXMwN0lJUFdVYTVIMEY1OGxzZTgwaFpQcW5TMk5WQVgxd2JVRFZvRXhjMjQ2V09oTW51eUpLQzIyOW1TdHRzYkY2Uk4yclAwX0VsSXBPMFZsNTBTcmZoaGx4OXJkR1Zham1CYl9fOWNVb3AzZGN1Wl9FMmNzcmIxc3hDek4xcHNuRV92LUVqQ0JESE4tcVBNYzlxYkRnWQ1=",
                Filename = "https://www.patreon.com/media-u/Z0FBQUFBQmhXZDd3a0xfckdEWmFrU0tjZHFUUkZfaDZ1OW92TjFVWFVDNk02c2FvS2FNczZxMS1rSVlaNUotX095dUNhdzJBSmYzMVpDV1luR1BYSXR6OVlZelpFOFFVektEcnpJT1plbElua2kwT1N2ZUMyU1NWaHV0eHQydWhnUXlmVWVLVDFYclBsSDBRaVJ3MDA5d2tzdDRZR3dtb3dBWQ1=",
                UrlType = PatreonCrawledUrlType.PostMedia
            };

            PatreonCrawledUrlProcessor crawledUrlProcessor = new PatreonCrawledUrlProcessor(new PatreonRemoteFilenameRetriever());
            await crawledUrlProcessor.BeforeStart(settings);
            await crawledUrlProcessor.ProcessCrawledUrl(crawledUrl,
                Path.Combine(settings.DownloadDirectory, "UnitTesting"));

            replacedert.Equal(@"c:\downloads\UnitTesting\[123456] 2020-07-07 Test Post\media_https___www.patreon.com_media-u_Z0FBQUFBQmhX", crawledUrl.DownloadPath);
        }

19 View Source File : PatreonCrawledUrlProcessorTests.cs
License : MIT License
Project Creator : AlexCSDev

[Fact]
        public async Task ProcessCrawledUrl_MediaFileNameTooLong_IsTruncatedWithExtension()
        {
            PatreonDownloaderSettings settings = new PatreonDownloaderSettings
            {
                CookieContainer = new CookieContainer(),
                DownloadDirectory = "c:\\downloads",
                MaxDownloadRetries = 10,
                OverwriteFiles = false,
                RemoteFileSizeNotAvailableAction = RemoteFileSizeNotAvailableAction.KeepExisting,
                RetryMultiplier = 1,
                SaveAvatarAndCover = true,
                SaveDescriptions = true,
                SaveEmbeds = true,
                SaveJson = true,
                UseSubDirectories = true,
                SubDirectoryPattern = "[%PostId%] %PublishedAt% %Postreplacedle%",
                MaxFilenameLength = 50
            };

            settings.Consumed = true;

            PatreonCrawledUrl crawledUrl = new PatreonCrawledUrl
            {
                PostId = "123456",
                replacedle = "Test Post",
                PublishedAt = DateTime.Parse("07.07.2020 20:00:15"),
                Url = "https://www.patreon.com/media-u/Z0FBQUFBQmhXZDd3LXMwN0lJUFdVYTVIMEY1OGxzZTgwaFpQcW5TMk5WQVgxd2JVRFZvRXhjMjQ2V09oTW51eUpLQzIyOW1TdHRzYkY2Uk4yclAwX0VsSXBPMFZsNTBTcmZoaGx4OXJkR1Zham1CYl9fOWNVb3AzZGN1Wl9FMmNzcmIxc3hDek4xcHNuRV92LUVqQ0JESE4tcVBNYzlxYkRnWQ1=",
                Filename = "E0OarAVlc0iipzgUC7JdvBCf9fgSmbwk3xRDjRGByTM24SuMl6HkY1DIdGfcvnZhbTb978AHonnwqWNzMPEWBRQp007ateP9ByhB.png",
                UrlType = PatreonCrawledUrlType.PostFile
            };

            PatreonCrawledUrlProcessor crawledUrlProcessor = new PatreonCrawledUrlProcessor(new PatreonRemoteFilenameRetriever());
            await crawledUrlProcessor.BeforeStart(settings);
            await crawledUrlProcessor.ProcessCrawledUrl(crawledUrl,
                Path.Combine(settings.DownloadDirectory, "UnitTesting"));

            replacedert.Equal(@"c:\downloads\UnitTesting\[123456] 2020-07-07 Test Post\post_E0OarAVlc0iipzgUC7JdvBCf9fgSmbwk3xRDjRGByTM24.png", crawledUrl.DownloadPath);
        }

19 View Source File : Job_Creation_Test.cs
License : MIT License
Project Creator : AdemCatamak

[Fact]
        public void When_JobCreatedWithFullProperty__JobContainsAllProperty()
        {
            var jobId = Guid.NewGuid();
            const string messageHandlerTypeName = "message-handler";
            const JobStatus jobStatus = JobStatus.InProgress;
            DateTime createdOn = DateTime.Parse("1923-10-29");
            var lastOperationTime = DateTime.MaxValue;
            const string? lastOperationInfo = "last-operation-info";

            Job job = new Job(jobId, _message, messageHandlerTypeName, jobStatus, createdOn, lastOperationTime, lastOperationInfo, 5, DateTime.UtcNow);

            replacedert.Equal(jobId, job.Id);
            replacedert.Equal(messageHandlerTypeName, job.MessageHandlerTypeName);
            replacedert.Equal(jobStatus, job.JobStatus);
            replacedert.Equal(createdOn, job.CreatedOn);
            replacedert.Equal(lastOperationTime, job.LastOperationTime);
            replacedert.Equal(lastOperationInfo, job.LastOperationInfo);
        }

19 View Source File : PostSubdirectoryHelperTests.cs
License : MIT License
Project Creator : AlexCSDev

[Fact]
        public async Task CreateNameFromPattern_PatternIsInWrongCase_ProperStringIsReturned()
        {
            PatreonCrawledUrl crawledUrl = new PatreonCrawledUrl
            {
                PostId = "123456",
                replacedle = "Test Post",
                PublishedAt = DateTime.Parse("07.07.2020 20:00:15"),
                Url = "http://google.com",
                Filename = "test.png",
                UrlType = PatreonCrawledUrlType.PostMedia
            };

            replacedert.Equal("[123456] 2020-07-07 Test Post", PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, "[%postId%] %PubliSHedAt% %Postreplacedle%"));
        }

19 View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime GetDateArg2(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
            {
                return DateTime.MinValue;
            }
            return DateTime.Parse(value);
        }

19 View Source File : BitfinexClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Converter()
        {
            while (true)
            {
                try
                {
                    if (_isDisposed)
                    {
                        return;
                    }

                    if (!_newMessage.IsEmpty)
                    {
                        string mes;

                        if (_newMessage.TryDequeue(out mes))
                        {
                            if (mes.Contains("\"event\":\"error\""))
                            {
                                lock (_senderLocker)
                                {
                                    SendLogMessage(mes, LogMessageType.Error);
                                }
                            }
                            else if (mes.StartsWith("{\"event\":\"info\""))
                            {
                                lock (_senderLocker)
                                {
                                    if (mes.Contains("\"code\":20051") || mes.Contains("\"code\":20060"))
                                    {
                                        SendLogMessage("остановка/перезапуск сервера Websocket", LogMessageType.Error);

                                        if (Disconnected != null)
                                        {
                                            Disconnected();
                                        }
                                    }
                                }
                            }
                            else if (mes.Contains("\"event\":\"auth\""))
                            {

                            }
                            else if (mes.Contains("\"os\"")) // снимок моих ордеров
                            {


                            }
                            else if(mes.Contains("\"on\""))
                            {
                                
                            }
                            else if ( mes.Contains("\"ou\"") || mes.Contains("\"oc\"")) // обновление или закрытие моего ордера
                            {
                                lock (_senderLocker)
                                {
                                    Thread.Sleep(300);

                                    var values = ParseData(mes);

                                    int numUser = _osOrders[values[0]];

                                    var order = new Order();

                                    order.NumberUser = numUser;
                                    order.SecurityNameCode = values[1];
                                    order.PortfolioNumber = values[1].Substring(3);
                                    order.Side = values[2].ToDecimal() > 0 ? Side.Buy : Side.Sell;
                                    order.NumberMarket = values[0];
                                    order.Price = values[6].ToDecimal();
                                    order.Volume = Math.Abs(values[2].ToDecimal());

                                    order.TimeCallBack = DateTime.Parse(values[8].TrimEnd('Z'));

                                    if (values[5].Contains("EXECUTED"))
                                    {
                                        order.State = OrderStateType.Done;
                                    }
                                    else
                                    {
                                        switch (values[5])
                                        {
                                            case "ACTIVE":
                                                order.State = OrderStateType.Activ;
                                                break;

                                            case "PARTIALLY FILLED":
                                                order.State = OrderStateType.Patrial;
                                                break;

                                            case "CANCELED":
                                                order.TimeCancel = order.TimeCallBack;
                                                order.State = OrderStateType.Cancel;
                                                _osOrders.Remove(order.NumberMarket);
                                                break;

                                            default:
                                                order.State = OrderStateType.None;
                                                break;
                                        }
                                    }
                                    if (MyOrderEvent != null)
                                    {
                                        MyOrderEvent(order);
                                    }
                                }
                            }
                            else if (mes.Contains("[0,\"tu\",[")) // my new trade / новая моя сделка
                            {
                                lock (_senderLocker)
                                {
                                    // [0,"tu",["5809001-IOTBTC",275774974,"IOTBTC",1533415991,15073784940,13,0.00012184,"EXCHANGE LIMIT",0.00012184,-0.026,"IOT"]] моя сделка
                                    var valuesMyTrade = ParseData(mes);

                                    Thread.Sleep(300);

                                    MyTrade myTrade = new MyTrade();
                                    myTrade.Price = valuesMyTrade[6].ToDecimal();
                                    myTrade.NumberTrade = valuesMyTrade[1];
                                    myTrade.SecurityNameCode = valuesMyTrade[2];
                                    myTrade.Side = valuesMyTrade[5].Contains("-") ? Side.Sell : Side.Buy;
                                    myTrade.Volume = Math.Abs(valuesMyTrade[5].ToDecimal());
                                    myTrade.Time = new DateTime(1970, 01, 01) + TimeSpan.FromSeconds(Convert.ToDouble(valuesMyTrade[3]));
                                    myTrade.NumberOrderParent = valuesMyTrade[4];

                                    if (MyTradeEvent != null)
                                    {
                                        MyTradeEvent(myTrade);
                                    }
                                }
                            }
                            else if (mes.Contains("\"ws\"")) // snapshot of portfolios / снимок портфелей
                            {
                                lock (_senderLocker)
                                {
                                    var res = Walets.FromJson(mes)[2].AllWallets;

                                    if (NewPortfolio != null)
                                    {
                                        NewPortfolio(res);
                                    }
                                }
                            }
                            else if (mes.Contains("\"wu\"")) // portfolio update / обновление портфеля
                            {
                                lock (_senderLocker)
                                {
                                    var res = WalletUpdate.FromJson(mes)[2].UpdatedWallet; ;

                                    if (UpdatePortfolio != null)
                                    {
                                        UpdatePortfolio(res);
                                    }
                                }
                            }
                            else if (mes.Contains("[0,\"ps\",[")) // shapshot of position / снимок позиций
                            {
                                
                            }
                            else if (mes.Contains("\"pn\"")|| mes.Contains("\"pu\"")|| mes.Contains("\"pc\"")) // снимок позиций
                            {

                            }
                            else if (mes.Contains("\"event\":\"subscribed\"") && mes.Contains("\"chanId\""))
                            {
                                lock (_senderLocker)
                                {
                                    // inform about successful subscription / информируем об успешной подписке
                                    var info = JsonConvert.DeserializeAnonymousType(mes, new SubscriptionInformation());

                                    if (info.channel == "trades")
                                    {
                                        _subscribedTradesSecurity.Add(info.pair, info.chanId);
                                    }

                                    if (info.channel == "book")
                                    {
                                        _subscribedBooksSecurity.Add(info.pair, info.chanId);
                                    }

                                    string msgInfo =
                                        string.Format(
                                            "Инструмент {0} успешно подписан на канал : {1}, Id канала = {2}", info.pair,
                                            info.channel, info.chanId);

                                    SendLogMessage(msgInfo, LogMessageType.System);

                                }
                            }
                            else if (mes.Contains("\"tu\"")) // new tick / новый тик
                            {
                                lock (_senderLocker)
                                {
                                    var bitfinexTick = UpdateDataBitfinex.FromJson(mes);

                                    // find the security that owns this snapshot / находим бумагу которой принадлежит этот снимок
                                    var namePair =
                                        _subscribedTradesSecurity.FirstOrDefault(
                                            dic => dic.Value == Convert.ToInt32(bitfinexTick[0].Double));

                                    if (NewTradesEvent != null)
                                    {
                                        NewTradesEvent(bitfinexTick, namePair.Key);
                                    }
                                }
                            }
                            else if (mes.Contains("[["))
                            {
                                lock (_senderLocker)
                                {
                                    var countParams = NumberParametersSnapshot(mes);

                                    if (countParams == 3)
                                    {
                                        // process a shapshot of depth / обрабатываем снимок стакана

                                        var orderBook = BitfinexSnapshotParser.FromJson(mes);

                                        // find the security that owns this snapshot / находим бумагу которой принадлежит этот снимок
                                        var namePair =
                                            _subscribedBooksSecurity.FirstOrDefault(
                                                dic => dic.Value == Convert.ToInt32(orderBook[0].IdChanel));

                                        if (NewMarketDepth != null)
                                        {
                                            NewMarketDepth(orderBook, namePair.Key);
                                        }
                                    }
                                }
                            }
                            else if (mes.Contains("hb"))
                            {
                                // heartbeat message came / пришло сообщение серцебиения
                            }
                            else if (!mes.Contains("[[") && !mes.Contains("\"te\"") && !mes.Contains("\"ws\""))
                            {
                                lock (_senderLocker)
                                {
                                    var bitfinexChangeOrderBook = UpdateDataBitfinex.FromJson(mes);

                                    // find the security that owns this snapshot / находим бумагу которой принадлежит этот снимок
                                    var namePair =
                                        _subscribedBooksSecurity.FirstOrDefault(
                                            dic => dic.Value == Convert.ToInt32(bitfinexChangeOrderBook[0].Double));

                                    if (UpdateMarketDepth != null)
                                    {
                                        UpdateMarketDepth(bitfinexChangeOrderBook, namePair.Key);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(1);
                    }
                }

                catch (Exception exception)
                {
                    SendLogMessage(exception.Message, LogMessageType.Connect);
                }                
            }
        }

19 View Source File : UPSProvider.cs
License : MIT License
Project Creator : alexeybusygin

private void ParseRatesResponseMessage(XDoreplacedent xDoc)
        {
            if (xDoc.Root != null)
            {
                var response = xDoc.Root.XPathSelectElement("Response");
                if (response != null)
                {
                    var responseErrors = response.Elements("Error");
                    foreach (var responseError in responseErrors)
                    {
                        AddError(new Error
                        {
                            Description = responseError.XPathSelectElement("ErrorDescription")?.Value,
                            Number = responseError.XPathSelectElement("ErrorCode")?.Value,
                        });
                    }
                }

                var ratedShipment = xDoc.Root.Elements("RatedShipment");
                foreach (var rateNode in ratedShipment)
                {
                    var name = rateNode.XPathSelectElement("Service/Code").Value;
                    AvailableService service;
                    if (_serviceCodes.ContainsKey(name))
                    {
                        service = (AvailableService) _serviceCodes[name];
                    }
                    else
                    {
                        continue;
                    }
                    if (((int) Services & service.EnumValue) != service.EnumValue)
                    {
                        continue;
                    }
                    var description = "";
                    if (_serviceCodes.ContainsKey(name))
                    {
                        description = _serviceCodes[name].ToString();
                    }
                    var totalCharges = Convert.ToDecimal(rateNode.XPathSelectElement("TotalCharges/MonetaryValue").Value);
                    var currencyCode = rateNode.XPathSelectElement("TotalCharges/CurrencyCode").Value;
                    if (UseNegotiatedRates)
                    {
                        var negotiatedRate = rateNode.XPathSelectElement("NegotiatedRates/NetSummaryCharges/GrandTotal/MonetaryValue");
                        if (negotiatedRate != null) // check for negotiated rate
                        {
                            totalCharges = Convert.ToDecimal(negotiatedRate.Value);
                            currencyCode = rateNode.XPathSelectElement("NegotiatedRates/NetSummaryCharges/GrandTotal/CurrencyCode").Value;
                        }
                    }

                    var date = rateNode.XPathSelectElement("GuaranteedDaysToDelivery").Value;
                    if (string.IsNullOrEmpty(date)) // no gauranteed delivery date, so use MaxDate to ensure correct sorting
                    {
                        date = DateTime.MaxValue.ToShortDateString();
                    }
                    else
                    {
                        date = (Shipment.Options.ShippingDate ?? DateTime.Now)
                            .AddDays(Convert.ToDouble(date)).ToShortDateString();
                    }
                    var deliveryTime = rateNode.XPathSelectElement("ScheduledDeliveryTime").Value;
                    if (string.IsNullOrEmpty(deliveryTime)) // no scheduled delivery time, so use 11:59:00 PM to ensure correct sorting
                    {
                        date += " 11:59:00 PM";
                    }
                    else
                    {
                        date += " " + deliveryTime.Replace("Noon", "PM").Replace("P.M.", "PM").Replace("A.M.", "AM");
                    }
                    var deliveryDate = DateTime.Parse(date);

                    AddRate(name, description, totalCharges, deliveryDate, new RateOptions()
                    {
                        SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
                    }, currencyCode);
                }
            }
        }

19 View Source File : ApiControlerEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime GetDateArg2(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null") return DateTime.MinValue;
            return DateTime.Parse(value);
        }

19 View Source File : LicenseInfo.cs
License : Apache License 2.0
Project Creator : Algoryx

private static bool ParseDate( ref LicenseInfo info, string dateString )
    {
      try {
        info.EndDate = DateTime.Parse( dateString );
      }
      catch ( FormatException ) {
        if ( dateString.ToLower() == "none" )
          info.EndDate = DateTime.MaxValue;
        else
          info.EndDate = DateTime.MinValue;

        return false;
      }

      return true;
    }

19 View Source File : DateTimeLiteral.cs
License : MIT License
Project Creator : Adoxio

protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			if (Value == null)
			{
				base.Render(writer);
				return;
			}

			DateTime dt;

			if (Value is DateTime)
			{
				dt = (DateTime)Value;
			}
			else if (Value is DateTime?)
			{
				dt = ((DateTime?)Value).Value;
			}
			else
			{
				dt = DateTime.Parse(Value.ToString());
			}

			if (dt.Kind == DateTimeKind.Utc)
			{
				// check if we are to use the default site timezone
				if (UseSiteTimeZone)
				{
					var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
					var tz = portal.GetTimeZone();
					dt = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

					// if no timezone label provided, use the display name of the current timezone
					if (string.IsNullOrEmpty(TimeZoneLabel))
					{
						TimeZoneLabel = tz.DisplayName;
					}
				}
				else if (!string.IsNullOrEmpty(TimeZone))  // a specific timezone is given
				{
					var tz = TimeZoneInfo.FindSystemTimeZoneById(TimeZone);
					dt = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

					// if no timezone label provided, use the display name of the current timezone
					if (string.IsNullOrEmpty(TimeZoneLabel))
					{	
						TimeZoneLabel = tz.DisplayName;
					}
				}
			}
			
			// output the datetime in the correct format (default if not provided)
			Text = string.IsNullOrEmpty(Format) ? dt.ToString() : dt.ToString(Format);

			// append the time zone label if it is not disabled and if we have one
			if (!string.IsNullOrEmpty(TimeZoneLabel) && OutputTimeZoneLabel)
			{
				Text = "{0} {1}".FormatWith(Text, TimeZoneLabel);
			}

			base.Render(writer);
		}

19 View Source File : DepartmentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task HttpPut_ReturnsANoContentResult()
        {
            var departmentToUpdate = new Department { ID = 1, Name = "English 2", Budget = 350000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID = 1, RowVersion = new byte[] { } };
            var dto = _mapper.Map<DepartmentDTO>(departmentToUpdate);
            var result = await _sut.Update(departmentToUpdate.ID, dto);

            replacedert.IsType<NoContentResult>(result);
        }

19 View Source File : PlanController.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime? GetDateArg(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "-" || value == "undefined" || value == "null" || !DateTime.TryParse(value, out var date))
            {
                return null;
            }
            return DateTime.Parse(value);
        }

19 View Source File : InstructorsControllerTests.cs
License : MIT License
Project Creator : alimon808

private List<Instructor> Instructors()
        {
            return new List<Instructor>
            {
                new Instructor { ID = 1, FirstMidName = "Kim",     LastName = "Abercrombie", HireDate = DateTime.Parse("1995-03-11"),
                    Coursereplacedignments = new List<Coursereplacedignment>
                    {
                        new Coursereplacedignment {
                            CourseID = Courses().Single(c => c.replacedle == "Composition" ).ID,
                            InstructorID = 1,
                            Course = new Course {
                                ID = 6, CourseNumber = 2021, replacedle = "Composition", Credits = 3, DepartmentID = Departments().Single( s => s.Name == "English").ID,
                                Enrollments = new List<Enrollment>
                                {
                                    new Enrollment {
                                        StudentID = Students().Single(s => s.LastName == "Li").ID,
                                        CourseID = Courses().Single(c => c.replacedle == "Composition").ID,
                                        Grade = Grade.B
                                    },
                                    new Enrollment {
                                        StudentID = Students().Single(s => s.LastName == "Alonso").ID,
                                        CourseID = Courses().Single(c => c.replacedle == "Composition" ).ID,
                                        Grade = Grade.B
                                    },
                                }
                            },
                        },
                        new Coursereplacedignment {
                            CourseID = Courses().Single(c => c.replacedle == "Literature" ).ID,
                            InstructorID = 1,
                            Course = new Course {
                                ID = 7, CourseNumber = 2042, replacedle = "Literature", Credits = 4, DepartmentID = Departments().Single( s => s.Name == "English").ID,
                                Enrollments = new List<Enrollment>
                                {
                                    new Enrollment {
                                        StudentID = Students().Single(s => s.LastName == "Justice").ID,
                                        CourseID = Courses().Single(c => c.replacedle == "Literature").ID,
                                        Grade = Grade.B
                                    }
                                }
                            }
                        }
                    },

                },
                new Instructor { ID = 2, FirstMidName = "Fadi",    LastName = "Fakhouri", HireDate = DateTime.Parse("2002-07-06") },
                new Instructor { ID = 3 ,FirstMidName = "Roger",   LastName = "Harui", HireDate = DateTime.Parse("1998-07-01") },
                new Instructor { ID = 4, FirstMidName = "Candace", LastName = "Kapoor", HireDate = DateTime.Parse("2001-01-15") },
                new Instructor { ID = 5, FirstMidName = "Roger",   LastName = "Zheng", HireDate = DateTime.Parse("2004-02-12") }
            };
        }

19 View Source File : Message_Creation_Test.cs
License : MIT License
Project Creator : AdemCatamak

[Fact]
        public void When_MessageCreatedWithFullProperty__MessageContainsAllProperty()
        {
            var guid = Guid.NewGuid();
            var payload = "1";
            DateTime createdOn = DateTime.Parse("1923-10-29");

            Message message = new Message(guid, payload, createdOn);

            replacedert.Equal(guid, message.Id);
            replacedert.Equal(payload, message.Payload);
            replacedert.Equal(createdOn, message.CreatedOn);
        }

19 View Source File : StudentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task CreatePost_ReturnsAViewResult_WithInvalidModel_DbUpdateException()
        {
            var student = new Student { ID = 9, FirstMidName = "John", LastName = "Wick", EnrollmentDate = DateTime.Parse("2005-09-01") };
            mockStudentRepo.Setup(m => m.SaveChangesAsync())
                .Callback(() => throw new DbUpdateException("myexception", new Exception()))
                .Returns(Task.FromResult(0));

            var result = await sut.Create(student);

            replacedert.IsType<ViewResult>(result);

            var viewData = ((ViewResult)result).ViewData;
            replacedert.True(viewData.ModelState.Count > 0);
        }

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static object ObjectFromString(string str, Type type)
		{
			object result = null;
			if (string.IsNullOrEmpty(str))
				result = type.IsValueType ? Activator.CreateInstance(type) : null;
			else if (type == typeof(Guid))
				result = new Guid(str);
			else if (type == typeof(DateTime))
				result = DateTime.Parse(str);
			else if (type == typeof(Decimal))
				result = Decimal.Parse(str);
			else if (type.IsEnum)
				result = Enum.Parse(type, str);
			else if (type.IsArray)
				result = ArrayFromString(str, type);
			else
			{
				var parse = type.GetParseMethod();
				if (parse != null)
					result = parse.Invoke(null, new object[] { str });
				else
				{
					if (type.IsValueType && !type.IsPrimitive)
						result = StructFromString(str, type);
					else
						result = System.Convert.ChangeType(str, type);
				}
			}
			return result;
		}

19 View Source File : DepartmentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task HttpPut_ReturnsABadRequestResult_WithInvalidDepartmentID()
        {
            var departmentToUpdate = new Department { ID = 1, Name = "English 2", Budget = 350000, AddedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, StartDate = DateTime.Parse("2007-09-01"), InstructorID = 1, RowVersion = new byte[] { } };
            var dto = _mapper.Map<DepartmentDTO>(departmentToUpdate);
            var result = await _sut.Update(2, dto);

            replacedert.IsType<BadRequestResult>(result);
        }

19 View Source File : AduDateTimePicker.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void SetDateTime(string datetime)
        {
            if (this.PART_TextBox != null)
            {
                this.PART_TextBox.Text = datetime;
                if (string.IsNullOrEmpty(datetime))
                {
                    this.PART_Calendar.SelectedDate = null;
                    this.Value = null;
                }
                else
                {
                    this.PART_Calendar.SelectedDate = DateTime.Parse(datetime);
                }
            }
        }

19 View Source File : UnitOfWorkTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task Commit_ShouldSaveChanges()
        {
            var instructor = new Instructor { FirstMidName = "Kim", LastName = "Abercrombie", HireDate = DateTime.Parse("1995-03-11") };
            _sut.InstructorRepository.Add(instructor);

            _sut.Commit();

            var result = await _sut.InstructorRepository.GetByLastName("Abercrombie").ToListAsync();
            replacedert.Equal(instructor.LastName, result[0].LastName);
        }

19 View Source File : AiurUrl.Tests.cs
License : MIT License
Project Creator : AiursoftWeb

[TestMethod]
        public void TestLocalhost()
        {
            var url = new AiurUrl("https://www.bing.com", "Home", "Search", new TestAddressModel
            {
                Question = "MyQuestion",
                Count = 10,
                Email = "[email protected]",
                MyNull = null,
                CreateTime = DateTime.Parse("2020-01-01 14:15:16")
            });
            replacedert.IsFalse(url.IsLocalhost());
            url.Address = "https://127.0.0.1";
            replacedert.IsTrue(url.IsLocalhost());
        }

19 View Source File : StudentsControllerTests.cs
License : MIT License
Project Creator : alimon808

[Fact]
        public async Task CreatePost_ReturnsAViewResult_WithInvalidModel()
        {
            var student = new Student { ID = 9, FirstMidName = "John", LastName = "Wick", EnrollmentDate = DateTime.Parse("2005-09-01") };
            sut.ModelState.AddModelError("myerror", "my error message");

            var result = await sut.Create(student);

            replacedert.IsType<ViewResult>(result);

            var model = (Student)((ViewResult)result).Model;
            replacedert.Equal("Wick", model.LastName);
        }

19 View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344

public void Add(DateTime datetime)
        {
            var value = (uint) (datetime - DateTime.Parse("1970-1-1").ToLocalTime()).TotalSeconds;
            var bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            _stream.Write(bytes, 0, bytes.Length);
        }

19 View Source File : ParquetCsvComparison.cs
License : MIT License
Project Creator : aloneguid

private object ChangeType(object v, Type t)
      {
         if (v == null) return null;
         if (v.GetType() == t) return v;
         if (v is string s && string.IsNullOrEmpty(s)) return null;

         if(t == typeof(DateTimeOffset))
         {
            string so = (string)v;
            return new DateTimeOffset(DateTime.Parse(so));
         }

         if (t == typeof(byte[]))
         {
            string so = (string) v;
            return Encoding.UTF8.GetBytes(so);
         }

         return Convert.ChangeType(v, t);
      }

19 View Source File : Startup.cs
License : MIT License
Project Creator : alanmacgowan

private void InitializeDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var appDbContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                appDbContext.Database.EnsureCreated();

                var grantDbContext = serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>();
                grantDbContext.Database.EnsureCreated();

                var configDbContext = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                var configDbCreator = (RelationalDatabaseCreator)configDbContext.Database.GetService<IDatabaseCreator>();

                try
                {
                    configDbCreator.CreateTables();
                }
                catch
                {

                }

                if (!configDbContext.Clients.Any())
                {
                    foreach (var client in Config.GetClients())
                    {
                        configDbContext.Clients.Add(client.ToEnreplacedy());
                    }
                    configDbContext.SaveChanges();
                }

                if (!configDbContext.IdenreplacedyResources.Any())
                {
                    foreach (var resource in Config.GetIdenreplacedyResources())
                    {
                        configDbContext.IdenreplacedyResources.Add(resource.ToEnreplacedy());
                    }
                    configDbContext.SaveChanges();
                }

                if (!configDbContext.ApiResources.Any())
                {
                    foreach (var resource in Config.GetApiResources())
                    {
                        configDbContext.ApiResources.Add(resource.ToEnreplacedy());
                    }
                    configDbContext.SaveChanges();
                }

                if (!appDbContext.Books.Any())
                {
                    var books = new Book[]
{
                    new Book{replacedle="Book 1",Description = "This is Book number 1",PublishDate=DateTime.Parse("2005-09-01"), ISBN = "1289189218291", Category = "Comedy", Price = 44, Pages = 111,Language="Spanish"  },
                    new Book{replacedle="Book 2",Description = "This is Book number 2",PublishDate=DateTime.Parse("2017-05-04"), ISBN = "2222222222622", Category = "Drama", Price = 33, Pages = 222,Language="English" },
                    new Book{replacedle="Book 3",Description = "This is Book number 3",PublishDate=DateTime.Parse("2017-04-03"), ISBN = "3232323222533", Category = "Travel", Price = 23, Pages = 223,Language="Spanish" },
                    new Book{replacedle="Book 4",Description = "This is Book number 4",PublishDate=DateTime.Parse("2016-12-12"), ISBN = "7676676767676", Category = "History", Price = 233, Pages = 422,Language="Portuguese" },
                    new Book{replacedle="Book 5",Description = "This is Book number 5",PublishDate=DateTime.Parse("2015-11-12"), ISBN = "4545454555555", Category = "Comedy", Price = 37, Pages = 123,Language="Spanish" },
};
                    foreach (Book s in books)
                    {
                        appDbContext.Books.Add(s);
                    }
                    appDbContext.SaveChanges();
                }
            }
        }

19 View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime GetDateArg(string name, DateTime def)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
            {
                return def;
            }
            return DateTime.Parse(value);
        }

19 View Source File : DateTimeObjectType.cs
License : MIT License
Project Creator : 404Lcc

public object Draw(Type memberType, string memberName, object value, object target)
        {
            string oldData = value.ToString();
            string newData = EditorGUILayout.TextField(memberName, oldData);
            return newData != oldData ? DateTime.Parse(newData) : value;
        }

19 View Source File : PostgresJobRepository_UpdateStatusAsync_Test.cs
License : MIT License
Project Creator : AdemCatamak

[Fact]
        public async Task When_UpdateAsyncExecuted__Status_LastOperationInfo_LastOperationTime_ShouldBeChanged()
        {
            var jobId = Guid.NewGuid();
            DateTime lastOperationTime = DateTime.Parse("2021-01-01");
            const string lastOperationInfo = "last-operation-info";

            Job job = new Job(jobId, new Message("some-payload"), "some-handler", JobStatus.Queued, DateTime.UtcNow, lastOperationTime, lastOperationInfo, 5, DateTime.UtcNow);
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            await jobRepository.AddAsync(job);

            job.SetCompleted();
            await jobRepository.UpdateJobStatusAsync(job);

            await using var connection = new NpgsqlConnection(_postgresInfraFixture.ConnectionString);
            string jobCountScript = $"select * from {SCHEMA}.jobs where id = @id";
            var jobFromDb = await connection.QueryFirstAsync(jobCountScript, param: new {id = job.Id});

            replacedert.Equal(jobId, jobFromDb.id);
            replacedert.Equal((int) JobStatus.Completed, jobFromDb.job_status);
            replacedert.Equal(JobStatus.Completed.ToString(), jobFromDb.last_operation_info);
            replacedertThat.GreaterThan(lastOperationTime, (DateTime) jobFromDb.last_operation_time);
        }

19 View Source File : PortalCacheInvalidatorThread.cs
License : MIT License
Project Creator : Adoxio

private void LogTimeTelemetry(DateTime pushedToCache, Dictionary<string, EnreplacedyRecordMessage> processingRecords, TimeBasedChangedData crmQueryResults, Dictionary<string, string> timeStampTable)
		{
			var filteredProcessingRecords = processingRecords.Where(item => item.Value.MessageType == MessageType.Create || item.Value.MessageType == MessageType.Update);
			var filteredCrmQueryResults = crmQueryResults.UpdatedEnreplacedyRecords.OfType<Microsoft.Xrm.Sdk.NewOrUpdatedItem>()
				// Only add telemetry for non-initial load enreplacedies (timestamp already has been recorded.
				// This will avoid awful timespan values being captured on initial startup
				.Where(filteredResult => timeStampTable.ContainsKey(filteredResult.NewOrUpdatedEnreplacedy.LogicalName)
					// Timestamp table stores string dataTokens from CRM in the form of 123456!04/04/2004 04:04:04.04
					? filteredResult.NewOrUpdatedEnreplacedy.GetAttributeValue<DateTime>("modifiedon") > DateTime.Parse(timeStampTable[filteredResult.NewOrUpdatedEnreplacedy.LogicalName].Split('!')[1])
					: false);

			IEnumerable<TimeTrackingEntry> entries = filteredProcessingRecords.Join(
				// With list
				filteredCrmQueryResults,
				// Keys
				processingRecord => processingRecord.Key,
				crmQueryResult => crmQueryResult.NewOrUpdatedEnreplacedy.LogicalName,
				// How to join
				(processingRecord, crmqueryResult) => new TimeTrackingEntry(
					processingRecord.Key, pushedToCache,
					crmqueryResult.NewOrUpdatedEnreplacedy.GetAttributeValue<DateTime>("modifiedon"),
					processingRecord.Value.Received));

			entries.ToList().ForEach(traceEntry =>
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application,
					string.Format("Overall the '{0}' change took {1} to propagate\n\tMessage to reach portal through Azure: {2}\n\tSleep and Retreival of change from CRM: {3}",
					traceEntry.EnreplacedyLogicalName,
					traceEntry.OverallDelta,
					traceEntry.AzureProcessingDelta,
					traceEntry.InvalidationDelta));
			});
		}

19 View Source File : ApiControlerEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected DateTime? GetDateArg(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null") return null;
            return DateTime.Parse(value);
        }

19 View Source File : VWAP.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Load()
        {
            if (!File.Exists(@"Engine\" + Name + @".txt"))
            {
                return;
            }
            try
            {
                using (StreamReader reader = new StreamReader(@"Engine\" + Name + @".txt"))
                {
                    UseDate = Convert.ToBoolean(reader.ReadLine());
                    DatePickerStart = DateTime.Parse(reader.ReadLine());
                    TimePickerStart = DateTime.Parse(reader.ReadLine());
                    ToEndTicks = Convert.ToBoolean(reader.ReadLine());
                    DatePickerEnd = DateTime.Parse(reader.ReadLine());
                    TimePickerEnd = DateTime.Parse(reader.ReadLine());

                    DateDev2 = Convert.ToBoolean(reader.ReadLine());
                    DateDev3 = Convert.ToBoolean(reader.ReadLine());
                    DateDev4 = Convert.ToBoolean(reader.ReadLine());

                    ColorDate = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDateDev = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    UseDay = Convert.ToBoolean(reader.ReadLine());

                    DayDev2 = Convert.ToBoolean(reader.ReadLine());
                    DayDev3 = Convert.ToBoolean(reader.ReadLine());
                    DayDev4 = Convert.ToBoolean(reader.ReadLine());

                    ColorDay = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorDayDev = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    UseWeekly = Convert.ToBoolean(reader.ReadLine());

                    WeekDev2 = Convert.ToBoolean(reader.ReadLine());
                    WeekDev3 = Convert.ToBoolean(reader.ReadLine());
                    WeekDev4 = Convert.ToBoolean(reader.ReadLine());

                    ColorWeek = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));
                    ColorWeekDev = Color.FromArgb(Convert.ToInt32(reader.ReadLine()));

                    PaintOn = Convert.ToBoolean(reader.ReadLine());
                    reader.Close();
                }
            }
            catch (Exception)
            {
                // отправить в лог
            }
        }

See More Examples