System.DateTime.AddYears(int)

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

695 Examples 7

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
        {
            // create DN for subject and issuer
            var dn = new CX500DistinguishedName();
            dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
            // create a new private key for the certificate
            CX509PrivateKey privateKey = new CX509PrivateKey
            {
                ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider",
                MachineContext = false,
                Length = 2048,
                KeySpec = X509KeySpec.XCN_AT_SIGNATURE, // use is not limited
                ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG
            };
            privateKey.Create();

            // Use the stronger SHA512 hashing algorithm
            var hashobj = new CObjectId();
            hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
                ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
                AlgorithmFlags.AlgorithmFlagsNone, "SHA256");

            // add extended key usage if you want - look at MSDN for a list of possible OIDs
            var oid = new CObjectId();
            oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
            var oidlist = new CObjectIds { oid };
            var eku = new CX509ExtensionEnhancedKeyUsage();
            eku.InitializeEncode(oidlist);

            // Create the self signing request
            var cert = new CX509CertificateRequestCertificate();
            cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, "");
            cert.Subject = dn;
            cert.Issuer = dn; // the issuer and the subject are the same
            cert.NotBefore = DateTime.Now;
            // this cert expires immediately. Change to whatever makes sense for you
            cert.NotAfter = DateTime.Now.AddYears(1);
            cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
            cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
            cert.Encode(); // encode the certificate

            // Do the final enrollment process
            var enroll = new CX509Enrollment();
            enroll.InitializeFromRequest(cert); // load the certificate
            enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
            string csr = enroll.CreateRequest(); // Output the request in base64
                                                 // and install it back as the response
            enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
                csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no preplacedword
                                                                // output a base64 encoded PKCS#12 so we can import it back to the .Net security clreplacedes
            var base64encoded = enroll.CreatePFX("", // no preplacedword, this is for internal consumption
                PFXExportOptions.PFXExportChainWithRoot);

            // instantiate the target clreplaced with the PKCS#12 data (and the empty preplacedword)
            return new System.Security.Cryptography.X509Certificates.X509Certificate2(
                System.Convert.FromBase64String(base64encoded), "",
                // mark the private key as exportable (this is usually what you want to do)
                System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
            );
        }

19 View Source File : TimedTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void skinComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = scb_cycle.SelectedIndex;

            date.Visible = true;
            date.Enabled = true;
            week_panel.Visible = false;
            date.MinDate = DateTime.Now.AddYears(-10);
            label3.Text = "日期:";

            if(index == 0){ // 一次
                date.MinDate = DateTime.Now;
            }
            else if (index == 1)
            {
                // 每天                
                date.Enabled = false;                
            }
            else if (index == 2)
            {
                // 每周
                week_panel.Visible = true;
                label3.Text = "星期:";
            }
        }

19 View Source File : Yun.cs
License : MIT License
Project Creator : 6tail

public Solar getStartSolar()
        {
            Solar birth = lunar.getSolar();
            DateTime c = ExactDate.fromYmd(birth.getYear(), birth.getMonth(), birth.getDay());
            c = c.AddYears(startYear);
            c = c.AddMonths(startMonth);
            c = c.AddDays(startDay);
            return Solar.fromDate(c);
        }

19 View Source File : SolarYear.cs
License : MIT License
Project Creator : 6tail

public SolarYear next(int years)
        {
            DateTime c = ExactDate.fromYmd(year, 1, 1);
            c = c.AddYears(years);
            return new SolarYear(c);
        }

19 View Source File : Index.cshtml.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<IActionResult> OnPostClearLogAsync(int type)
        {
            switch (type)
            {
                case 1:

                    await _logAppService.ClearLog(DateTime.Now.AddYears(-1));
                    break;

                case 2:
                    await _logAppService.ClearLog(DateTime.Now.AddMonths(-6));
                    break;

                case 3:
                    await _logAppService.ClearLog(DateTime.Now.AddMonths(-3));
                    break;

                case 4:
                    await _logAppService.ClearLog(DateTime.Now.AddMonths(-1));
                    break;
            }




            return RedirectToPage("OperatorLog");
        }

19 View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<UserYearlyCountListStats> GetUsersCountOverTwoYears()
        {
            // end Date 6/4/ 2020
            // start date 1/1/2019
            // the stats will
            // CurrentYear : 1/1/20, 1/2/20, 1/3/20, 1/4/20, 1/5/20 = 0, 1/6/20 = 0, 1/7/20 = 0, ...
            // PreviousYear: 1/1/19, 1/2/19, 1/3/19, 1/4/19, 1/5/19 = x, 1/6/20 = y, 1/7/19 = z, ...
            var startDate = DateTime.UtcNow.AddYears(-1).AddMonths(-DateTime.UtcNow.Month + 1).AddDays(-DateTime.UtcNow.Day + 1).Date;
            var endDate = DateTime.UtcNow.Date;

            var usersMonthly = (from u in _usersRepo.Table
                                where u.CreatedAt >= startDate && u.CreatedAt <= endDate
                                group u by new
                                {
                                    u.CreatedAt.Year,
                                    u.CreatedAt.Month
                                } into g
                                select new
                                {
                                    Count = g.Count(),
                                    MonthYear = new DateTime(g.Key.Year, g.Key.Month, 1)
                                }).ToList();

            var months = Enumerable.Range(0, 24).Select(offset => startDate.AddMonths(offset)).ToList();

            months.ForEach(month =>
            {
                if (!usersMonthly.Any(u => u.MonthYear.Year == month.Year && u.MonthYear.Month == month.Month))
                {
                    usersMonthly.Add(new
                    {
                        Count = 0,
                        MonthYear = month,
                    });
                }
            });

            return new UserYearlyCountListStats()
            {
                CurrentYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList(),
                PreviousYear = usersMonthly.Where(um => um.MonthYear.Year == DateTime.UtcNow.Year - 1).OrderBy(c => c.MonthYear).Select(c => c.Count).ToList()
            };
        }

19 View Source File : TimeAggregatedDataGenerator.cs
License : MIT License
Project Creator : Actipro

public void Generate() {
			// Create a random number generator
			var resolvedRandomSeed = randomSeed ?? Environment.TickCount;
			var random = new Random(resolvedRandomSeed);

			// Initialize the date
			DateTime date;
			var resolvedDataPointCount = this.DataPointCount;
			switch (timePeriod) {
				case TimePeriod.Month:
					date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
					date = date.AddMonths(-resolvedDataPointCount);
					break;
				case TimePeriod.Week:
					date = DateTime.Today;
					date = date.AddDays(-resolvedDataPointCount * 7);
					break;
				default:  // Year
					date = new DateTime(DateTime.Today.Year, 1, 1);
					date = date.AddYears(-resolvedDataPointCount);
					break;
			}

			// Initialize the results with the first data item
			this.BeginUpdate();
			try {
				this.Clear();

				// Quit if there are no data points
				if (resolvedDataPointCount == 0)
					return;
				
				// Determine the trend percentage
				double trendPercentage;
				switch (trend) {
					case Trend.Upward:
						trendPercentage = 0.3;
						break;
					case Trend.Downward:
						trendPercentage = 0.7;
						break;
					default:  // Random
						trendPercentage = 0.5;
						break;
				}

				// Get the first amount
				var delta = Convert.ToDouble(trendPercentage) * this.StepRange;
				var step = Convert.ToDouble(random.NextDouble()) * this.StepRange;
				var firstAmount = (presetAmounts != null ? presetAmounts[0] : this.StartAmount + step - delta);
				this.Add(this.CreateData(random, 0, timePeriod, date, firstAmount));
				
				switch (timePeriod) {
					case TimePeriod.Month:
						date = date.AddMonths(1);
						break;
					case TimePeriod.Week:
						date = date.AddDays(7);
						break;
					default:  // Year
						date = date.AddYears(1);
						break;
				}

				for (int index = 1; index < resolvedDataPointCount; index++) {
					step = Convert.ToDouble(random.NextDouble()) * this.StepRange;
					var amount = (presetAmounts != null ? presetAmounts[index] : this[index - 1].Amount + step - delta);

					if (!this.AllowNegativeNumbers)
						amount = Math.Max(0, amount);

					this.Add(this.CreateData(random, index, timePeriod, date, amount));

					switch (timePeriod) {
						case TimePeriod.Month:
							date = date.AddMonths(1);
							break;
						case TimePeriod.Week:
							date = date.AddDays(7);
							break;
						default:  // Year
							date = date.AddYears(1);
							break;
					}
				}
			}
			finally {
				this.EndUpdate();
			}
		}

19 View Source File : DateTimePicker.xaml.cs
License : MIT License
Project Creator : ADeltaX

private DateTime Increase(int selstart, int value)
		{
			DateTime retval = (ParseDateText(false) ?? SelectedDate);

			try
			{
				switch (DateFormat.Substring(selstart, 1))
				{
					case "h":
					case "H":
						retval = retval.AddHours(value);
						break;
					case "y":
						retval = retval.AddYears(value);
						break;
					case "M":
						retval = retval.AddMonths(value);
						break;
					case "m":
						retval = retval.AddMinutes(value);
						break;
					case "d":
						retval = retval.AddDays(value);
						break;
					case "s":
						retval = retval.AddSeconds(value);
						break;
				}
			}
			catch (ArgumentException ex)
			{
				//Catch dates with year over 9999 etc, dont throw
			}

			return retval;
		}

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

private static string ComputeTokenSignature(string uri, string sharedKey, string policyName)
		{
			string signatureStringFormat = "sig={0}",
				expiryStringFormat = "se={0}",
				keyNameStringFormat = "skn={0}",
				resourceStringFormat = "sr={0}",
				tokenFormat = "{0}&{1}&{2}&{3}";

			DateTime epochBaseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
			DateTime expiry = DateTime.Now.AddYears(1);
			var expiryString = ((long)(expiry - epochBaseTime).TotalSeconds).ToString("D");

			var requestUri = new Uri(uri);
			var resourceUrl = requestUri.Host + HttpUtility.UrlDecode(requestUri.AbsolutePath);

			var fields = new List<string> { HttpUtility.UrlEncode(resourceUrl), expiryString };
			using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(sharedKey)))
			{
				var requestString = string.Join("\n", fields);
				var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(requestString)));

				return string.Format(
					tokenFormat,
					string.Format(signatureStringFormat, HttpUtility.UrlEncode(signature)),
					string.Format(expiryStringFormat, HttpUtility.UrlEncode(expiryString)),
					string.Format(keyNameStringFormat, HttpUtility.UrlEncode(policyName)),
					string.Format(resourceStringFormat, HttpUtility.UrlEncode(resourceUrl)));
			}
		}

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

public static Enreplacedy CreateSupportPlan(decimal total, IPortalContext portal, OrganizationServiceContext context,
			Enreplacedy uom, Enreplacedy contact, Enreplacedy product, Enreplacedy account)
		{
			var supportPlanId = Guid.NewGuid();

			var supportPlan = new Enreplacedy("adx_supportplan") { Id = supportPlanId };

			supportPlan.Attributes["adx_supportplanid"] = supportPlanId;

			var siteSettingStringFormat = context.GetSiteSettingValueByName(portal.Website, "HelpDesk/SupportPlanNameFormat");
			var contactName = string.Empty;
			var accountName = string.Empty;

			if (account != null)
			{
				supportPlan.Attributes["adx_customer"] = account.ToEnreplacedyReference();
				supportPlan.Attributes["adx_billtocustomer"] = account.ToEnreplacedyReference();
				accountName = account.GetAttributeValue<string>("name");
			}
			else if (contact != null)
			{
				supportPlan.Attributes["adx_customercontact"] = contact.ToEnreplacedyReference();
				contactName = contact.GetAttributeValue<string>("fullname");
			}

			supportPlan.Attributes["adx_name"] = !string.IsNullOrWhiteSpace(siteSettingStringFormat)
															? string.Format(siteSettingStringFormat,
																			accountName,
																			contactName,
																			DateTime.UtcNow)
															: string.Format(ResourceManager.GetString("Support_Plan_For_Purchased"),
																			accountName,
																			contactName,
																			DateTime.UtcNow);

			supportPlan.Attributes["adx_startdate"] = DateTime.UtcNow;

			supportPlan.Attributes["adx_enddate"] = DateTime.UtcNow.AddYears(1);

			if (product != null)
			{
				supportPlan.Attributes["adx_product"] = product.ToEnreplacedyReference();
			}

			supportPlan.Attributes["adx_totalprice"] = new Money(total);

			if (uom != null)
			{
				supportPlan.Attributes["adx_allotmentsused"] = 0;
				supportPlan.Attributes["adx_allotmentsissued"] = (int)uom.GetAttributeValue<decimal>("quanreplacedy");
				supportPlan.Attributes["adx_allotmentsremaining"] = (int)uom.GetAttributeValue<decimal>("quanreplacedy");
			}

			try
			{
				context.AddObject(supportPlan);

				context.SaveChanges();
			}
			catch
			{

			}

			supportPlan = context.CreateQuery("adx_supportplan")
				.FirstOrDefault(sr => sr.GetAttributeValue<Guid>("adx_supportplanid") == supportPlanId);
			return supportPlan;
		}

19 View Source File : IdeaForumDataAdapterFactory.cs
License : MIT License
Project Creator : 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 View Source File : DateFilters.cs
License : MIT License
Project Creator : Adoxio

public static DateTime? DateAddYears(DateTime? date, int value)
		{
			return date.HasValue
				? date.Value.AddYears(value)
				: (DateTime?)null;
		}

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

private void SetParams(IDataAdapterDependencies dependencies, bool isMin, bool isMax, DateTime? min, DateTime? max)
		{
			_isMin = isMin;
			_isMax = isMax;
			_min = min;
			_max = max;

			//_context = portalLiquidContext;
			_dependencies = dependencies;

			_occurences =
				new Lazy<EventOccurrenceDrop[]>(
					() => _adapter.SelectEventOccurrences(DateTime.Today.AddYears(-2), DateTime.Today.AddYears(2))
						.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);
		}

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

public override object BeforeMethod(string method)
		{
			if (method == null || !EventsEnabled)
			{
				return null;
			}

			DateTime dateTime;

			if (DateTime.TryParse(method, out dateTime))
			{

				if (_isMin)
				{
					_min = dateTime;

					if (_max != null) //there is a minimum value
					{
						if (_max < _min)
						{
							throw new ArgumentOutOfRangeException("_max", ResourceManager.GetString("MaxDate_LessThan_MinDate_Exception"));
						}

						_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(_min.Value, _max.Value)
							.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);

						return All;
					}

					_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(_min.Value, DateTime.Today.AddYears(2))
						.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);

					return new EventOccurrencesDrop(this, _dependencies, false, false, _min, _max);
				}

				if (_isMax)
				{
					_max = dateTime;

					if (_min != null) //there is a minimum value
					{
						if (_max < _min)
						{
							throw new ArgumentOutOfRangeException("_max", ResourceManager.GetString("MaxDate_LessThan_MinDate_Exception"));
						}

						_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(_min.Value, _max.Value)
							.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);

						return All;
					}

					//there is no minimum value

					_occurences = new Lazy<EventOccurrenceDrop[]>(() => _adapter.SelectEventOccurrences(DateTime.Today.AddYears(-2), _max.Value)
							.Select(e => new EventOccurrenceDrop(this, _dependencies, e)).ToArray(), LazyThreadSafetyMode.None);

					return new EventOccurrencesDrop(this, _dependencies, false, false, _min, _max);
				}

			}

			return null;
		}

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

protected void Page_Load(object sender, EventArgs args)
		{
			if (Enreplacedy.LogicalName != "adx_webpage")
			{
				return;
			}

			var webPage = XrmContext.CreateQuery("adx_webpage")
				.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webpageid") == Enreplacedy.Id);

			if (webPage == null)
			{
				return;
			}

			var subject = webPage.GetAttributeValue<EnreplacedyReference>("adx_subjectid");

			if (subject == null)
			{
				MostPopularArticlesSearchData.Query =
					Html.Setting("knowledgebase/search/query", "adx_averagerating_int:5^5 adx_averagerating_int:4^4 adx_averagerating_int:3 +msa_publishtoweb:1 createdon.year:@thisyear^2 createdon.year:@1yearago createdon.year:@2yearsago^0.5");
			}
			else
			{
				MostPopularArticlesSearchData.SelectParameters.Add("subjectid", subject.Id.ToString());

				MostPopularArticlesSearchData.Query =
					Html.Setting("knowledgebase/search/querywithsubject", "adx_averagerating_int:5^5 adx_averagerating_int:4^4 adx_averagerating_int:3 +subjectid:@subjectid~0.99 +msa_publishtoweb:1 createdon.year:@thisyear^2 createdon.year:@1yearago createdon.year:@2yearsago^0.5");
			}

			var now = DateTime.UtcNow;

			MostPopularArticlesSearchData.SelectParameters.Add("thisyear", now.ToString("yyyy"));
			MostPopularArticlesSearchData.SelectParameters.Add("1yearago", now.AddYears(-1).ToString("yyyy"));
			MostPopularArticlesSearchData.SelectParameters.Add("2yearsago", now.AddYears(-2).ToString("yyyy"));
			MostPopularArticlesSearchData.SelectParameters.Add("3yearsago", now.AddYears(-3).ToString("yyyy"));
			MostPopularArticlesSearchData.SelectParameters.Add("4yearsago", now.AddYears(-4).ToString("yyyy"));
			MostPopularArticlesSearchData.SelectParameters.Add("5yearsago", now.AddYears(-5).ToString("yyyy"));

			if (subject == null)
			{
				return;
			}

			if (string.IsNullOrEmpty(SearchData.Query))
			{
				SearchData.Query = "+subjectid:@subjectid~0.99 +msa_publishtoweb:1 createdon.year:@thisyear^2 createdon.year:@1yearago createdon.year:@2yearsago^0.5";
			}

			SearchData.SelectParameters.Add("subjectid", subject.Id.ToString());
			SearchData.SelectParameters.Add("thisyear", now.ToString("yyyy"));
			SearchData.SelectParameters.Add("1yearago", now.AddYears(-1).ToString("yyyy"));
			SearchData.SelectParameters.Add("2yearsago", now.AddYears(-2).ToString("yyyy"));
			SearchData.SelectParameters.Add("3yearsago", now.AddYears(-3).ToString("yyyy"));
			SearchData.SelectParameters.Add("4yearsago", now.AddYears(-4).ToString("yyyy"));
			SearchData.SelectParameters.Add("5yearsago", now.AddYears(-5).ToString("yyyy"));

			SubjectSearch.Visible = true;
		}

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

[HttpGet]
		public ActionResult Download(Guid enreplacedyListId, Guid viewId, string from, string to, string filter, string search)
		{
			DateTime parsedFrom;

			var fromDate = DateTime.TryParseExact(from, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out parsedFrom)
				? parsedFrom
				: DateTime.UtcNow.AddYears(-10);

			DateTime parsedTo;

			var toDate = DateTime.TryParseExact(to, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out parsedTo)
				? parsedTo
				: DateTime.UtcNow.AddYears(10);

			var dataAdapter = new EnreplacedyListCalendarDataAdapter(
				new EnreplacedyReference("adx_enreplacedylist", enreplacedyListId),
				new EnreplacedyReference("savedquery", viewId),
				new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext));

			var events = dataAdapter.SelectEvents(fromDate, toDate, filter, search)
				.OrderBy(e => e.Start)
				.ThenBy(e => e.Summary);

			var vcalendar = new VCalendar(events.Select(GetVEvent));

			return new ContentResult
			{
				ContentType = "text/calendar",
				Content = vcalendar.ToString()
			};
		}

19 View Source File : CalendarController.cs
License : MIT License
Project Creator : ahmetozlu

public void YearPrev()
    {
        _dateTime = _dateTime.AddYears(-1);
        CreateCalendar();
    }

19 View Source File : CalendarController.cs
License : MIT License
Project Creator : ahmetozlu

public void YearNext()
    {
        _dateTime = _dateTime.AddYears(1);
        CreateCalendar();
    }

19 View Source File : KickassParser.cs
License : MIT License
Project Creator : 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 View Source File : SetCookie.cs
License : MIT License
Project Creator : akasarto

public static void SetCookie(this HttpContextBase @this, string cookieName, string cookieValue, DateTime? expirationDate = null)
		{
			var requestCookies = @this.Request.Cookies;
			var responseCookies = @this.Response.Cookies;

			if (expirationDate == null)
			{
				expirationDate = DateTime.UtcNow.AddYears(1);
			}

			var httpCookie = @this.GetCookie(cookieName);

			if (httpCookie == null)
			{
				httpCookie = new HttpCookie(cookieName);
			}

			httpCookie.Value = cookieValue;
			httpCookie.Expires = expirationDate.Value;

			responseCookies.Add(httpCookie);
		}

19 View Source File : AuditGetRecentUpdates.cs
License : MIT License
Project Creator : 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 View Source File : DateAddOrSubtract.cs
License : MIT License
Project Creator : 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 View Source File : SolicitationTrafficStop.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private int GetAge(DateTime Birthday)
        {
            DateTime today = DateTime.Today;
            int age = today.Year - Birthday.Year;

            if (Birthday > today.AddYears(-age))
            {
                age--;
            }
            Game.LogTrivial(age.ToString());
            return age;
                
        }

19 View Source File : SolicitationTrafficStop.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public void DetermineAnswers(bool PreplacedengerHookedOtherVehicles)
        {
            if (!PreplacedengerHookedOtherVehicles)
            {
                
                int roll = replacedortedCalloutsHandler.rnd.Next(5);
                
                Game.LogTrivial("Hookedothervehicles false, roll " + roll.ToString());
                if (roll == 0)
                {
                    DateTime DriverBirthday = DriverPersona.Birthday;
                    DateTime PreplacedengerBirthday = PreplacedengerPersona.Birthday;
                    while (GetAge(DriverBirthday) < 26) { DriverBirthday = DriverBirthday.AddYears(-1); }
                    while (GetAge(PreplacedengerBirthday) - GetAge(DriverBirthday) > 3) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(1); GameFiber.Yield(); }
                    while (GetAge(DriverBirthday) - GetAge(PreplacedengerBirthday) > 3) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(-1); GameFiber.Yield(); }

                    PreplacedengerPersona.Birthday = PreplacedengerBirthday;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Birthday = DriverBirthday;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersMarried();
                    DriverShouldBeArrested = false;
                    PreplacedengerShouldBeArrested = false;
                }
                else if (roll == 1)
                {
                    DateTime DriverBirthday = DriverPersona.Birthday;
                    DateTime PreplacedengerBirthday = PreplacedengerPersona.Birthday;
                    while (GetAge(DriverBirthday) < 25) { DriverBirthday = DriverBirthday.AddYears(-1); }
                    while (GetAge(PreplacedengerBirthday) - GetAge(DriverBirthday) > 4) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(1); GameFiber.Yield(); }
                    while (GetAge(DriverBirthday) - GetAge(PreplacedengerBirthday) > 4) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(-1); GameFiber.Yield(); }
                    PreplacedengerPersona.Birthday = PreplacedengerBirthday;
                    PreplacedengerPersona.Wanted = true;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Birthday = DriverBirthday;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersMarried();
                    DriverShouldBeArrested = false;
                    PreplacedengerShouldBeArrested = true;
                }
                else if (roll == 2)
                {
                    DateTime DriverBirthday = DriverPersona.Birthday;
                    DateTime PreplacedengerBirthday = PreplacedengerPersona.Birthday;
                    while (GetAge(DriverBirthday) < 25) { DriverBirthday = DriverBirthday.AddYears(-1); }
                    while (GetAge(PreplacedengerBirthday) - GetAge(DriverBirthday) > 4) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(1); GameFiber.Yield(); }
                    while (GetAge(DriverBirthday) - GetAge(PreplacedengerBirthday) > 4) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(-1); GameFiber.Yield(); }
                    PreplacedengerPersona.Birthday = PreplacedengerBirthday;
                    
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Birthday = DriverBirthday;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    DriverPersona.Wanted = true;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = false;
                }
                else if (roll == 3)
                {
                    DateTime DriverBirthday = DriverPersona.Birthday;
                    DateTime PreplacedengerBirthday = PreplacedengerPersona.Birthday;
                    while (GetAge(DriverBirthday) < 25) { DriverBirthday = DriverBirthday.AddYears(-1); }
                    while (GetAge(PreplacedengerBirthday) - GetAge(DriverBirthday) > 4) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(1); GameFiber.Yield(); }
                    while (GetAge(DriverBirthday) - GetAge(PreplacedengerBirthday) > 4) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(-1); GameFiber.Yield(); }
                    PreplacedengerPersona.Birthday = PreplacedengerBirthday;
                    PreplacedengerPersona.Wanted = true;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Birthday = DriverBirthday;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    DriverPersona.Wanted = true;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = true;
                }
                else
                {
                    PreplacedengerPersona.Wanted = false;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Wanted = false;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersNotMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = true;
                }
            }
            else
            {
                int roll = replacedortedCalloutsHandler.rnd.Next(5);
                
                Game.LogTrivial("Hookedothervehicles true, roll " + roll.ToString());
                if (roll == 0)
                {
                    PreplacedengerPersona.Wanted = false;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Wanted = false;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersNotMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = true;

                }
                else if (roll == 1)
                {
                    PreplacedengerPersona.Wanted = true;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Wanted = true;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersNotMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = true;

                }
                else if (roll == 2)
                {
                    PreplacedengerPersona.Wanted = false;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Wanted = true;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersNotMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = true;

                }
                else if (roll == 3)
                {
                    PreplacedengerPersona.Wanted = true;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Wanted = false;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersNotMarried();
                    DriverShouldBeArrested = true;
                    PreplacedengerShouldBeArrested = true;

                }
                else
                {
                    DateTime DriverBirthday = DriverPersona.Birthday;
                    DateTime PreplacedengerBirthday = PreplacedengerPersona.Birthday;
                    while (GetAge(DriverBirthday) < 26) { DriverBirthday = DriverBirthday.AddYears(-1); }
                    while (GetAge(PreplacedengerBirthday) - GetAge(DriverBirthday) > 3) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(1); GameFiber.Yield(); }
                    while (GetAge(DriverBirthday) - GetAge(PreplacedengerBirthday) > 3) { PreplacedengerBirthday = PreplacedengerBirthday.AddYears(-1); GameFiber.Yield(); }

                    PreplacedengerPersona.Birthday = PreplacedengerBirthday;
                    PreplacedengerPersona.Wanted = true;
                    Functions.SetPersonaForPed(Preplacedenger, PreplacedengerPersona);
                    DriverPersona.Wanted = false;
                    DriverPersona.ELicenseState = ELicenseState.Valid;
                    DriverPersona.Birthday = DriverBirthday;
                    Functions.SetPersonaForPed(Driver, DriverPersona);
                    GetDriverAndPreplacedengerAnswersMarried();
                    DriverShouldBeArrested = false;
                    PreplacedengerShouldBeArrested = true;
                }
            }
        }

19 View Source File : DateTimeAxis.cs
License : MIT License
Project Creator : AlexGyver

private IList<double> CreateDateTickValues(
            double min, double max, double step, DateTimeIntervalType intervalType)
        {
            DateTime start = ToDateTime(min);
            switch (intervalType)
            {
                case DateTimeIntervalType.Weeks:

                    // make sure the first tick is at the 1st day of a week
                    start = start.AddDays(-(int)start.DayOfWeek + (int)this.FirstDayOfWeek);
                    break;
                case DateTimeIntervalType.Months:

                    // make sure the first tick is at the 1st of a month
                    start = new DateTime(start.Year, start.Month, 1);
                    break;
                case DateTimeIntervalType.Years:

                    // make sure the first tick is at Jan 1st
                    start = new DateTime(start.Year, 1, 1);
                    break;
            }

            // Adds a tick to the end time to make sure the end DateTime is included.
            DateTime end = ToDateTime(max).AddTicks(1);

            DateTime current = start;
            var values = new Collection<double>();
            double eps = step * 1e-3;
            DateTime minDateTime = ToDateTime(min - eps);
            DateTime maxDateTime = ToDateTime(max + eps);
            while (current < end)
            {
                if (current > minDateTime && current < maxDateTime)
                {
                    values.Add(ToDouble(current));
                }

                switch (intervalType)
                {
                    case DateTimeIntervalType.Months:
                        current = current.AddMonths((int)Math.Ceiling(step));
                        break;
                    case DateTimeIntervalType.Years:
                        current = current.AddYears((int)Math.Ceiling(step));
                        break;
                    default:
                        current = current.AddDays(step);
                        break;
                }
            }

            return values;
        }

19 View Source File : CertificatesController.cs
License : MIT License
Project Creator : alexyz79

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Issue (
            string requestId, string preplacedword, string code) {
            if (string.IsNullOrEmpty (requestId)) {
                return NotFound ();
            }

            var request = await DBContext.CertificateRequest
                .Include (s => s.Reviewer)
                .SingleOrDefaultAsync (m => m.Uuid == requestId);

            if (request == null) {
                return NotFound ();
            }

            if (code != request.SecurityCode) {
                return RedirectToAction ("RequestExpired");
            }

            var now = DateTime.UtcNow.Date;

            var certificate = new Certificate ();

            certificate.Uuid = Guid.NewGuid ().ToString ();
            certificate.CreationDate = now;
            certificate.ExpireDate = now.AddYears (1);
            certificate.Revoked = false;
            certificate.ReviewerUuid = request.ReviewerUuid;
            certificate.ReviewerName = request.Reviewer.Name;
            certificate.ReviewerEmail = request.Reviewer.Email;

            DistinguishedName dn = new DistinguishedName ();

            dn.CommonName = request.Reviewer.Name;
            dn.Email = request.Reviewer.Email;
            dn.Organization = TrustManager.IssuerDN.Organization;
            dn.OrganizationalUnit = TrustManager.IssuerDN.OrganizationalUnit;
            dn.Country = TrustManager.IssuerDN.Country;
            dn.Locality = TrustManager.IssuerDN.Locality;
            dn.State = TrustManager.IssuerDN.State;

            var x509certificate = TrustManager.IssueCertificate (
                certificate.Uuid.ToString (),
                preplacedword,
                dn,
                CertificateType.ReviewerCertificate,
                now, now.AddYears (1));

            certificate.SerialNumber = x509certificate.SerialNumber;

            DBContext.Add (certificate);
            await DBContext.SaveChangesAsync ();

            request.CertificateUuid = certificate.Uuid;
            request.Certificate = certificate;
            request.Reviewer.Certificate = certificate;

            DBContext.Update (request);
            await DBContext.SaveChangesAsync ();

            var message = await RenderService.RenderToStringAsync ("Email/CertificateIssued", request.Reviewer);
            var attachments = new List<Attachment> ();

            attachments.Add (
                await EmailManager.LoadAttachment (
                    TrustManager.CertificatePath (
                        certificate.Uuid,
                        CertificateType.ReviewerCertificate,
                        StoreFormat.P12Store), "private.p12", "application/x-pkcs12"));

            attachments.Add (
                await EmailManager.LoadAttachment (
                    TrustManager.CertificatePath (
                        certificate.Uuid,
                        CertificateType.ReviewerCertificate,
                        StoreFormat.CRT), "public.crt", "application/x-x509-ca-cert"));

            attachments.Add (
                await EmailManager.LoadAttachment (
                    TrustManager.CertificatePath (
                        "root",
                        CertificateType.AuthorityCertificate,
                        StoreFormat.CRT), "authority.crt", "application/x-x509-ca-cert"));

            var response = await EmailManager.SendEmailHTML (
                message,
                EmailManager.Sender,
                request.Reviewer.Email,
                "Your new certificate is ready",
                attachments
            );

            if (!response.Successful)
                return View ("ErrorSendingCertificate");

            return RedirectToAction (nameof (CertificateSent));
        }

19 View Source File : TrustManager.cs
License : MIT License
Project Creator : alexyz79

private static X509Certificate2 SetupRootCertificate () {

            var certPreplacedword = Configuration.GetValue<string> ("TrustManager:Preplacedword", "default preplacedword");
   
            IssuerDN = new DistinguishedName () {
                CommonName = Configuration.GetValue<string> ("TrustManager:CommonName", "Certificate Authority Root"),
                Organization = Configuration.GetValue<string> ("TrustManager:Org", "Your Organization"),
                OrganizationalUnit = Configuration.GetValue<string> ("TrustManager:OrgUnit", "Your Organizational Unit"),
                Locality = Configuration.GetValue<string> ("TrustManager:Locality", "Your Locality"),
                Country = Configuration.GetValue<string> ("TrustManager:Country", "Your Country"),
                State = Configuration.GetValue<string> ("TrustManager:State", "Your State"),
                Email = Configuration.GetValue<string> ("TrustManager:Email", "Your Email")
            };

            if (!File.Exists (AuthorityPrivateCertificatesPath + "root.pfx")) {

                DateTime now = DateTime.UtcNow.Date;
        
                var defaultYears = Configuration.GetValue<int> ("TrustManager:Years", 50);

                return IssueCertificate (
                    "root",
                    certPreplacedword,
                    IssuerDN,
                    CertificateType.AuthorityCertificate,
                    now,
                    now.AddYears (defaultYears));
            }

            return LoadCertificate (
                "root",
                certPreplacedword,
                CertificateType.AuthorityCertificate,
                StoreFormat.PFX);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : alexyz79

public static void Main(string[] args)
        {
            var build = WebHost.CreateDefaultBuilder(args);            
     
            Environment = build.GetSetting("environment");
            
            var builder  = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile($"appsettings.{Environment}.json", optional: false);
            
            Configuration = builder.Build();
            TrustManager.Init(Configuration);
            EmailManager.Init(Configuration);
            FileManager.Init(Configuration);

            DateTime now = DateTime.UtcNow.Date;

            if ( !TrustManager
                        .CertificateAvailable(
                            "webserver",CertificateType.ServerCertificate,StoreFormat.PFX)) {
                
                ServerDN = new DistinguishedName();

                ServerDN.CommonName = Configuration["WebServer:ServerCertificate:CommonName"];
                ServerDN.Organization = Configuration["WebServer:ServerCertificate:Org"];
                ServerDN.OrganizationalUnit = Configuration["WebServer:ServerCertificate:OrgUnit"];
                ServerDN.Locality = Configuration["WebServer:ServerCertificate:Locality"];
                ServerDN.Country = Configuration["WebServer:ServerCertificate:Country"];
                ServerDN.State = Configuration["WebServer:ServerCertificate:State"];
                ServerDN.Email = Configuration["WebServer:ServerCertificate:Email"];                
                
                ServerCertificate = TrustManager.IssueCertificate(
                                                                "webserver", 
                                                                Configuration["WebServer:ServerCertificate:Preplacedword"],
                                                                ServerDN,
                                                                CertificateType.ServerCertificate,
                                                                now,
                                                                now.AddYears(50));
            } else {
                ServerCertificate = TrustManager.LoadCertificate(
                                                                "webserver",
                                                                Configuration["WebServer:ServerCertificate:Preplacedword"],
                                                                CertificateType.ServerCertificate,
                                                                StoreFormat.PFX);
            }            

            if ( !TrustManager
                        .CertificateAvailable(
                            "administrator",CertificateType.AdministratorCertificate,StoreFormat.PFX)) {
                
                AdministratorDN = new DistinguishedName();

                AdministratorDN.CommonName = Configuration["WebServer:AdministratorCertificate:CommonName"];
                AdministratorDN.Organization = Configuration["WebServer:AdministratorCertificate:Org"];
                AdministratorDN.OrganizationalUnit = Configuration["WebServer:AdministratorCertificate:OrgUnit"];
                AdministratorDN.Locality = Configuration["WebServer:AdministratorCertificate:Locality"];
                AdministratorDN.Country = Configuration["WebServer:AdministratorCertificate:Country"];
                AdministratorDN.State = Configuration["WebServer:AdministratorCertificate:State"];
                AdministratorDN.Email = Configuration["WebServer:AdministratorCertificate:Email"];                
                
                AdministratorCertificate = 
                            TrustManager.IssueCertificate(
                                                        "administrator", 
                                                        Configuration["WebServer:AdministratorCertificate:Preplacedword"],
                                                        AdministratorDN,
                                                        CertificateType.AdministratorCertificate,
                                                        now,
                                                        now.AddYears(50));
            } else {
                AdministratorCertificate = 
                            TrustManager.LoadCertificate(
                                                        "administrator", 
                                                        Configuration["WebServer:AdministratorCertificate:Preplacedword"],
                                                        CertificateType.AdministratorCertificate,
                                                        StoreFormat.PFX);
            }

            var kestrelopts = new KestrelServerOptions();
            var adapterOptions = new HttpsConnectionAdapterOptions();

            adapterOptions.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
            adapterOptions.ClientCertificateValidation = TrustManager.ValidateCertificate;
            adapterOptions.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
            adapterOptions.ServerCertificate = Program.ServerCertificate;
            
            var host = build
                .UseKestrel(options => {
                    options.Listen(IPAddress.Any, Port, 
                                        listenOptions => {
                                            listenOptions
                                            .UseHttps(adapterOptions);
                                        });
                                }
                ) 
                .UseStartup<Startup>()
                .Build();
                host.Run();
        }

19 View Source File : FakerGenerator.cs
License : MIT License
Project Creator : alfa-laboratory

public DateTime? GetDate(int day, int month, int year, bool future = true, DateTime? refDate = null)
        {
            var trigger = 1;
            if (!future) trigger = -1;

            refDate ??= DateTimeHelper.Value.GetDateTimeNow();

            if (day >= 0 && month >= 0 && year >= 0)
            {
                try
                {
                    return refDate?
                        .AddDays((trigger) * day)
                        .AddMonths((trigger) * month)
                        .AddYears((trigger) * year);
                }catch(ArgumentOutOfRangeException ex)
                {
                    Log.Logger().LogWarning($"Date {day}.{month}.{year} is incorrect. Exception is {ex.Message}");
                    return null;
                }
            }
            Log.Logger().LogWarning($"Use only positive numbers when specifying a date other than the specified date.");
            return null;
        }

19 View Source File : ApplicationServicesTests.cs
License : MIT License
Project Creator : AlphaYu

[Fact]
        public async Task TesUserAppService()
        {
            var user6 = new UserSaveInputDto()
            {
                ID =17,
                Account = SecurityHelper.GenerateRandomCode(6),
                Avatar = "",
                Birthday = DateTime.Now.AddYears(-20),
                DeptId = 25,
                Email = "[email protected]",
                Name = "王大户",
                Preplacedword = "123321",
                Phone = "",
                Sex = 1
            };
            var result6 = await _userAppService.Save(user6);
            replacedert.Equal(1, result6);

            var reuslt5 = await _userAppService.GetPaged(new UserSearchDto() { PageIndex = 0, PageSize = 100 });
            replacedert.NotEmpty(reuslt5.Data);

            var result4 = await _userAppService.SetRole(new RoleSetInputDto { ID = 17, RoleIds = "2,3," });
            replacedert.Equal(1, result4);

            var result3 = await _userAppService.ChangeStatus(17);
            replacedert.Equal(1, result3);

            var result2 = await _userAppService.Delete(17);
            replacedert.Equal(1, result2);

            var user1 = new UserSaveInputDto()
            {
                Account = SecurityHelper.GenerateRandomCode(6),
                Avatar = "",
                Birthday = DateTime.Now.AddYears(-20),
                DeptId = 25,
                Email = "[email protected]",
                Name = "王大户",
                Preplacedword = "123321",
                Phone = "",
                Sex = 1
            };
            var result1 = await _userAppService.Save(user1);
            replacedert.Equal(1,result1);
        }

19 View Source File : DateExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static int CalculateAge(this DateTime birthdate)
        {
            var age = DateTime.Today.Year - birthdate.Year;
            // Subtract a year if the birthday has not happened yet this year
            // https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c
            if (birthdate > DateTime.Today.AddYears(-age))
            {
                age--;
            }
            return age;
        }

19 View Source File : DateExtensionsTests.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void CalculateAge_Returns_Correct_Age_If_Birthday_Has_Happened_This_Year()
        {
            // Arrange
            var birthdate = DateTime.Today.AddMonths(1);
            birthdate = birthdate.AddYears(-5);

            // Act
            var result = birthdate.CalculateAge();

            // replacedert
            result.ShouldBe(4);
        }

19 View Source File : DateExtensionsTests.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void CalculateAge_Returns_Correct_Age_If_Birthday_Has_Not_Happened_This_Year()
        {
            // Arrange
            var birthdate = DateTime.Today.AddMonths(-1);
            birthdate = birthdate.AddYears(-5);

            // Act
            var result = birthdate.CalculateAge();

            // replacedert
            result.ShouldBe(5);
        }

19 View Source File : DateOfBirthHandler.cs
License : MIT License
Project Creator : andrewlock

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
        {
            var dateOfBirthClaim = context.User.FindFirstValue(ClaimTypes.DateOfBirth);

            if (dateOfBirthClaim == null)
            {
                return Task.CompletedTask;
            }

            var dateOfBirth = Convert.ToDateTime(dateOfBirthClaim);
            var cutoff = dateOfBirth.AddYears(requirement.MinimumAge);

            if(cutoff < DateTime.Today)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }

19 View Source File : EmployeeValidation.cs
License : MIT License
Project Creator : Andyhacool

protected static bool HaveMinimumAge(DateTime birthDate)
        {
            return birthDate <= DateTime.Now.AddYears(-18);
        }

19 View Source File : ChartElement.cs
License : MIT License
Project Creator : AngeloCresta

internal static double GetIntervalSize(
			double current, 
			double interval, 
			DateTimeIntervalType type, 
			Series series,
			double intervalOffset, 
			DateTimeIntervalType intervalOffsetType,
			bool forceIntIndex,
			bool forceAbsInterval)
		{
			// AxisName is not date.
			if( type == DateTimeIntervalType.Number || type == DateTimeIntervalType.Auto )
			{
				return interval;
			}

			// Special case for indexed series
			if(series != null && series.IsXValueIndexed)
			{
				// Check point index
				int pointIndex = (int)Math.Ceiling(current - 1);
				if(pointIndex < 0)
				{
					pointIndex = 0;
				}
				if(pointIndex >= series.Points.Count || series.Points.Count <= 1)
				{
					return interval;
				}

				// Get starting and ending values of the closest interval
				double		adjuster = 0;
				double		xValue = series.Points[pointIndex].XValue;
				xValue = AlignIntervalStart(xValue, 1, type, null);
				double		xEndValue = xValue + GetIntervalSize(xValue, interval, type);
				xEndValue += GetIntervalSize(xEndValue, intervalOffset, intervalOffsetType);
				xValue += GetIntervalSize(xValue, intervalOffset, intervalOffsetType);
				if(intervalOffset < 0)
				{
					xValue = xValue + GetIntervalSize(xValue, interval, type);
					xEndValue = xEndValue + GetIntervalSize(xEndValue, interval, type);
				}

				// The first point in the series
				if(pointIndex == 0 && current < 0)
				{
					// Round the first point value depending on the interval type
					DateTime	dateValue = DateTime.FromOADate(series.Points[pointIndex].XValue);
					DateTime	roundedDateValue = dateValue;
					switch(type)
					{
						case(DateTimeIntervalType.Years): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Months): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Days): // Ignore hours,...
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;

						case(DateTimeIntervalType.Hours): //
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, dateValue.Hour, 
								dateValue.Minute, 0);
							break;

						case(DateTimeIntervalType.Minutes):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, 
								dateValue.Day, 
								dateValue.Hour, 
								dateValue.Minute, 
								dateValue.Second);
							break;

						case(DateTimeIntervalType.Seconds):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, 
								dateValue.Day, 
								dateValue.Hour, 
								dateValue.Minute, 
								dateValue.Second,
								0);
							break;

						case(DateTimeIntervalType.Weeks):
							roundedDateValue = new DateTime(dateValue.Year, 
								dateValue.Month, dateValue.Day, 0, 0, 0);
							break;
					}

					// The first point value is exactly on the interval boundaries
					if(roundedDateValue.ToOADate() == xValue || roundedDateValue.ToOADate() == xEndValue)
					{
						return - current + 1;
					}
				}

				// Adjuster of 0.5 means that position should be between points
				++pointIndex;
				while(pointIndex < series.Points.Count)
				{
					if(series.Points[pointIndex].XValue >= xEndValue)
					{
						if(series.Points[pointIndex].XValue > xEndValue && !forceIntIndex)
						{
							adjuster = -0.5;
						}
						break;
					}

					++pointIndex;
				}

				// If last point outside of the max series index
				if(pointIndex == series.Points.Count)
				{
					pointIndex += series.Points.Count/5 + 1;
				}

				double size = (pointIndex + 1) - current + adjuster;
		
				return (size != 0) ? size : interval;
			}
	
			// Non indexed series
			else
			{
				DateTime	date = DateTime.FromOADate(current);
				TimeSpan	span = new TimeSpan(0);

				if(type == DateTimeIntervalType.Days)
				{
					span = TimeSpan.FromDays(interval);
				}
				else if(type == DateTimeIntervalType.Hours)
				{
					span = TimeSpan.FromHours(interval);
				}
				else if(type == DateTimeIntervalType.Milliseconds)
				{
					span = TimeSpan.FromMilliseconds(interval);
				}
				else if(type == DateTimeIntervalType.Seconds)
				{
					span = TimeSpan.FromSeconds(interval);
				}
				else if(type == DateTimeIntervalType.Minutes)
				{
					span = TimeSpan.FromMinutes(interval);
				}
				else if(type == DateTimeIntervalType.Weeks)
				{
					span = TimeSpan.FromDays(7.0 * interval);
				}
				else if(type == DateTimeIntervalType.Months)
				{
					// Special case handling when current date points 
					// to the last day of the month
					bool lastMonthDay = false;
					if(date.Day == DateTime.DaysInMonth(date.Year, date.Month))
					{
						lastMonthDay = true;
					}

					// Add specified amount of months
					date = date.AddMonths((int)Math.Floor(interval));
					span = TimeSpan.FromDays(30.0 * ( interval - Math.Floor(interval) ));

					// Check if last month of the day was used
					if(lastMonthDay && span.Ticks == 0)
					{
						// Make sure the last day of the month is selected
						int daysInMobth = DateTime.DaysInMonth(date.Year, date.Month);
						date = date.AddDays(daysInMobth - date.Day);
					}
				}
				else if(type == DateTimeIntervalType.Years)
				{
					date = date.AddYears((int)Math.Floor(interval));
					span = TimeSpan.FromDays(365.0 * ( interval - Math.Floor(interval) ));
				}

				// Check if an absolute interval size must be returned
				double result = date.Add(span).ToOADate() - current;
				if(forceAbsInterval)
				{
					result = Math.Abs(result);
				}
				return result;
			}
		}

19 View Source File : StudentValidation.cs
License : MIT License
Project Creator : anjoy8

protected static bool HaveMinimumAge(DateTime birthDate)
        {
            return birthDate <= DateTime.Now.AddYears(-14);
        }

19 View Source File : CheckoutViewModel.cs
License : MIT License
Project Creator : anjoy8

public override async Task InitializeAsync(object navigationData)
        {
            if (navigationData is ObservableCollection<Baskereplacedem>)
            {
                IsBusy = true;

                // Get navigation data
                var orderItems = ((ObservableCollection<Baskereplacedem>)navigationData);

                OrderItems = orderItems;

                var authToken = _settingsService.AuthAccessToken;
                var userInfo = await _userService.GetUserInfoAsync(authToken);

                // Create Shipping Address
                ShippingAddress = new Address
                {
                    Id = !string.IsNullOrEmpty(userInfo?.UserId) ? new Guid(userInfo.UserId) : Guid.NewGuid(),
                    Street = userInfo?.Street,
                    ZipCode = userInfo?.ZipCode,
                    State = userInfo?.State,
                    Country = userInfo?.Country,
                    City = userInfo?.Address
                };

                // Create Payment Info
                var paymentInfo = new PaymentInfo
                {
                    CardNumber = userInfo?.CardNumber,
                    CardHolderName = userInfo?.CardHolder,
                    CardType = new CardType { Id = 3, Name = "MasterCard" },
                    SecurityNumber = userInfo?.CardSecurityNumber
                };

                // Create new Order
                Order = new Order
                {
                    BuyerId = userInfo.UserId,
                    OrderItems = CreateOrderItems(orderItems),
                    OrderStatus = OrderStatus.Submitted,
                    OrderDate = DateTime.Now,
                    CardHolderName = paymentInfo.CardHolderName,
                    CardNumber = paymentInfo.CardNumber,
                    CardSecurityNumber = paymentInfo.SecurityNumber,
                    CardExpiration = DateTime.Now.AddYears(5),
                    CardTypeId = paymentInfo.CardType.Id,
                    ShippingState = _shippingAddress.State,
                    ShippingCountry = _shippingAddress.Country,
                    ShippingStreet = _shippingAddress.Street,
                    ShippingCity = _shippingAddress.City,
                    ShippingZipCode = _shippingAddress.ZipCode,
                    Total = CalculateTotal(CreateOrderItems(orderItems))
                };

                if (_settingsService.UseMocks)
                {
                    // Get number of orders
                    var orders = await _orderService.GetOrdersAsync(authToken);

                    // Create the OrderNumber
                    Order.OrderNumber = orders.Count + 1;
                    RaisePropertyChanged(() => Order);
                }

                IsBusy = false;
            }
        }

19 View Source File : NewOrderCommandHandlerTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
        public async Task Handle_return_false_if_order_is_not_persisted()
        {
            var buyerId = "1234";

            var fakeOrderCmd = FakeOrderRequestWithBuyer(new Dictionary<string, object>
            { ["cardExpiration"] = DateTime.Now.AddYears(1) });

            _orderRepositoryMock.Setup(orderRepo => orderRepo.GetAsync(It.IsAny<int>()))
               .Returns(Task.FromResult<Order>(FakeOrder()));

            _orderRepositoryMock.Setup(buyerRepo => buyerRepo.UnitOfWork.SaveChangesAsync(default(CancellationToken)))
                .Returns(Task.FromResult(1));

            _idenreplacedyServiceMock.Setup(svc => svc.GetUserIdenreplacedy()).Returns(buyerId);

            var LoggerMock = new Mock<ILogger<CreateOrderCommandHandler>>();
            //Act
            var handler = new CreateOrderCommandHandler(_mediator.Object, _orderingIntegrationEventService.Object, _orderRepositoryMock.Object, _idenreplacedyServiceMock.Object, LoggerMock.Object);
            var cltToken = new System.Threading.CancellationToken();
            var result = await handler.Handle(fakeOrderCmd, cltToken);

            //replacedert
            replacedert.False(result);
        }

19 View Source File : NewOrderCommandHandlerTest.cs
License : MIT License
Project Creator : anjoy8

private Order FakeOrder()
        {
            return new Order("1", "fakeName", new Address("street", "city", "state", "country", "zipcode"), 1, "12", "111", "fakeName", DateTime.Now.AddYears(1));
        }

19 View Source File : BuyerAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void add_payment_success()
    {        
        //Arrange    
        var cardTypeId = 1;
        var alias = "fakeAlias";
        var cardNumber = "124";
        var securityNumber = "1234";
        var cardHolderName = "FakeHolderNAme";
        var expiration = DateTime.Now.AddYears(1);
        var orderId = 1;
        var name = "fakeUser";
        var idenreplacedy = new Guid().ToString();
        var fakeBuyerItem = new Buyer(idenreplacedy, name);

        //Act
        var result = fakeBuyerItem.VerifyOrAddPaymentMethod(cardTypeId, alias, cardNumber, securityNumber, cardHolderName, expiration, orderId);

        //replacedert
        replacedert.NotNull(result);
    }

19 View Source File : BuyerAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void create_payment_method_success()
    {
        //Arrange    
        var cardTypeId = 1;
        var alias = "fakeAlias";
        var cardNumber = "124";
        var securityNumber = "1234";
        var cardHolderName = "FakeHolderNAme";
        var expiration = DateTime.Now.AddYears(1);
        var fakePaymentMethod = new PaymentMethod(cardTypeId, alias, cardNumber, securityNumber, cardHolderName, expiration);

        //Act
        var result = new PaymentMethod(cardTypeId, alias, cardNumber, securityNumber, cardHolderName, expiration);

        //replacedert
        replacedert.NotNull(result);
    }

19 View Source File : BuyerAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void create_payment_method_expiration_fail()
    {
        //Arrange    
        var cardTypeId = 1;
        var alias = "fakeAlias";
        var cardNumber = "124";
        var securityNumber = "1234";
        var cardHolderName = "FakeHolderNAme";
        var expiration = DateTime.Now.AddYears(-1);        

        //Act - replacedert
        replacedert.Throws<OrderingDomainException>(() => new PaymentMethod(cardTypeId, alias, cardNumber, securityNumber, cardHolderName, expiration));
    }

19 View Source File : BuyerAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void payment_method_isEqualTo()
    {
        //Arrange    
        var cardTypeId = 1;
        var alias = "fakeAlias";
        var cardNumber = "124";
        var securityNumber = "1234";
        var cardHolderName = "FakeHolderNAme";
        var expiration = DateTime.Now.AddYears(1);

        //Act
        var fakePaymentMethod = new PaymentMethod(cardTypeId, alias, cardNumber, securityNumber, cardHolderName, expiration);
        var result = fakePaymentMethod.IsEqualTo(cardTypeId, cardNumber, expiration);

        //replacedert
        replacedert.True(result);
    }

19 View Source File : BuyerAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void Add_new_PaymentMethod_raises_new_event()
    {
        //Arrange    
        var alias = "fakeAlias";
        var orderId = 1;
        var cardTypeId = 5;
        var cardNumber = "12";
        var cardSecurityNumber = "123";
        var cardHolderName = "FakeName";
        var cardExpiration = DateTime.Now.AddYears(1);
        var expectedResult = 1;
        var name = "fakeUser";

        //Act 
        var fakeBuyer = new Buyer(Guid.NewGuid().ToString(), name);
        fakeBuyer.VerifyOrAddPaymentMethod(cardTypeId, alias, cardNumber, cardSecurityNumber, cardHolderName, cardExpiration, orderId);

        //replacedert
        replacedert.Equal(fakeBuyer.DomainEvents.Count, expectedResult);
    }

19 View Source File : OrderAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void Add_new_Order_raises_new_event()
    {
        //Arrange
        var street = "fakeStreet";
        var city = "FakeCity";
        var state = "fakeState";
        var country = "fakeCountry";
        var zipcode = "FakeZipCode";
        var cardTypeId = 5;
        var cardNumber = "12";
        var cardSecurityNumber = "123";
        var cardHolderName = "FakeName";
        var cardExpiration = DateTime.Now.AddYears(1);
        var expectedResult = 1;

        //Act 
        var fakeOrder = new Order("1", "fakeName", new Address(street, city, state, country, zipcode), cardTypeId, cardNumber, cardSecurityNumber, cardHolderName, cardExpiration);

        //replacedert
        replacedert.Equal(fakeOrder.DomainEvents.Count, expectedResult);
    }

19 View Source File : OrderAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void Add_event_Order_explicitly_raises_new_event()
    {
        //Arrange   
        var street = "fakeStreet";
        var city = "FakeCity";
        var state = "fakeState";
        var country = "fakeCountry";
        var zipcode = "FakeZipCode";
        var cardTypeId = 5;
        var cardNumber = "12";
        var cardSecurityNumber = "123";
        var cardHolderName = "FakeName";
        var cardExpiration = DateTime.Now.AddYears(1);
        var expectedResult = 2;

        //Act 
        var fakeOrder = new Order("1", "fakeName", new Address(street, city, state, country, zipcode), cardTypeId, cardNumber, cardSecurityNumber, cardHolderName, cardExpiration);
        fakeOrder.AddDomainEvent(new OrderStartedDomainEvent(fakeOrder, "fakeName", "1", cardTypeId,cardNumber,cardSecurityNumber,cardHolderName,cardExpiration));
        //replacedert
        replacedert.Equal(fakeOrder.DomainEvents.Count, expectedResult);
    }

19 View Source File : OrderAggregateTest.cs
License : MIT License
Project Creator : anjoy8

[Fact]
    public void Remove_event_Order_explicitly()
    {
        //Arrange    
        var street = "fakeStreet";
        var city = "FakeCity";
        var state = "fakeState";
        var country = "fakeCountry";
        var zipcode = "FakeZipCode";
        var cardTypeId = 5;
        var cardNumber = "12";
        var cardSecurityNumber = "123";
        var cardHolderName = "FakeName";
        var cardExpiration = DateTime.Now.AddYears(1);
        var fakeOrder = new Order("1", "fakeName", new Address(street, city, state, country, zipcode), cardTypeId, cardNumber, cardSecurityNumber, cardHolderName, cardExpiration);
        var @fakeEvent = new OrderStartedDomainEvent(fakeOrder, "1", "fakeName", cardTypeId, cardNumber, cardSecurityNumber, cardHolderName, cardExpiration);
        var expectedResult = 1;

        //Act         
        fakeOrder.AddDomainEvent(@fakeEvent);
        fakeOrder.RemoveDomainEvent(@fakeEvent);
        //replacedert
        replacedert.Equal(fakeOrder.DomainEvents.Count, expectedResult);
    }

19 View Source File : OrderingScenarios.cs
License : MIT License
Project Creator : anjoy8

string BuildCheckout(string cityExpected)
        {
            var checkoutBasket = new BasketDTO()
            {
                City = cityExpected,
                Street = "street",
                State = "state",
                Country = "coutry",
                ZipCode = "zipcode",
                CardNumber = "1111111111111",
                CardHolderName = "CardHolderName",
                CardExpiration = DateTime.Now.AddYears(1),
                CardSecurityNumber = "123",
                CardTypeId = 1,
                Buyer = "Buyer",                
                RequestId = Guid.NewGuid()
            };

            return JsonConvert.SerializeObject(checkoutBasket);
        }

19 View Source File : DateImplementation.cs
License : MIT License
Project Creator : apexsharp

public Date addYears(int years) => new DateInstance(date.AddYears(years));

See More Examples