System.DateTime.AddDays(double)

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

3989 Examples 7

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static IEnumerable<DateTime> GetDates(this OrganizationServiceContext context, Enreplacedy eventSchedule, DateTime date)
		{
			return GetDates(context, eventSchedule, date, date.AddDays(1));
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static IEnumerable<DateTime> GetDates(this OrganizationServiceContext context, Enreplacedy eventSchedule, DateTime firstDate, DateTime lastDate)
		{
			eventSchedule.replacedertEnreplacedyName("adx_eventschedule");

			var interval = eventSchedule.GetAttributeValue<int?>("adx_interval");
			var recurrenceOption = eventSchedule.GetAttributeValue<OptionSetValue>("adx_recurrence");
			var recurrence = recurrenceOption == null ? null : (int?)recurrenceOption.Value;
			var startTime = eventSchedule.GetAttributeValue<DateTime?>("adx_starttime");
			var endTime = eventSchedule.GetAttributeValue<DateTime?>("adx_endtime");
			var maxRecurrences = eventSchedule.GetAttributeValue<int?>("adx_maxrecurrences");
			var weekOption = eventSchedule.GetAttributeValue<OptionSetValue>("adx_week");
			var week = weekOption == null ? null : (int?)weekOption.Value;
			var recurrenceEndDate = eventSchedule.GetAttributeValue<DateTime?>("adx_recurrenceenddate");

			var scheduledDates = new List<DateTime>();
			var intervalValue = interval.HasValue ? interval.Value : 1;

			if (recurrence == 1 /*"Nonrecurring"*/)
			{
				// this is a nonrecurring event.  We only need to add the current date
				if (endTime >= firstDate && startTime < lastDate)
				{
					scheduledDates.Add(startTime.Value);
				}
			}
			else if (recurrence == 2 /*"Daily"*/)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					// check if the time for this event is between now and the maximum timespan
					if (d >= firstDate && d < lastDate)
					{
						var sunday = eventSchedule.GetAttributeValue<bool?>("adx_sunday");
						var monday = eventSchedule.GetAttributeValue<bool?>("adx_monday");
						var tuesday = eventSchedule.GetAttributeValue<bool?>("adx_tuesday");
						var wednesday = eventSchedule.GetAttributeValue<bool?>("adx_wednesday");
						var thursday = eventSchedule.GetAttributeValue<bool?>("adx_thursday");
						var friday = eventSchedule.GetAttributeValue<bool?>("adx_friday");
						var saturday = eventSchedule.GetAttributeValue<bool?>("adx_saturday");

						// this is in our date window.  Check if there are restrictions on the days
						if (
							(d.DayOfWeek == DayOfWeek.Sunday && (sunday != null && sunday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Monday && (monday != null && monday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Tuesday && (tuesday != null && tuesday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Wednesday && (wednesday != null && wednesday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Thursday && (thursday != null && thursday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Friday && (friday != null && friday.Value)) ||
							(d.DayOfWeek == DayOfWeek.Saturday && (saturday != null && saturday.Value)))
						{
							scheduledDates.Add(d);
						}
					}

					// move to the next event
					d = d.AddDays(intervalValue);

					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}
			else if (recurrence == 3 /*"Weekly"*/)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					// check if the time for this event is between now and the maximum timespan
					if (d >= firstDate && d < lastDate)
					{
						// this is in our date window. 
						scheduledDates.Add(d);
					}

					// move to the next event
					d = d.AddDays(intervalValue * 7);

					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}
			else if (recurrence == 4 /*"Monthly"*/ && week == null)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					// check if the time for this event is between now and the maximum timespan
					if (d >= firstDate && d < lastDate)
					{
						// this is in our date window. 
						scheduledDates.Add(d);
					}

					// move to the next event
					d = d.AddMonths(intervalValue);

					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}
			else if (recurrence == 4 /*"Monthly"*/ && week != null)
			{
				DateTime d = startTime.Value;
				var done = false;
				var counter = 0;

				while (!done)
				{
					var d2 = new DateTime(d.Year, d.Month, 1, d.Hour, d.Minute, d.Second);
					if (week == 2 /*"Second"*/)
					{
						d2 = d2.AddDays(7);
					}
					else if (week == 3 /*"Third"*/)
					{
						d2 = d2.AddDays(14);
					}
					else if (week == 4 /*"Fourth"*/)
					{
						d2 = d2.AddDays(21);
					}
					else if (week == 5 /*"Last"*/)
					{
						d2 = d2.AddMonths(1);
						d2 = d2.AddDays(-7);
					}

					// move forward to the first scheduled day that matches the original day
					while (d2.DayOfWeek != startTime.Value.DayOfWeek)
					{
						d2 = d2.AddDays(1);
					}

					// check if the time for this event is between now and the maximum timespan
					if (d2 >= firstDate && d2 < lastDate)
					{
						// this is in our date window. 
						scheduledDates.Add(d2);
					}

					// move to the next event
					d = d.AddMonths(intervalValue);

					// check if we are done, but be careful that we might have to check another iteration if the date is
					// a little past the specified date and the setting is set to use the 'last' week of the month. It is safe to 
					// check an extra week past our final date.
					if ((maxRecurrences.HasValue ? counter++ >= maxRecurrences : false) || d > lastDate.AddDays(7) || d > recurrenceEndDate)
					{
						done = true;
					}
				}
			}

			var eventScheduleExceptions = eventSchedule.GetRelatedEnreplacedies(context, "adx_eventschedule_eventscheduleexception");

			foreach (var scheduleException in eventScheduleExceptions)
			{
				var scheduledTime = scheduleException.GetAttributeValue<DateTime?>("adx_scheduledtime");

				// check if this scheduled date was in the list of dates we calculated, and remove it if it is
				if (scheduledDates.Contains(scheduledTime.Value))
				{
					scheduledDates.Remove(scheduledTime.Value);
				}

				var rebookingTime = scheduleException.GetAttributeValue<DateTime?>("adx_rebookingtime");

				// check if this rescheduled date fits within our time window
				if (rebookingTime.HasValue && rebookingTime.Value >= firstDate && rebookingTime.Value < lastDate)
				{
					scheduledDates.Add(rebookingTime.Value);
				}
			}

			return scheduledDates;
		}

19 Source : IdeaForumDataAdapterFactory.cs
with MIT License
from Adoxio

public IIdeaForumDataAdapter CreateIdeaForumDataAdapter(Enreplacedy ideaForum, string filter, string timeSpan, int? status = 1)
		{
			IIdeaForumDataAdapter ideaForumDataAdapter = null;

			if (string.Equals(filter, "new", StringComparison.InvariantCultureIgnoreCase))
			{
				ideaForumDataAdapter = new IdeaForumByNewDataAdapter(ideaForum);
			}
			else
			{
				ideaForumDataAdapter = this.IsIdeasPreRollup()
					? this.CreateIdeaDataAdapterPreRollup(ideaForum, filter)
					: this.CreateIdeaDataAdapter(ideaForum, filter);
			}

			ideaForumDataAdapter.MinDate = timeSpan == "this-year" ? DateTime.UtcNow.AddYears(-1).Date
				: timeSpan == "this-month" ? DateTime.UtcNow.AddMonths(-1).Date
				: timeSpan == "this-week" ? DateTime.UtcNow.AddDays(-7).Date
				: timeSpan == "today" ? DateTime.UtcNow.AddHours(-24)
				: (DateTime?)null;

			ideaForumDataAdapter.Status = status != (int?)IdeaStatus.Any ? status : null;

			return ideaForumDataAdapter;
		}

19 Source : WebResourceHandler.cs
with MIT License
from Adoxio

protected virtual void SetResponseParameters(HttpContext context, Enreplacedy webResource)
		{
			context.Response.StatusCode = (int)HttpStatusCode.OK;
			context.Response.ContentType = GetMimeType(webResource);
			context.Response.Cache.SetExpires(DateTime.Now.AddDays(30));
			context.Response.Cache.SetCacheability(HttpCacheability.Public);
			context.Response.Cache.SetLastModified(DateTime.Now);
		}

19 Source : DateFilters.cs
with MIT License
from Adoxio

public static DateTime? DateAddDays(DateTime? date, double value)
		{
			return date.HasValue
				? date.Value.AddDays(value)
				: (DateTime?)null;
		}

19 Source : NoCacheAttribute.cs
with MIT License
from Adoxio

public override void OnResultExecuting(ResultExecutingContext filterContext)
		{
			filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
			filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
			filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
			filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
			filterContext.HttpContext.Response.Cache.SetNoStore();

			base.OnResultExecuting(filterContext);
		}

19 Source : DateTimeExtensions.cs
with MIT License
from Adoxio

public static DateTime Round(this DateTime d, RoundTo to)
		{
			var floor = Floor(d, to);
			if (to == RoundTo.Second && d.Millisecond >= 500) return floor.AddSeconds(1);
			if (to == RoundTo.Minute && d.Second >= 30) return floor.AddMinutes(1);
			if (to == RoundTo.Hour && d.Minute >= 30) return floor.AddHours(1);
			if (to == RoundTo.Day && d.Hour >= 12) return floor.AddDays(1);
			if (to == RoundTo.Month && d.Day >= DateTime.DaysInMonth(d.Year, d.Month) / 2) return floor.AddMonths(1);
			return d;
		}

19 Source : JobPostingsFeedHandler.cs
with MIT License
from Adoxio

private static bool IsOpen(DateTime? closingOn)
		{
			return closingOn == null || closingOn.Value.AddDays(1).Date >= DateTime.UtcNow;
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static Enum GetAlertType(this OrganizationServiceContext context, Guid? id, Enreplacedy website)
		{
			if (id == null)
			{
				return Enums.AlertType.None;
			}

			var opportunity = context.CreateQuery("opportunity").First(opp => opp.GetAttributeValue<Guid>("opportunityid") == id);

			if (opportunity.GetAttributeValue<OptionSetValue>("statecode") != null && opportunity.GetAttributeValue<OptionSetValue>("statecode").Value != (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Open)
			{
				return Enums.AlertType.None;
			}

			if (opportunity.GetAttributeValue<OptionSetValue>("statuscode") != null && opportunity.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered)
			{
				return Enums.AlertType.New;
			}

			var opportunityLatestStatusModifiedOn = context.GetOpportunityLatestStatusModifiedOn(opportunity);

			return opportunityLatestStatusModifiedOn == null
					   ? Enums.AlertType.None
					   : opportunityLatestStatusModifiedOn <= DateTime.Now.AddDays(-context.GetInactiveDaysUntilPotentiallyStalled(website))
							 ? Enums.AlertType.PotentiallyStalled
							 : (opportunityLatestStatusModifiedOn <= DateTime.Now.AddDays(-context.GetInactiveDaysUntilOverdue(website))
									? Enums.AlertType.Overdue
									: Enums.AlertType.None);
		}

19 Source : Home.aspx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			//RedirectToLoginIfNecessary();

			var contact = Contact;

			if (contact != null)
			{
				var homeAlertsSavedQuery = XrmContext.CreateQuery("savedquery").FirstOrDefault(query => query.GetAttributeValue<OptionSetValue>("statecode") != null && query.GetAttributeValue<OptionSetValue>("statecode").Value == 0 && query.GetAttributeValue<string>("name") == HomeAlertsSavedQueryName);

				var alerts = Opportunities.Where(opp => (opp.GetAttributeValue<OptionSetValue>("statuscode") != null && opp.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered)
					|| XrmContext.GetOpportunityLatestStatusModifiedOn(opp) <= DateTime.Now.AddDays(-ServiceContext.GetInactiveDaysUntilOverdue(Website)))
					.OrderByDescending(opp => GetAlertType(opp.Id)).ThenBy(opp => opp.GetRelatedEnreplacedy(XrmContext, new Relationship("opportunity_customer_accounts")).GetAttributeValue<string>("name"));
				
				var columnsGenerator = new SavedQueryColumnsGenerator(XrmContext, homeAlertsSavedQuery);

				Alerts.DataKeyNames = new[] { "opportunityid" };
				Alerts.DataSource = columnsGenerator.ToDataTable(alerts);
				Alerts.ColumnsGenerator = columnsGenerator;
				Alerts.DataBind();

				var newOpportunities = Opportunities.Where(opp => opp.GetAttributeValue<OptionSetValue>("statuscode") != null && opp.GetAttributeValue<OptionSetValue>("statuscode").Value == 
					(int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered);

				NewOpportunityCount.Text = newOpportunities.Count().ToString();
				NewOpportunityValue.Text = newOpportunities.Where(o => o.GetAttributeValue<Money>("estimatedvalue") != null).Sum(opp => opp.GetAttributeValue<Money>("estimatedvalue").Value).ToString("C");

				var acceptedOpportunities = Opportunities.Where(opp => opp.GetAttributeValue<OptionSetValue>("statuscode") != null && opp.GetAttributeValue<OptionSetValue>("statuscode").Value !=
					(int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered);

				AcceptedOpportunityCount.Text = acceptedOpportunities.Count().ToString();
				AcceptedOpportunityValue.Text = acceptedOpportunities.Where(o => o.GetAttributeValue<Money>("estimatedvalue") != null).Sum(opp => opp.GetAttributeValue<Money>("estimatedvalue").Value).ToString("C");
			}
			else
			{
				PartnerHomePanel.Visible = false;
			}
		}

19 Source : ScheduleService.aspx.cs
with MIT License
from Adoxio

private void BindTimeDropDowns()
		{
			for (var t = DateTime.MinValue; t < DateTime.MinValue.AddDays(1); t = t.AddMinutes(30))
			{
				StartTime.Items.Add(new Lisreplacedem(t.ToString("h:mm tt"), t.Subtract(DateTime.MinValue).TotalMinutes.ToString(CultureInfo.InvariantCulture)));
				EndTime.Items.Add(new Lisreplacedem(t.ToString("h:mm tt"), t.Subtract(DateTime.MinValue).TotalMinutes.ToString(CultureInfo.InvariantCulture)));
			}

			StartTime.Text = "540"; // 9 AM
			EndTime.Text = "1020"; // 5 PM
		}

19 Source : MapController.cs
with MIT License
from Adoxio

public static IQueryable<Enreplacedy> FilterAlertsByDate(this IQueryable<Enreplacedy> query, int dateFilterCode, DateTime dateFrom, DateTime dateTo)
		{
			switch (dateFilterCode)
			{
				case 0: // filter last 7 days
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddDays(-7));
				case 1: // filter last 30 days
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddDays(-30));
				case 2: // filter last 12 months
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() > DateTime.Now.AddMonths(-12));
				case 3: // filter by date range
					return query.Where(a => a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() >= dateFrom && a.GetAttributeValue<DateTime?>("adx_scheduledstartdate").GetValueOrDefault() <= dateTo);
				default:
					return query;
			}
		}

19 Source : MapController.cs
with MIT License
from Adoxio

[AcceptVerbs(HttpVerbs.Post)]
		[AjaxValidateAntiForgeryToken, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "Handled with the custom attribute AjaxValidateAntiForgeryToken")]
		public ActionResult Search(int dateFilterCode, string dateFrom, string dateTo, int statusFilterCode, int priorityFilterCode, string[] types, bool includeAlerts)
		{
			dateFilterCode = (dateFilterCode >= 0) ? dateFilterCode : 0;
			var status = (statusFilterCode > 0) ? statusFilterCode : 999;
			var priority = (priorityFilterCode >= 0) ? priorityFilterCode : 0;
			DateTime fromDate;
			DateTime.TryParse(dateFrom, out fromDate);
			DateTime toDate;
			DateTime.TryParse(dateTo, out toDate);
			var typesGuids = types == null || types.Length < 1 ? null : Array.ConvertAll(types, Guid.Parse);
			var context = PortalCrmConfigurationManager.CreateServiceContext();

			var serviceRequests = context.CreateQuery("adx_servicerequest").Where(s => s.GetAttributeValue<decimal?>("adx_lareplacedude") != null && s.GetAttributeValue<decimal?>("adx_longitude") != null)
				.FilterServiceRequestsByPriority(priority)
				.FilterServiceRequestsByStatus(status)
				.FilterServiceRequestsByDate(dateFilterCode, fromDate, toDate.AddDays(1))
				.FilterServiceRequestsByType(typesGuids)
				.ToList();

			var serviceRequestMapNodes = new List<MapNode>();

			if (serviceRequests.Any())
			{
				serviceRequestMapNodes =
					serviceRequests.Select(
						s =>
							new MapNode(
								MapNode.NodeType.ServiceRequest,
								s.GetAttributeValue<string>("adx_servicerequestnumber"),
								s.GetAttributeValue<string>("adx_name"),
								s.GetAttributeValue<string>("adx_location"),
								string.Empty,
								s.GetAttributeValue<OptionSetValue>("adx_servicestatus") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_servicestatus").Value,
								s.GetAttributeValue<OptionSetValue>("adx_priority") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_priority").Value,
								s.GetAttributeValue<DateTime>("adx_incidentdate"),
								s.GetAttributeValue<DateTime>("adx_scheduleddate"),
								s.GetAttributeValue<DateTime>("adx_closeddate"),
								s.GetAttributeValue<decimal?>("adx_lareplacedude").GetValueOrDefault(0),
								s.GetAttributeValue<decimal?>("adx_longitude").GetValueOrDefault(0),
								ServiceRequestHelpers.GetPushpinImageUrl(context, s),
								ServiceRequestHelpers.GetCheckStatusUrl(s))).ToList();
			}

			var alertMapNodes = new List<MapNode>();

			if (includeAlerts)
			{
				var alerts = context.CreateQuery("adx_311alert").Where(a =>
					a.GetAttributeValue<decimal?>("adx_lareplacedude") != null && a.GetAttributeValue<decimal?>("adx_longitude") != null && a.GetAttributeValue<bool?>("adx_publishtoweb").GetValueOrDefault(false) == true)
					.FilterAlertsByDate(dateFilterCode, fromDate, toDate.AddDays(1)).ToList();

				if (alerts.Any())
				{
					var alertIconImageUrl = ServiceRequestHelpers.GetAlertPushpinImageUrl();
					alertMapNodes = alerts.Select(a => new MapNode(MapNode.NodeType.Alert, a.GetAttributeValue<string>("adx_name"), a.GetAttributeValue<string>("adx_address1_line1"), a.GetAttributeValue<string>("adx_description"), a.GetAttributeValue<DateTime?>("adx_scheduledstartdate"), a.GetAttributeValue<DateTime?>("adx_scheduledenddate"), a.GetAttributeValue<decimal?>("adx_lareplacedude") ?? 0, a.GetAttributeValue<decimal?>("adx_longitude") ?? 0, alertIconImageUrl)).ToList();
				}
			}

			var mapNodes = serviceRequestMapNodes.Union(alertMapNodes).ToList();

			var json = Json(mapNodes);

			return json;
		}

19 Source : MapController.cs
with MIT License
from Adoxio

public static IQueryable<Enreplacedy> FilterServiceRequestsByDate(this IQueryable<Enreplacedy> query, int dateFilterCode, DateTime dateFrom, DateTime dateTo)
		{
			switch (dateFilterCode)
			{
				case 0: // filter last 7 days
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddDays(-7));
				case 1: // filter last 30 days
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddDays(-30));
				case 2: // filter last 12 months
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() > DateTime.Now.AddMonths(-12));
				case 3: // filter by date range
					return query.Where(s => s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() >= dateFrom && s.GetAttributeValue<DateTime?>("adx_incidentdate").GetValueOrDefault() <= dateTo);
				default:
					return query;
			}
		}

19 Source : ScheduleService.aspx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			RedirectToLoginIfAnonymous();

			if (IsPostBack)
			{
				return;
			}

			StartDate.SelectedDate = DateTime.Today;
			EndDate.SelectedDate = DateTime.Today.AddDays(7);

			var services = XrmContext.CreateQuery("service").Where(s => s.GetAttributeValue<bool?>("isschedulable").GetValueOrDefault(false) && s.GetAttributeValue<string>("description").Contains("*WEB*")).ToList();

			if (!services.Any())
			{
				SearchPanel.Visible = false;
				NoServicesMessage.Visible = true;

				return;
			}

			BindServicesDropDown(services);
			BindTimeZoneDropDown();
			BindTimeDropDowns();
		}

19 Source : AduDatePicker.cs
with GNU General Public License v3.0
from aduskin

private void PART_Btn_Yestday_Click(object sender, RoutedEventArgs e)
      {
         this.SetSelectedDate(DateTime.Today.AddDays(-1));
      }

19 Source : AduDatePicker.cs
with GNU General Public License v3.0
from aduskin

private void PART_Btn_AnWeekAgo_Click(object sender, RoutedEventArgs e)
      {
         this.SelectedDates.Clear();
         this.PART_Calendar.SelectedDates.Clear();
         this.PART_Calendar_Second.SelectedDates.Clear();
         this.SelectedDateStart = null;
         this.SelectedDateEnd = null;
         this.PART_Calendar.SelectedDate = null;
         this.PART_Calendar_Second.SelectedDate = null;
         this.SetSelectedDate(DateTime.Today.AddDays(-7));
      }

19 Source : AduDatePicker.cs
with GNU General Public License v3.0
from aduskin

private void PART_Btn_RecentlyAWeek_Click(object sender, RoutedEventArgs e)
      {
         this.ClearSelectedDates();
         this.FastSetSelectedDates(DateTime.Today.AddDays(-7), DateTime.Today);
      }

19 Source : AduDatePicker.cs
with GNU General Public License v3.0
from aduskin

private void SetSelectedDates(DateTime? selectedDateStart, DateTime? selectedDateEnd)
      {
         this.SelectedDates.Clear();
         DateTime? dtTemp = selectedDateStart;
         while (dtTemp <= selectedDateEnd)
         {
            this.SelectedDates.Add(dtTemp.Value);
            dtTemp = dtTemp.Value.AddDays(1);
         }
         this.HandleSelectedDatesChanged();

         if (this.PART_TextBox_New != null && selectedDateStart.HasValue && selectedDateEnd.HasValue)
         {
            this.SetRangeDateToTextBox(selectedDateStart, selectedDateEnd);
         }
      }

19 Source : Util.cs
with MIT License
from Adyen

public static string CalculateSessionValidity()
        {
            //+1day
           var dateTime=DateTime.Now.AddDays(1);
           return String.Format("{0:s}", dateTime);
           
        }

19 Source : ConfigurationContractTestBase.cs
with MIT License
from AElfProject

protected async Task<Hash> CreateProposalAsync(ContractTester<ConfigurationContractTestAElfModule> tester,
            Address contractAddress, Address organizationAddress, string methodName, IMessage input)
        {
            var configContract = tester.GetContractAddress(HashHelper.ComputeFrom("AElf.ContractNames.Configuration"));
            var proposal = await tester.ExecuteContractWithMiningAsync(contractAddress,
                nameof(AuthorizationContractContainer.AuthorizationContractStub.CreateProposal),
                new CreateProposalInput
                {
                    ContractMethodName = methodName,
                    ExpiredTime = DateTime.UtcNow.AddDays(1).ToTimestamp(),
                    Params = input.ToByteString(),
                    ToAddress = configContract,
                    OrganizationAddress = organizationAddress
                });
            var proposalId = Hash.Parser.ParseFrom(proposal.ReturnValue);
            return proposalId;
        }

19 Source : GenesisContractTestBase.cs
with MIT License
from AElfProject

protected async Task<Hash> CreateProposalAsync(ContractTester<BasicContractZeroTestAElfModule> tester,
            Address contractAddress, Address organizationAddress, string methodName, IMessage input)
        {
            var basicContract = tester.GetZeroContractAddress();
            // var organizationAddress = await GetGenesisAddressAsync(tester, parliamentContractAddress);
            var proposal = await tester.ExecuteContractWithMiningAsync(contractAddress,
                nameof(AuthorizationContractContainer.AuthorizationContractStub.CreateProposal),
                new CreateProposalInput
                {
                    ContractMethodName = methodName,
                    ExpiredTime = DateTime.UtcNow.AddDays(1).ToTimestamp(),
                    Params = input.ToByteString(),
                    ToAddress = basicContract,
                    OrganizationAddress = organizationAddress
                });
            var proposalId = Hash.Parser.ParseFrom(proposal.ReturnValue);
            return proposalId;
        }

19 Source : ParliamentContractTestBase.cs
with MIT License
from AElfProject

internal CreateProposalInput CreateProposalInput(IMessage input, Address organizationAddress)
        {
            var createProposalInput = new CreateProposalInput
            {
                ContractMethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Transfer),
                ExpiredTime = DateTime.UtcNow.AddDays(1).ToTimestamp(),
                Params = input.ToByteString(),
                ToAddress = TokenContractAddress,
                OrganizationAddress = organizationAddress
            };
            return createProposalInput;
        }

19 Source : ParliamentContractTestBase.cs
with MIT License
from AElfProject

internal CreateProposalInput CreateParliamentProposalInput(IMessage input, Address organizationAddress)
        {
            var createProposalInput = new CreateProposalInput
            {
                ContractMethodName = nameof(ParliamentContractImplContainer.ParliamentContractImplStub.ChangeOrganizationProposerWhiteList),
                ToAddress = ParliamentAddress,
                Params = input.ToByteString(),
                ExpiredTime =  DateTime.UtcNow.AddDays(1).ToTimestamp(),
                OrganizationAddress = organizationAddress
            };
            return createProposalInput;
        }

19 Source : CalendarController.cs
with MIT License
from ahmetozlu

void CreateCalendar()
    {
        DateTime firstDay = _dateTime.AddDays(-(_dateTime.Day - 1));
        int index = GetDays(firstDay.DayOfWeek);

        int date = 0;
        for (int i = 0; i < _totalDateNum; i++)
        {
            Text label = _dateItems[i].GetComponentInChildren<Text>();
            _dateItems[i].SetActive(false);

            if (i >= index)
            {
                DateTime thatDay = firstDay.AddDays(date);
                if (thatDay.Month == firstDay.Month)
                {
                    _dateItems[i].SetActive(true);

                    label.text = (date + 1).ToString();
                    date++;
                }
            }
        }
        _yearNumText.text = _dateTime.Year.ToString();
        _monthNumText.text = _dateTime.Month.ToString();
    }

19 Source : RequireBoostingAttribute.cs
with MIT License
from Aiko-IT-Systems

public override async Task<bool> ExecuteCheckAsync(CommandContext ctx, bool help)
        {
            if (this.GuildId != 0)
            {
                var guild = await ctx.Client.GetGuildAsync(this.GuildId);
                var member = await guild.GetMemberAsync(ctx.User.Id);
                return member != null && member.PremiumSince.HasValue ? await Task.FromResult(member.PremiumSince.Value.UtcDateTime.Date < DateTime.UtcNow.Date.AddDays(-this.Since)) : await Task.FromResult(false);
            }
            else
            {
                return ctx.Member != null && ctx.Member.PremiumSince.HasValue ? await Task.FromResult(ctx.Member.PremiumSince.Value.UtcDateTime.Date < DateTime.UtcNow.Date.AddDays(-this.Since)): await Task.FromResult(false);
            }
        }

19 Source : SerialNumber.cs
with GNU General Public License v3.0
from aiportal

public static SerialNumber DeSerialize(string str)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(str))
			{
				string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
				if (ss.Length > 3)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						License = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3]
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = Global.Config.InstallTime;
					sn.ExpireTime = Global.Config.InstallTime.Add(span);
				}
			}
			return sn;
		}

19 Source : SerialNumber.cs
with GNU General Public License v3.0
from aiportal

public static SerialNumber DeSerialize(string str, DateTime installTime)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(str))
			{
				string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
				if (ss.Length > 3)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						License = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3]
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = installTime;
					sn.ExpireTime = installTime.Add(span);
				}
			}
			return sn;
		}

19 Source : StorageEngine.cs
with GNU General Public License v3.0
from aiportal

public static void ScanAndRestrictLocalStore(object state)
		{
			if (Global.Config.DiskQuota > 0 || Global.Config.DaysLimit > 0)
			{
				var sessions = Database.Invoke(db => db.SelectObjects<SessionInfo>("SessionView", null, "IsEnd, LastActiveTime DESC", 0,
					"SessionId", "IsEnd", "LastActiveTime", "DataLength"));

				if (Global.Config.DiskQuota > 0)
				{
					long total = 0;
					long capacity = Global.Config.DiskQuota * 1024 * 1024 * 1024;
					foreach (var s in sessions)
					{
						if (!s.IsEnd)
							total += s.DataLength;
						else if (total < capacity)
							total += s.DataLength;
						else
							TryRemoveSessionData(s.SessionId.Replace("-", ""));
					}
				}
				if (Global.Config.DaysLimit > 0)
				{
					var date = DateTime.Now.AddDays(-Global.Config.DaysLimit);
					foreach (var s in sessions)
					{
						if (s.LastActiveTime < date)
							TryRemoveSessionData(s.SessionId.Replace("-", ""));
					}
				}
			}
		}

19 Source : CacheManager.cs
with GNU General Public License v3.0
from aiportal

public void TryRemoveSession(string sessionId)
		{
			try
			{
				string dir = Path.Combine(CachePath, sessionId);
				string rde = Path.Combine(dir, "0.rde");
				int rdiCount = Directory.GetFiles(dir, "*.rdi").Length;
				//Debug.replacedert(rdiCount == 0);
				if (rdiCount == 0 && File.Exists(rde))
					Directory.Delete(dir, true);
				else if (Directory.GetLastWriteTime(dir).AddDays(1) < DateTime.Now)
					Directory.Delete(dir, true);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 Source : SerialNumber.cs
with GNU General Public License v3.0
from aiportal

public static SerialNumber DeSerialize(string licContent, string keyName, DateTime installTime)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(licContent))
			{
				string[] ss = RSA.Decrypt(licContent, keyName).Split(',');
				if (ss.Length > 4)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						LicenseType = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3],
						MaxActivity = Convert.ToInt32(ss[4])
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = installTime;
					sn.ExpireTime = installTime.Add(span);
				}
			}
			return sn;
		}

19 Source : ClearLoginLogBackgroundService.cs
with MIT License
from aishang2015

public async Task DoWork()
        {
            while (true)
            {
                // 清理过期的日志
                var setting = _loginSetting.GetCacheData(60 * 60 * 24).FirstOrDefault();
                if (setting != null)
                {
                    var expire = DateTime.Now.AddDays(-setting.SaveTime);
                    await _loginLogDetail.RemoveAsync(d => d.OperateAt < expire);
                }
                await _systemIdenreplacedyDbUnitOfWork.SaveAsync();

                // 一小时清理一次
                await Task.Delay(TimeSpan.FromHours(1));
            }
        }

19 Source : ClearOperateLogBackgroundService.cs
with MIT License
from aishang2015

public async Task DoWork()
        {
            while (true)
            {
                // 清理过期的日志
                var settings = _logSettingCaching.GetCacheData();
                foreach (var setting in settings)
                {
                    var expire = DateTime.Now.AddDays(-setting.SaveTime);
                    await _logDetaiRepository.RemoveAsync(d => d.OperateAt < expire && d.SettingId == setting.Id);
                }
                await _systemIdenreplacedyDbUnitOfWork.SaveAsync();

                // 一小时清理一次
                await Task.Delay(TimeSpan.FromHours(1));
            }
        }

19 Source : KickassParser.cs
with MIT License
from aivarasatk

private DateTime ParseDate(string date)
        {
            var digitEndIndex = 0;
            foreach(var c in date)
            {
                if (char.IsLetter(c))
                    break;
                digitEndIndex++;
            }

            int.TryParse(date.Substring(0, digitEndIndex), out var numberToSubtract);
            var parsedDate = DateTime.UtcNow;

            if (date.Contains("min.")) parsedDate = parsedDate.AddMinutes(-numberToSubtract);
            if (date.Contains("hour")) parsedDate = parsedDate.AddHours(-numberToSubtract);
            if (date.Contains("day")) parsedDate = parsedDate.AddDays(-numberToSubtract);
            if (date.Contains("month")) parsedDate = parsedDate.AddMonths(-numberToSubtract);
            if (date.Contains("year")) parsedDate = parsedDate.AddYears(-numberToSubtract);

            return parsedDate;
        }

19 Source : ThePirateBayParser.cs
with MIT License
from aivarasatk

protected override DateTime ParseDate(string date, string[] formats)
        {
            var yesterdayFormat = "'Y-day' HH:mm";
            if (DateTime.TryParseExact(date, yesterdayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDate))
                return parsedDate.AddDays(-1);

            if (!DateTime.TryParse(date, out parsedDate))
                DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate);

            return parsedDate;
        }

19 Source : CampaignGenerator.cs
with GNU General Public License v3.0
from akaAgar

private DateTime IncrementDate(DateTime dateTime) => dateTime.AddDays(Toolbox.RandomMinMax(1, 3));

19 Source : DateAddOrSubtract.cs
with MIT License
from akaskela

protected override void Execute(CodeActivityContext context)
        {
            bool dateSet = false;
            if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
            {
                OptionSetValue value = this.Units.Get<OptionSetValue>(context);
                if (value != null)
                {
                    switch (value.Value)
                    {
                        case 222540000:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddYears(this.Number.Get<int>(context)));
                            break;
                        case 222540001:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddMonths(this.Number.Get<int>(context)));
                            break;
                        case 222540002:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddDays(this.Number.Get<int>(context) * 7));
                            break;
                        case 222540003:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddDays(this.Number.Get<int>(context)));
                            break;
                        case 222540004:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddHours(this.Number.Get<int>(context)));
                            break;
                        default:
                            ModifiedDate.Set(context, this.DateToModify.Get(context).AddMinutes(this.Number.Get<int>(context)));
                            break;
                    }
                    dateSet = true;
                }
            }

            if (!dateSet)
            {
                ModifiedDate.Set(context, this.DateToModify.Get(context));
            }
        }

19 Source : AuditGetRecentUpdates.cs
with MIT License
from akaskela

protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
        {
            TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
            
            DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
            table.Columns.AddRange(new DataColumn[] { new DataColumn("Date"), new DataColumn("User"), new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
            DateTime oldestUpdate = DateTime.MinValue;

            if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
            {
                OptionSetValue value = this.Units.Get<OptionSetValue>(context);
                if (value != null)
                {
                    switch (value.Value)
                    {
                        case 222540000:
                            oldestUpdate = DateTime.Now.AddYears(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540001:
                            oldestUpdate = DateTime.Now.AddMonths(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540002:
                            oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -7);
                            break;
                        case 222540003:
                            oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540004:
                            oldestUpdate = DateTime.Now.AddHours(this.Number.Get<int>(context) * -1);
                            break;
                        default:
                            oldestUpdate = DateTime.Now.AddMinutes(this.Number.Get<int>(context) * -1);
                            break;
                    }
                }
            }

            int maxUpdates = this.MaxAuditLogs.Get(context) > 100 || this.MaxAuditLogs.Get(context) < 1 ? 100 : this.MaxAuditLogs.Get(context);
            RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
            {
                Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
                PagingInfo = new PagingInfo() { Count = maxUpdates, PageNumber = 1 }
            };
            RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
            var detailsToInclude = response.AuditDetailCollection.AuditDetails
                .Where(ad => ad is AttributeAuditDetail && ad.AuditRecord.Contains("createdon") && ((DateTime)ad.AuditRecord["createdon"]) > oldestUpdate)
                .OrderByDescending(ad => ((DateTime)ad.AuditRecord["createdon"]))
                .ToList();

            if (detailsToInclude.Any())
            {
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
                {
                    EnreplacedyFilters = EnreplacedyFilters.Attributes,
                    LogicalName = workflowContext.PrimaryEnreplacedyName
                };
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
                EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;

                foreach (var detail in detailsToInclude.Select(d => d as AttributeAuditDetail).Where(d => d.NewValue != null && d.OldValue != null))
                {
                    DateTime dateToModify = (DateTime)detail.AuditRecord["createdon"];
                    if (dateToModify.Kind != DateTimeKind.Utc)
                    {
                        dateToModify = dateToModify.ToUniversalTime();
                    }


                    LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
                    LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
                    DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;

                    var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
                        .Distinct()
                        .Select(a =>
                        new {
                            AttributeName = a,
                            DisplayName = GetDisplayLabel(metadata, a)
                        })
                        .OrderBy(a => a.DisplayName);

                    foreach (var item in details)
                    {
                        DataRow newRow = table.NewRow();
                        newRow["User"] = GetDisplayValue(detail.AuditRecord, "userid");
                        newRow["Date"] = timeZoneSpecificDateTime.ToString("MM/dd/yyyy h:mm tt");
                        newRow["Attribute"] = item.DisplayName;
                        newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
                        newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
                        table.Rows.Add(newRow);
                    }
                }
            }
            return table;
        }

19 Source : DateTimeUtils.cs
with MIT License
from akaskela

private static DateTime CreateDateTime(DateTimeParser dateTimeParser)
        {
            bool is24Hour;
            if (dateTimeParser.Hour == 24)
            {
                is24Hour = true;
                dateTimeParser.Hour = 0;
            }
            else
            {
                is24Hour = false;
            }

            DateTime d = new DateTime(dateTimeParser.Year, dateTimeParser.Month, dateTimeParser.Day, dateTimeParser.Hour, dateTimeParser.Minute, dateTimeParser.Second);
            d = d.AddTicks(dateTimeParser.Fraction);

            if (is24Hour)
            {
                d = d.AddDays(1);
            }
            return d;
        }

19 Source : WeatherForecastService.cs
with Apache License 2.0
from akovac35

public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
        {
            _logger.Here(l => l.Entering(startDate));

            _logger.Here(l => l.LogInformation("CorrelationId is useful for correlating log contents with service or web page requests: {@0}", CorrelationProviderAccessorInstance.Current?.GetCorrelationId()));

            var rng = new Random();
            var tmp = Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = startDate.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            }).ToArray());

            _logger.Here(l => l.Exiting(tmp));
            return tmp;
        }

19 Source : SessionService.cs
with MIT License
from aksoftware98

public async Task<EnreplacedyApiResponse<WorkScheduleDetail>> CreateWorkScheduleAsync(WorkScheduleDetail scheduleDetail, string currentUserId)
        {
            if (scheduleDetail is null)
                throw new ArgumentNullException(nameof(scheduleDetail));

            if (scheduleDetail.Sessions is null || scheduleDetail.Sessions.Count < 1)
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Sessions can't be empty");

            // if there exists a session with startDate DOW different that endDate DOW
            if (scheduleDetail.Sessions.Any(s => s.StartDate.DayOfWeek != s.EndDate.DayOfWeek))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Sessions start and end date should be on the same day");

            // Check if there is a session with end date earlier than start date
            if (scheduleDetail.Sessions.Any(s => s.EndDate <= s.StartDate))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Schedule has incorrect time ranges");

            var tomorrowDate = DateTime.UtcNow.AddDays(1).NormalizedDate();

            if (scheduleDetail.Sessions.Any(s => s.StartDate < tomorrowDate))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Sessions can only be added for tomorrow and beyond");

            if (scheduleDetail.Sessions.Any(s => s.User is null))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "A session doesn't have a user specified for it");

            var sessionsByDayOfWeek = scheduleDetail.Sessions.GroupBy(s => s.StartDate.DayOfWeek);
            
            // Check if any session has conflicts wit any other session
            if (HasTimeConflicts(sessionsByDayOfWeek))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Schedule has some time conflicts");

            var org = await _orgRepository.GetByIdAsync(scheduleDetail.OrganiztionId);

            if (org is null)
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Organization does not exist");

            var usersIdsRetrieved = new List<string>();
            var sessionsAdded = new Session[scheduleDetail.Sessions.Count];
            int i = 0;

            foreach (var sessionDetail in scheduleDetail.Sessions)
            {
                if (!usersIdsRetrieved.Contains(sessionDetail.User.Id))
                {
                    var user = await _userManager.FindByIdAsync(sessionDetail.User.Id);

                    if (user is null)
                        return new EnreplacedyApiResponse<WorkScheduleDetail>
                            (error: $"Session with name: {sessionDetail.Name} has a selected user that does not exist");

                    usersIdsRetrieved.Add(user.Id);
                }

                var session = new Session
                {
                    Name = sessionDetail.Name?.Trim(),
                    Description = sessionDetail.Description?.Trim(),
                    StartDate = sessionDetail.StartDate.ToUniversalTime(),
                    EndDate = sessionDetail.EndDate.ToUniversalTime(),
                    CreatedById = currentUserId,
                    ModifiedById = currentUserId,
                    OrganizationId = org.Id,
                    UserId = sessionDetail.User.Id
                };

                await _sessionRepository.InsertAsync(session);
                sessionsAdded[i] = session;
                i++;
            }

            var endDate = sessionsAdded.Max(s => s.EndDate);

            return new EnreplacedyApiResponse<WorkScheduleDetail>(enreplacedy: new WorkScheduleDetail(sessionsAdded, tomorrowDate, endDate));
        }

19 Source : UsersService.cs
with MIT License
from aksoftware98

public async Task<UserManagerResponse> LoginUserAsync(LoginRequest model)
        {
            var user = await _userManger.FindByEmailAsync(model.Email);

            if (user == null)
            {
                throw new NotFoundException($"Username or preplacedword is invalid");
            }

            var result = await _userManger.CheckPreplacedwordAsync(user, model.Preplacedword);

            if (!result)
                throw new NotFoundException($"Username or preplacedword is invalid");

            var claims = new[]
            {
                new Claim(ClaimTypes.Email, model.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.GivenName, user.FirstName),
                new Claim(ClaimTypes.Surname, user.LastName)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["AuthSettings:Key"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["AuthSettings:Issuer"],
                audience: _configuration["AuthSettings:Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            string tokenreplacedtring = new JwtSecurityTokenHandler().WriteToken(token);

            return new UserManagerResponse
            {
                UserInfo = claims.ToDictionary(c => c.Type, c => c.Value),
                Message = tokenreplacedtring,
                IsSuccess = true,
                ExpireDate = token.ValidTo
            };
        }

19 Source : SessionService.cs
with MIT License
from aksoftware98

public async Task<EnreplacedyApiResponse<WorkScheduleDetail>> UpdateWorkScheduleAsync(WorkScheduleDetail scheduleDetail, string currentUserId)
        {
            if (scheduleDetail is null)
                throw new ArgumentNullException(nameof(scheduleDetail));

            if (scheduleDetail.Sessions is null || scheduleDetail.Sessions.Count < 1)
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Sessions can't be empty");

            // if there exists a session with startDate DOW different that endDate DOW
            if (scheduleDetail.Sessions.Any(s => s.StartDate.DayOfWeek != s.EndDate.DayOfWeek))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Sessions start and end date should be on the same day");

            // Check if there is a session with end date earlier than start date
            if (scheduleDetail.Sessions.Any(s => s.EndDate <= s.StartDate))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Schedule has incorrect time ranges");

            var tomorrorwDate = DateTime.UtcNow.AddDays(1).NormalizedDate();

            if (scheduleDetail.Sessions.Any(s => s.StartDate < tomorrorwDate))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Can't update sessions earlier than tomorrow");

            if (scheduleDetail.Sessions.Any(s => s.User is null))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "A session doesn't have a user specified for it");

            var newSessionsByDayOfWeek = scheduleDetail.Sessions.GroupBy(s => s.StartDate.DayOfWeek);

            // Check if any session has conflicts wit any other session
            if (HasTimeConflicts(newSessionsByDayOfWeek))
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Schedule has some time conflicts");

            var endDate = scheduleDetail.Sessions.Max(s => s.EndDate);

            var oldSessions = await SessionsBetweenDates(tomorrorwDate, endDate, scheduleDetail.OrganiztionId);

            // Get from the old session the ones where they do not exist in the new sessions
            // Those would be the ones to delete
            var sessionsToDelete = oldSessions.Where(session => !scheduleDetail.Sessions.Any(sessionDetail => sessionDetail.Id == session.Id));

            var usersIdsRetrieved = new List<string>();
            var sessionsToReturn = new Session[scheduleDetail.Sessions.Count];
            int i = 0;

            foreach (var sessionDetail in scheduleDetail.Sessions)
            {
                if (!usersIdsRetrieved.Contains(sessionDetail.User.Id))
                {
                    var user = await _userManager.FindByIdAsync(sessionDetail.User.Id);

                    if (user is null)
                        return new EnreplacedyApiResponse<WorkScheduleDetail>
                            (error: $"Session with name: {sessionDetail.Name} has a selected user that does not exist");

                    usersIdsRetrieved.Add(user.Id);
                }

                Session session;

                // If the id is null then it is a new session to add
                if (string.IsNullOrEmpty(sessionDetail.Id))
                {
                    session = new Session
                    {
                        Name = sessionDetail.Name?.Trim(),
                        Description = sessionDetail.Description?.Trim(),
                        StartDate = sessionDetail.StartDate.ToUniversalTime(),
                        EndDate = sessionDetail.EndDate.ToUniversalTime(),
                        CreatedById = currentUserId,
                        ModifiedById = currentUserId,
                        OrganizationId = scheduleDetail.OrganiztionId,
                        UserId = sessionDetail.User.Id
                    };
                    
                    await _sessionRepository.InsertAsync(session);
                }

                // It is an already added session that needs to be updated
                else
                {
                    session = oldSessions.FirstOrDefault(s => s.Id == sessionDetail.Id);

                    if (session is null)
                        continue;

                    session.StartDate = sessionDetail.StartDate.ToUniversalTime();
                    session.EndDate = sessionDetail.EndDate.ToUniversalTime();
                    session.Name = sessionDetail.Name?.Trim();
                    session.Description = sessionDetail.Description.Trim();
                    session.UserId = sessionDetail.User.Id;
                    session.LastModifiedDate = DateTime.UtcNow;
                    session.ModifiedById = currentUserId;

                    await _sessionRepository.UpdateAsync(session);
                }

                sessionsToReturn[i] = session;
                i++;
            }

            // Delete the sessions that have been excluded from the schedule
            await _sessionRepository.DeleteAsync(sessionsToDelete);

            return new EnreplacedyApiResponse<WorkScheduleDetail>(enreplacedy: new WorkScheduleDetail(sessionsToReturn, tomorrorwDate, endDate));
        }

19 Source : ApplicationUserExtensions.cs
with MIT License
from aksoftware98

public static JwtSecurityToken GenerateJwtToken(this ApplicationUser user, IConfiguration configuration, IWebHostEnvironment env)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
                new Claim("OrgId", user.OrganizationId),
                new Claim("ProfilePicture", $"{env.WebRootPath.Replace("\\\\", "/")}/{user.ProfilePicture}")
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Key"]));

            return new JwtSecurityToken(
                issuer: configuration["Issuer"],
                audience: configuration["Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
        }

19 Source : SessionService.cs
with MIT License
from aksoftware98

public async Task<EnreplacedyApiResponse<WorkScheduleDetail>> GetWorkScheduleAsync(string organizationId, DateTime? fromDate = null, DateTime? toDate = null)
        {
            if (fromDate.HasValue && toDate.HasValue && fromDate.Value > toDate.Value)
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Incorrect selection of dates");

            var org = await _orgRepository.GetByIdAsync(organizationId);

            if (org is null)
                return new EnreplacedyApiResponse<WorkScheduleDetail>(error: "Organization does not exist");

            var startDate = fromDate ?? DateTime.UtcNow.AddDays(1).NormalizedDate();
            var endDate = toDate ?? startDate.AddDays(7);

            var sessions = await SessionsBetweenDates(startDate, endDate, org.Id);

            return new EnreplacedyApiResponse<WorkScheduleDetail>(enreplacedy: new WorkScheduleDetail(sessions, startDate, endDate));
        }

19 Source : IUserServiceV1.cs
with MIT License
from aksoftware98

public async Task<UserManagerResponse> LoginUserAsync(LoginRequest model)
        {
            var user = await _userManger.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return new UserManagerResponse
                {
                    Message = "There is no user with that Email address",
                    IsSuccess = false,
                };
            }

            var result = await _userManger.CheckPreplacedwordAsync(user, model.Preplacedword);

            if (!result)
                return new UserManagerResponse
                {
                    Message = "Invalid preplacedword",
                    IsSuccess = false,
                };

            var claims = new[]
            {
                new Claim("Email", model.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim("FirstName", user.FirstName),
                new Claim("LastName", user.LastName)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["AuthSettings:Key"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["AuthSettings:Issuer"],
                audience: _configuration["AuthSettings:Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            string tokenreplacedtring = new JwtSecurityTokenHandler().WriteToken(token);

            return new UserManagerResponse
            {
                UserInfo = claims.ToDictionary(c => c.Type, c => c.Value),
                Message = tokenreplacedtring,
                IsSuccess = true,
                ExpireDate = token.ValidTo
            };
        }

19 Source : SampleDataController.cs
with MIT License
from alanmacgowan

[HttpGet("[action]")]
        public IEnumerable<WeatherForecast> WeatherForecasts()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

19 Source : UpdateChecker.cs
with GNU General Public License v3.0
from Albo1125

private static void NextUpdateCallback(Popup p)
        {
            if (p.IndexOfGivenAnswer == 0)
            {
                Game.LogTrivial("Continue pressed");
                Index++;
                if (PluginsDownloadLink.Count > Index)
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Update " + (Index + 1) + ": " + PluginsDownloadLink[Index].Item1, new List<string>() { "Continue", "Go to download page" },
                        false, false, NextUpdateCallback);
                    pop.Display();
                }
                else
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Please install updates to maintain stability and don't request support for old versions.",
                        new List<string>() { "-", "Open installation/troubleshooting video tutorial", "Continue to game.", "Delay next update check by a week.", "Delay next update check by a month.",
                            "Fully disable update checks (not recommended)." }, false, false, NextUpdateCallback);
                    pop.Display();
                }
            }
            else if (p.IndexOfGivenAnswer == 1)
            {
                Game.LogTrivial("GoToDownload pressed.");
                if (PluginsDownloadLink.Count > Index && Index >= 0)
                {
                    System.Diagnostics.Process.Start(PluginsDownloadLink[Index].Item2);
                }
                else
                {
                    System.Diagnostics.Process.Start("https://youtu.be/af434m72rIo?list=PLEKypmos74W8PMP4k6xmVxpTKdebvJpFb");
                }
                p.Display();
            }
            else if (p.IndexOfGivenAnswer == 2)
            {
                Game.LogTrivial("ExitButton pressed.");
            }
            else if (p.IndexOfGivenAnswer == 3)
            {
                Game.LogTrivial("Delay by week pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(6);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 4)
            {
                Game.LogTrivial("Delay by month pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddMonths(1);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 5)
            {
                Game.LogTrivial("Disable Update Checks pressed.");
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                Popup pop = new Popup("Albo1125.Common Update Check", "Update checking has been disabled for this version of Albo1125.Common." +
                    "To re-enable it, delete the Albo1125.Common folder from your Grand Theft Auto V folder. Please do not request support for old versions.", false, true);
                pop.Display();
            }
        }

19 Source : UpdateChecker.cs
with GNU General Public License v3.0
from Albo1125

public static void InitialiseUpdateCheckingProcess()
        {
            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Starting update checks.");
            Directory.CreateDirectory("Albo1125.Common/UpdateInfo");
            if (!File.Exists("Albo1125.Common/CommonVariables.xml"))
            {
                new XDoreplacedent(
                        new XElement("CommonVariables")
                    )
                    .Save("Albo1125.Common/CommonVariables.xml");
            }
            try
            {
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                if (!string.IsNullOrWhiteSpace((string)CommonVariablesDoc.Root.Element("NextUpdateCheckDT")))
                {

                    try
                    {
                        if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value == replacedembly.GetExecutingreplacedembly().GetName().Version.ToString())
                        {
                            Game.LogTrivial("Albo1125.Common update checking has been disabled. Skipping checks.");
                            Game.LogTrivial("Albo1125.Common note: please do not request support for old versions.");
                            return;
                        }
                        DateTime UpdateCheckDT = DateTime.FromBinary(long.Parse(CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value));
                        if (DateTime.Now < UpdateCheckDT)
                        {

                            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Not checking for updates until " + UpdateCheckDT.ToString());
                            return;
                        }
                    }
                    catch (Exception e) { Game.LogTrivial(e.ToString()); Game.LogTrivial("Albo1125.Common handled exception. #1"); }

                }

                
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(1);
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                GameFiber.StartNew(delegate
                {


                    GetUpdateNodes();
                    foreach (UpdateEntry entry in AllUpdateEntries.ToArray())
                    {
                        CheckForModificationUpdates(entry.Name, new Version(FileVersionInfo.GetVersionInfo(entry.Path).FileVersion), entry.FileID, entry.DownloadLink);
                    }
                    if (PluginsDownloadLink.Count > 0) { DisplayUpdates(); }
                    Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Update checks complete.");
                });
            }
            catch (System.Xml.XmlException e)
            {
                Game.LogTrivial(e.ToString());
                Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
                throw e;
            }

            



        }

19 Source : CourtSystem.cs
with GNU General Public License v3.0
from Albo1125

public static DateTime DetermineCourtHearingDate()
        {
            if (RealisticCourtDates)
            {
                DateTime CourtDate = DateTime.Now;
                int Minutes = (int)Math.Round(((float)CourtDate.Minute) / 5.0f) * 5;
                while (CourtDate.Minute != Minutes)
                {
                    CourtDate = CourtDate.AddMinutes(1);
                    Minutes = (int)Math.Round(((float)CourtDate.Minute) / 5.0f) * 5;
                }
                while (CourtDate.Hour > 17 || CourtDate.Hour < 9)
                {
                    CourtDate = CourtDate.AddHours(LSPDFRPlusHandler.rnd.Next(1, 8));
                }


                CourtDate = CourtDate.AddDays(LSPDFRPlusHandler.rnd.Next(1, 4));

                return CourtDate;
            }
            else
            {
                return DateTime.Now.AddMinutes(LSPDFRPlusHandler.rnd.Next(2, 10));
            }
        }

See More Examples