public void ShouldRoundtripDateTimeAndDateTimeOffsetWithSameKindAndOffset() { var dates = new Dates { DateTimeUtcKind = new DateTime(2016,1,1,1,1,1,DateTimeKind.Utc), DateTimeOffset = new DateTimeOffset(1999, 1, 1, 1, 1, 1, 1, TimeSpan.FromHours(5)), DateTimeOffsetUtc = new DateTimeOffset(1999, 1, 1, 1, 1, 1, 1, TimeSpan.Zero) }; var client = new ElasticClient(); var serializedDates = client.Serializer.SerializeToString(dates,SerializationFormatting.None); serializedDates.Should() .Be("{\"dateTimeUtcKind\":\"2016-01-01T01:01:01Z\"," + "\"dateTimeOffset\":\"1999-01-01T01:01:01.001+05:00\"," + "\"dateTimeOffsetUtc\":\"1999-01-01T01:01:01.001+00:00\"}"); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(serializedDates))) { var deserializedDates = client.Serializer.Deserialize<Dates>(stream); deserializedDates.DateTimeUtcKind.Should().Be(dates.DateTimeUtcKind); deserializedDates.DateTimeUtcKind.Kind.Should().Be(dates.DateTimeUtcKind.Kind); deserializedDates.DateTimeOffset.Should().Be(dates.DateTimeOffset); deserializedDates.DateTimeOffset.Offset.Should().Be(dates.DateTimeOffset.Offset); deserializedDates.DateTimeOffset.Date.Kind.Should().Be(dates.DateTimeOffset.Date.Kind); deserializedDates.DateTimeOffsetUtc.Should().Be(dates.DateTimeOffsetUtc); deserializedDates.DateTimeOffsetUtc.Offset.Should().Be(dates.DateTimeOffsetUtc.Offset); deserializedDates.DateTimeOffsetUtc.Date.Kind.Should().Be(dates.DateTimeOffsetUtc.Date.Kind); } }
private RandomGenR() { this.dateModule = new Dates(); this.numberModule = new Numbers(); this.collectionsModule = new Collections(); this.stringsModule = new Strings(); }
public void IsValid_Should_Return_ValidationResult_When_Values_Are_Invalid() { var dates = new Dates { FirstDate = DateTime.Now, SecondDate = DateTime.Now.AddDays(-1) }; var attribute = new GreaterThanDateAttribute("FirstDate"); var context = new ValidationContext(dates, null, null); var result = attribute.GetValidationResult(dates.SecondDate, context); Assert.IsNotNull(result); }
protected void lnkBan_Click(object sender, EventArgs e) { var closeLink = (Control)sender; GridViewRow row = (GridViewRow)closeLink.NamingContainer; var id = ((TextBox)row.FindControl("txtID")).Text.Trim(); if (id == string.Empty) { return; } var hidSuspent = ((HiddenField)row.Cells[0].FindControl("hidSuspent")).Value.ToBool(); var categories = new Categories(); categories.Add(new Category { CatType = Constants.PartType, CatCode = FRType, ID = ((TextBox)row.FindControl("txtID")).Text.ToUpper(), Description = ((TextBox)row.FindControl("txtDesp")).Text, CreatedDate = Dates.ToDateTime(((HiddenField)row.FindControl("hidCreatedDate")).Value.Trim(), DateFormat.Format_01), Action = Constants.UpdateAction, Suspend = !hidSuspent }); var firstOrDefault = categories.FirstOrDefault(); if (firstOrDefault != null) { firstOrDefault.DataBaseInfo = UserContext.DataBaseInfo; } var controlPanel = new ControlPanelManager(); if (controlPanel.SetCategory(categories)) { CustomMessageControl.MessageBodyText = hidSuspent ? GlobalCustomResource.ModalityIncluded : GlobalCustomResource.ModalitySuspended; CustomMessageControl.MessageType = MessageTypes.Success; CustomMessageControl.ShowMessage(); AuditLog.LogEvent(UserContext, SysEventType.INFO, hidSuspent ? "Modality Included" : "Modality Suspended", hidSuspent ? GlobalCustomResource.ModalityIncluded : GlobalCustomResource.ModalitySuspended, true); lnkAddNew.Enabled = true; lnkAddNew.Style.Add("cursor", "Pointer"); BindData(null); } else { CustomMessageControl.MessageBodyText = hidSuspent ? GlobalCustomResource.ModalityIncludedFailed : GlobalCustomResource.ModalitySuspendedFailed; CustomMessageControl.MessageType = MessageTypes.Error; CustomMessageControl.ShowMessage(); AuditLog.LogEvent(UserContext, SysEventType.INFO, hidSuspent ? "Modality Included FAILED" : "Modality Suspended FAILED", hidSuspent ? GlobalCustomResource.ModalityIncludedFailed : GlobalCustomResource.ModalitySuspendedFailed, true); } }
public void testLiveUpdating() { O.freezeNow("2009/03/03"); // orders there on startup insertSimFilled(39, SYMBOL, "test"); insertSubmitted(39, SYMBOL, "test", "f2"); var gui = startGui(); gui.setMarket(SYMBOL); gui.wait(populateCompleted); AreEqual(gui.tracker.orderTable().count(), 2); publishFerretResponse(Dates.now(), "f2", "Accepted", "DMA"); gui.waitMatches("Market", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.NO_ACTION_REQUIRED); // new order sim filled var id = insertSimFilled(39, SYMBOL, "test"); publishAndWaitForCount(gui, id, 3); IsFalse(gui.statii.ContainsKey(latestRow(gui))); // new order submitted id = insertSubmitted(39, SYMBOL, "test", "f4"); publishAndWaitForCount(gui, id, 4); AreEqual("f4", latestRow(gui)["ferretOrderId"]); AreEqual("Submitted", latestRow(gui)["status"]); publishFerretResponse(Dates.now(), "f4", "Accepted", "DMA"); gui.waitMatches("Market", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.NO_ACTION_REQUIRED); publishFerretResponse(Dates.now(), "f4", "Executing", "DMA"); gui.waitMatches("Market", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.NO_ACTION_REQUIRED); publishFerretResponse(Dates.now(), "f4", "Accepted", "TICKET"); gui.waitMatches("Ticket", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.ACTION_REQUIRED); publishFerretResponse(Dates.now(), "f4", "Executing", "TICKET"); gui.waitMatches("Market", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.NO_ACTION_REQUIRED); publishFerretResponse(Dates.now(), "f4", "New", "UNUSED"); var stagedRow = latestRow(gui); gui.waitMatches("Stage", () => stagedRow["status"]); assertStatus(gui, OrderStatus.STAGE); publishFerretResponse(Dates.now(), "f4", "PlatformRejected", "UNUSED"); gui.waitMatches("PlatformRejected", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.FAILED); publishFerretResponse(Dates.now(), "f4", "Filled", "DMA"); gui.waitMatches("Filled", () => latestRow(gui)["status"]); assertStatus(gui, OrderStatus.SIM_MISMATCH); // submitted order updated due to sim fill var filledAt = Dates.date("1999/09/09 09:09:09"); LiveOrders.ORDERS.order(id).updateFill(12345, filledAt); publish(id); gui.waitMatches("12345.000000", () => latestRow(gui)["simFillPrice"]); assertStatus(gui, OrderStatus.NO_ACTION_REQUIRED); }
/// <summary> /// Renders the short story summary. /// </summary> /// <param name="writer">The writer.</param> protected void RenderShortSummary(HtmlTextWriter writer) { string kickStoryUrl = UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, _story.StoryIdentifier, _story.Category.CategoryIdentifier); string kickCountClass = GetKickCountClass(); // //TODO: make this CSS writer.WriteLine( @" <div style=""padding-bottom:5px;margin-bottom:10px;border-bottom: solid 1px silver;display:block"" class=""smallText""> <div style=""float:left;padding-right:15px;margin:0;width:60px;overflow:hidden;""> <div class=""storyKickCount {2}""><a href=""{0}""><span id=""{3}_KickCount"">{1}</span></a><br/><span class=""smallText"">kicks</span></div> </div> ", kickStoryUrl, _story.KickCount, kickCountClass, _story.StoryID); string publishedHtml = ""; if (_story.IsPublishedToHomepage) { publishedHtml = "published " + Dates.ReadableDiff(_story.PublishedOn, DateTime.Now) + ", "; } //TODO: remove inline style from table writer.WriteLine( @"<div class=""storySummaryMainTD xfolkentry""> <div class=""storyTitle""><a href=""{0}"" class=""taggedlink"">{1}</a> <a href=""{0}""></a></div> <div class=""storySubmitted"">{2} submitted by ", _story.Url, _story.Title, publishedHtml); UserLink userLink = new UserLink(); userLink.DataBind(UserCache.GetUser(_story.UserID)); userLink.RenderControl(writer); writer.WriteLine(@" {0}</div><div class=""storyActions"">", Dates.ReadableDiff(_story.CreatedOn, DateTime.Now)); if (_story.CommentCount == 0) { writer.WriteLine("0 comments"); } else if (_story.CommentCount == 1) { writer.WriteLine(@"1 comment"); } else { writer.WriteLine(@"{0} comments", _story.CommentCount); } writer.WriteLine("</div></div>"); }
public void August_WithDayYear() { var expectedDay = 10; var expectedYear = 2013; var target = Dates.August(expectedDay, expectedYear); target.Day.Should().Be(expectedDay); target.Year.Should().Be(expectedYear); target.Month.Should().Be(Months.August); }
private double GetHeightToday() { double[] OADates = new double[Dates.Count()]; bool didInterp; for (int i = 0; i < Dates.Count(); i++) { OADates[i] = Dates[i].ToOADate(); } return(MathUtilities.LinearInterpReal(clock.Today.ToOADate(), OADates, Heights, out didInterp) / 1000); }
public void DownloadPdf(Dates dates) { int id = Int32.Parse(User.Claims.First(c => c.Type == "UserId").Value); Report report = ReportManager.GetReport(dates, id); byte [] bytes = PdfCreator.createPDF(report); string base64 = Convert.ToBase64String(bytes); Response.ContentType = "application/pdf"; Response.Body.WriteAsync(bytes); }
public void GetDateTestNoFund() { // Arrange var date = new Dates(); var expected = "2017-09-01"; // Act var actual = date.GetDate("", "September17"); // Assert Assert.AreNotEqual(expected, (string)actual); }
public async Task <ActionResult> IndexAsync() { var meta = await AppUsers.GetCurrentAsync(this.Tenant).ConfigureAwait(true); var dates = await Dates.GetFrequencyDatesAsync(this.Tenant, meta.OfficeId).ConfigureAwait(true); var model = await OpeningCashTransactions.GetAsync(this.Tenant, meta.UserId, dates.Today).ConfigureAwait(true) ?? new OpeningCash(); return(this.FrapidView(this.GetRazorView <AreaRegistration>("Tasks/OpeningCash/Index.cshtml", this.Tenant), model)); }
protected void recacheMonthEnd(Date barDate) { if (monthEnd != null && !barDate.after(monthEnd)) { return; // monthEnd is still valid. } var firstOfCurrentMonth = Dates.date(Dates.year(barDate), Dates.monthNumber(barDate), 1); var firstOfNextMonth = Dates.monthsAhead(1, firstOfCurrentMonth); monthEnd = Dates.businessDaysAgo(1, firstOfNextMonth, financialCenter); }
public void February_WithDayYear() { var expectedDay = 10; var expectedYear = 2013; var target = Dates.February(expectedDay, expectedYear); target.Day.Should().Be(expectedDay); target.Year.Should().Be(expectedYear); target.Month.Should().Be(Months.February); }
private ListViewItem CreateRateListViewItem(Rate rate) { ListViewItem listViewItem = new ListViewItem(Dates.GetYYYYMMDD(rate.EffectiveDate)); listViewItem.ImageIndex = 0; listViewItem.SubItems.Add(rate.Amount.ToString("C")); listViewItem.Tag = rate; return(listViewItem); }
private double GetShadeModifierToday() { double[] OADates = new double[Dates.Count()]; bool didInterp; for (int i = 0; i < Dates.Count(); i++) { OADates[i] = Dates[i].ToOADate(); } return(MathUtilities.LinearInterpReal(clock.Today.ToOADate(), OADates, ShadeModifiers, out didInterp)); }
protected void lnkBan_Click(object sender, EventArgs e) { var closeLink = (Control)sender; GridViewRow row = (GridViewRow)closeLink.NamingContainer; var id = ((TextBox)row.FindControl("txtID")).Text.Trim(); if (id == string.Empty) { return; } var locations = new Locations(); var hidSuspent = ((HiddenField)row.Cells[0].FindControl("hidSuspent")).Value.ToBool(); locations.Add(new Location { Type = Type, Catg1 = Region, Catg2 = ddlRegion.SelectedItem.Text, Id = ((TextBox)row.FindControl("txtId")).Text.Trim().ToUpper(), Description = ((TextBox)row.FindControl("txtDescription")).Text, Parent = Constants.LabelWarehouse, Created = Dates.ToDateTime(((HiddenField)row.FindControl("hidCreatedDate")).Value.Trim(), DateFormat.Format_01), Suspend = !hidSuspent, Action = Constants.UpdateAction, }); var firstOrDefault = locations.FirstOrDefault(); if (firstOrDefault != null) { firstOrDefault.DataBaseInfo = UserContext.DataBaseInfo; } if (_controlPanel.SetLocation(locations)) { CustomMessageControl.MessageBodyText = hidSuspent ? GlobalCustomResource.LocationIncluded : GlobalCustomResource.LocationSuspended; CustomMessageControl.MessageType = MessageTypes.Success; CustomMessageControl.ShowMessage(); AuditLog.LogEvent(UserContext, SysEventType.INFO, hidSuspent ?"LOCATION Included": "LOCATION Suspended", hidSuspent ? GlobalCustomResource.LocationIncluded : GlobalCustomResource.LocationSuspended, true); lnkAddNew.Enabled = true; lnkAddNew.Style.Add("cursor", "Pointer"); BindData(); } else { CustomMessageControl.MessageBodyText = hidSuspent ? GlobalCustomResource.LocationIncludedFailed : GlobalCustomResource.LocationSuspendedFailed; CustomMessageControl.MessageType = MessageTypes.Error; CustomMessageControl.ShowMessage(); AuditLog.LogEvent(UserContext, SysEventType.INFO, hidSuspent ? "LOCATION Included FAILED" : "LOCATION Suspended FAILED", hidSuspent ? GlobalCustomResource.LocationIncludedFailed : GlobalCustomResource.LocationSuspendedFailed, true); } }
public override int GetHashCode() { unchecked { var hashCode = (BaseShowId != null ? BaseShowId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Dates != null ? Dates.GetHashCode() : 0); hashCode = (hashCode * 397) ^ SeatingAllocation; return(hashCode); } }
public string AccessDate(Dates date) { // Act var queryable = this.everyThing .Search() .AccessDate .Equal(date); // Assert return(queryable.ToString().ToLower()); }
public async Task <IActionResult> Create([Bind("date_id,date_pat_id,date_dr_id,date_date,date_time,date_pat_name,date_alpha")] Dates dates) { if (ModelState.IsValid) { _context.Add(dates); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(dates)); }
public void GetWeekBegin() { DateTime expected = "16-Dec-2013 4:50pm".ConvertToDate(DateTime.Now); DateTime actual = Dates.GetWeekBegin("16 dec 2013 16:50".ConvertToDate(DateTime.Now)); Assert.AreEqual(expected, actual); //same day is monday Assert.AreEqual("16-Dec-2013 4:50pm".ConvertToDate(DateTime.Now), Dates.GetWeekBegin("19 dec 2013 16:50".ConvertToDate(DateTime.Now))); // start with thursday, get monday Assert.AreEqual("9-Dec-2013 4:50pm".ConvertToDate(DateTime.Now), Dates.GetWeekBegin("15 dec 2013 16:50".ConvertToDate(DateTime.Now))); // start with sunday, get monday }
public async Task <IActionResult> MonitoringTicketsFilterx(string date, string ticket = "", string user = "", int status = 0) { DateTime df = Dates.ConverToDate(date, "es-DO"); var tickets = await _repository.GetTicketsAsync(MyCurrentUser.Get.OwnerId, df, true, ticket, user, false, true, 0, status); var vm = new LotterySaleView(); vm.Sales = tickets; return(PartialView("_TicketPartial", vm)); }
public ActionResult Statistics() { ViewBag.Vendors = _db.EResVendorsDropdown(); ViewBag.Databases = _db.EResDatabasesDropdown(); ViewBag.FundingSourceTypes = _db.EResFundingSourceTypeDropdown(); ViewBag.DatabaseTypes = _db.EResDatabaseTypeDropdown(); ViewBag.Years = new SelectList(Dates.GetTenYearDropdown()).Items; ViewBag.Months = new SelectList(Dates.GetMonthDropdown()).Items; return(View()); }
public void March_WithDayYear() { var expectedDay = 10; var expectedYear = 2013; var target = Dates.March(expectedDay, expectedYear); target.Day.Should().Be(expectedDay); target.Year.Should().Be(expectedYear); target.Month.Should().Be(Months.March); }
public void December_WithDayYear() { var expectedDay = 10; var expectedYear = 2013; var target = Dates.December(expectedDay, expectedYear); target.Day.Should().Be(expectedDay); target.Year.Should().Be(expectedYear); target.Month.Should().Be(Months.December); }
//public OutlineItem ItemAt(int index) //{ // return new OutlineItem(Dates[index], Values[index], index, KindOf(index)); //} public int IndexOf(DateTimeOffset date) { if (!Contains(date)) { return(-1); } else { Double dateValue = date.UtcDateTime.ToOADate(); return(Dates.IndexOf(dateValue)); } }
private void OnDateChange(object sender, DateRangeEventArgs e) { SelectEntireWeek(); Dates.Update(); if (scheduleLoaded && Groups.Latest != "") { UnloadSchedule(Dates.Previous, Groups.Latest); LoadSchedule(); } }
public static IEnumerable <Refund> Calculate( IPackageItem packageItem, IList <InvoiceDomain> packageInvoices, Func <DateRange, decimal, decimal> calculateCurrentCost) { var paidInvoiceItems = GetPaidInvoiceItems(packageItem, packageInvoices); if (!paidInvoiceItems.Any()) { yield break; // no payments. no refunds } // package item has some significant updates (cost, dates etc.) -> create a new refund if (packageItem.Version > paidInvoiceItems.Max(item => item.SourceVersion)) { // handle possible shift of package item start date before first paid invoice var refund = TryRefundBeforeFirstPaidDate(packageItem, paidInvoiceItems, calculateCurrentCost); if ((refund != null) && (refund.Amount != 0.0m)) { yield return(refund); } // always create a refund in range of first invoice to avoid // tricky cases with jagged diapasons of refunds / rejected / normal items // [--inv1--][--inv2--][--inv2--] // [--ref1--][--ref2--][--ref2--] var invoiceItemsGroups = paidInvoiceItems.GroupBy(item => item.FromDate); foreach (var paidItems in invoiceItemsGroups) { var currentRange = new DateRange( Dates.Max(packageItem.StartDate, paidItems.First().FromDate), Dates.Min(packageItem.EndDate, paidItems.First().ToDate)); // if package item date range moved into future, its start date can be greater than last invoice date // no payments now needed for new range, but we still need to refund already paid. // So set quantity and current cost to 0 and let the rest of logic flow. var quantity = Math.Max(currentRange.WeeksInclusive, 0); var currentCost = calculateCurrentCost(currentRange, quantity).Round(2); var refundAmount = CalculateRefundAmount(packageItem, currentCost, paidItems.ToList()).Round(2); if (refundAmount != 0.0m) { yield return(new Refund { StartDate = paidItems.First().FromDate, EndDate = paidItems.First().ToDate, Quantity = quantity, Amount = refundAmount }); } } } }
public IActionResult Create([FromBody] Dates item) { if (item == null) { return(BadRequest()); } _context.Dates.Add(item); _context.SaveChanges(); return(CreatedAtRoute("GetTodo", new { id = item.ID }, item)); }
public void Forget(string NPC, bool resetFriendship = true) { if (resetFriendship) { Modworks.Player.SetFriendshipPoints(NPC, 0); } Modworks.Player.SetFriendshipStatus(NPC, FriendshipStatus.Friendly); Spouses.Remove(NPC); Engagements.Remove(NPC); Divorces.Remove(NPC); Dates.Remove(NPC); }
public async Task <IActionResult> Create([Bind("Id,patient_id,date,time,name,alpha")] Dates dates) { if (ModelState.IsValid) { _context.Add(dates); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["patient_id"] = new SelectList(_context.patients, "Id", "fname", dates.patient_id); return(View(dates)); }
public override int GetHashCode() { unchecked { int result = Id.GetHashCode(); result = (result * 397) ^ (Title != null ? Title.GetHashCode() : 0); result = (result * 397) ^ (Description != null ? Description.GetHashCode() : 0); result = (result * 397) ^ (Company != null ? Company.GetHashCode() : 0); result = (result * 397) ^ (Dates != null ? Dates.GetHashCode() : 0); return(result); } }
/// <summary> /// Load data from all files /// </summary> private void LoadData() { foreach (var file in Directory.GetFiles(DataDirectory)) { var fileName = Path.GetFileNameWithoutExtension(file); var date = DateTime.Parse(fileName.Substring(FilePrefix.Length)); _rawData.Add(date, ParseDataFile(file)); } Dates.AddRange(_rawData.Keys); }
private int indexOf(DateTimeOffset date) { if (date < Since || date > Until) { return(Count - 1); } else { Double dateValue = date.UtcDateTime.ToOADate(); return(Dates.IndexOf(dateValue)); } }
protected void btnSearchFile_OnClick(object sender, EventArgs e) { Dates datets = new Dates(); if (!ValidateData()) { DivError.Visible = true; lblError.Text = "الرجاء ادخال قيم البحث"; return; } else { DivError.Visible = false; DateTime tmp; DateTime.TryParseExact(datets.HijriToGreg(txtDate.Text, "d/M/yyyy"), "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp); Response.Redirect(String.Format("SearchFile.aspx?name={0}&date={1}&category={2}&no={3}&country={4}&type={5}", txtFileName.Text, txtDate.Text, ddlField.SelectedValue, txtNo1.Text, ddlCountry.SelectedValue, ddlType.SelectedValue)); } }
protected void Button1_OnClick(object sender, EventArgs e) { Dates dates=new Dates(); Response.Write(dates.GregToHijri("14/9/2015","d/M/yyyy")); }
private bool ValidateData() { DateTime tmp; Dates datets = new Dates(); return !string.IsNullOrWhiteSpace(txtFileName.Text) || DateTime.TryParseExact(datets.HijriToGreg(txtDate.Text, "d/M/yyyy"), "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp) || !ddlField.SelectedValue.Equals("-1") || !ddlCountry.SelectedValue.Equals("-1") || !string.IsNullOrEmpty(txtNo1.Text) || !ddlType.SelectedValue.Equals("-1"); }
private void LoadData(string title="",string no="",string target="",string date="") { Dates dates=new Dates(); Database db=new Database(); Users u = Session["User"] as Users; db.AddParameter("@id", u.Id); string sql = "select *,category.title as FieldName,(select [Title] from FileTarget where id=files.[target]) as TargetName from (UserFav inner join files on (files.id=Userfav.FileId)) left join category on files.Field=category.id where UserFav.UserId=@id"; if(!string.IsNullOrWhiteSpace(title)) { sql += " and files.title like '%' + @title + '%'"; db.AddParameter("@title", title); } if (!string.IsNullOrWhiteSpace(no)) { sql += " and files.no like '%' + @no + '%'"; db.AddParameter("@no", no); } if (!string.IsNullOrWhiteSpace(target) && !target.Equals("-1")) { sql += " and files.[target]=@Field "; db.AddParameter("@Field", target); } DateTime tmp; if (DateTime.TryParseExact(dates.HijriToGreg(txtFileDate.Text, "d/M/yyyy"), "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp)) { sql += " and (day(files.fileDate)=@day and month(files.fileDate)=@month and year(files.fileDate)=@year) "; db.AddParameter("@day", tmp.Day); db.AddParameter("@month", tmp.Month); db.AddParameter("@year", tmp.Year); } if (!ddlCountry.SelectedValue.Equals("-1")) { sql += " and files.[country] = @country"; db.AddParameter("@country", ddlCountry.SelectedValue); } if (ddlSort.SelectedValue != "-1") { if (ddlSort.SelectedValue == "1") { sql += " order by files.fileDate desc"; } else if (ddlSort.SelectedValue == "2") { sql += " order by files.fileDate asc"; } else if (ddlSort.SelectedValue == "3") { sql += " order by files.Title"; } } DataTable dt = db.ExecuteDataTable(sql); Repeater1.DataSource = dt; Repeater1.DataBind(); }
private void LoadData(string title="",string no="",string target="",string date="",string country="",string type="") { Dates dates =new Dates(); Database db = new Database(); //Users u = Session["User"] as Users; // db.AddParameter("@id", u.Id); string sql; if (Session["User"] == null) { sql = "select files.*,FileTarget.title as TargetName,FileType.Title as TypeName from (files left join FileTarget on files.Target=FileTarget.id) inner join FileType on Files.Type=FileType.Id where files.[Security] in (1)"; } else { sql = "select files.*,FileTarget.title as TargetName,FileType.Title as TypeName from (files left join FileTarget on files.Target=FileTarget.id) inner join FileType on Files.Type=FileType.Id where files.[Security] in (1,2)"; } if (!string.IsNullOrWhiteSpace(title)) { sql += " and (files.title like '%' + @title + '%' or files.[No] like '%' + @title + '%' or files.[From] like '%' + @title + '%' or files.[To] like '%' + @title + '%' or files.[Desc] like '%' + @title + '%' or files.[FileKey] like '%' + @title + '%')"; db.AddParameter("@title", title); } if (!string.IsNullOrWhiteSpace(no)) { sql += " and files.no like '%' + @no + '%'"; db.AddParameter("@no", no); } if (!string.IsNullOrWhiteSpace(target) && !target.Equals("-1")) { sql += " and files.[target] = @Field"; db.AddParameter("@Field", target); } DateTime tmp; if (DateTime.TryParseExact(dates.HijriToGreg(txtFileDate.Text, "d/M/yyyy"), "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp)) { sql += " and (day(files.fileDate)=@day and month(files.fileDate)=@month and year(files.fileDate)=@year)"; db.AddParameter("@day", tmp.Day); db.AddParameter("@month", tmp.Month); db.AddParameter("@year", tmp.Year); } if (!string.IsNullOrWhiteSpace(country) && !country.Equals("-1")) { sql += " and files.[country] = @country"; db.AddParameter("@country", country); } if (!string.IsNullOrWhiteSpace(type) && !type.Equals("-1")) { sql += " and files.[type] = @type"; db.AddParameter("@type", type); } if (ddlSort.SelectedValue != "-1") { if (ddlSort.SelectedValue == "1") { sql += " order by files.fileDate desc"; } else if (ddlSort.SelectedValue == "2") { sql += " order by files.fileDate asc"; } else if (ddlSort.SelectedValue == "3") { sql += " order by files.Title"; } } DataTable dt = db.ExecuteDataTable(sql); Repeater1.DataSource = dt; Repeater1.DataBind(); }
private DataRow CheckLogin(string username, string password) { string sql = "select * from users where username=@username"; Database db = new Database(); db.AddParameter("@username", txtUserName.Text); DataTable dt = db.ExecuteDataTable(sql); if (dt.Rows.Count == 0) { ErrorDiv.Visible = true; lblError.Text = "الرجاء التأكد من بيانات الدخول"; return null; } if (!dt.Rows[0]["password"].ToString().Equals(txtPassword.Text)) { ErrorDiv.Visible = true; lblError.Text = "الرجاء التأكد من كلمة السر"; return null; } DateTime tmp; if (!string.IsNullOrWhiteSpace(dt.Rows[0]["LockedTo"].ToString())) { tmp = DateTime.Parse(dt.Rows[0]["LockedTo"].ToString()); if (tmp.CompareTo(DateTime.Now) <= 0) { Dates dates = new Dates(); ErrorDiv.Visible = true; lblError.Text = String.Format("هذا الحساب منتهي الصلاحية الرجاء مراسلة إدارة الموقع", dates.GregToHijri(tmp.ToString("dd/MM/yyyy"), "dd/MMM/yyyy hh:mm")); return null; } } if (!dt.Rows[0]["IsActive"].ToString().Equals("True")) { ErrorDiv.Visible = true; lblError.Text = "تم ايقاف الحساب من قبل مدير الموقع"; return null; } return dt.Rows[0]; }
//Calcuation Controller Action public void CalculateAction(List<CategoryViewModel> jCategory) { foreach (var group in jCategory) { foreach (var item in group.Functions) { if (item.Function == "Input") { item.Output = InputFunctions.Output(item.Type, item.Output); OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } else { //Logic check at Column Level string colLogic = null; bool colLogicParse = true; if(group.Logic != null) { foreach (var bit in group.Logic) { var grouplastLogic = group.Logic.Last(); string grouplastLogicOperator = grouplastLogic.Operator; Logic Logic = new Logic(); colLogic = Logic.Output(jCategory, bit, group.ID, 0); Expression ex = new Expression(colLogic); try { colLogicParse = Convert.ToBoolean(ex.Evaluate()); } catch (Exception exception) { logger.Error(exception); throw new HttpException(exception.ToString()); } if (grouplastLogicOperator == "AND" && colLogicParse == false) { break; } else if (grouplastLogicOperator == "OR" && colLogicParse == true) { colLogicParse = true; break; } } } if (item.Parameter.Count > 0) { string logic = null; bool logicparse = true; string MathString = null; bool PowOpen = false; //Logic check at column level if (colLogicParse == true) { foreach (var bit in item.Logic) { var lastLogic = item.Logic.Last(); string lastLogicOperator = lastLogic.Operator; Logic Logic = new Logic(); logic = Logic.Output(jCategory, bit, group.ID, item.ID); Expression ex = new Expression(logic); try { logicparse = Convert.ToBoolean(ex.Evaluate()); } catch (Exception exception) { logger.Error(exception); throw new HttpException(exception.ToString()); } if (lastLogicOperator == "AND" && logicparse == false) { break; } else if (lastLogicOperator == "OR" && logicparse == true) { logicparse = true; break; } } } else { logicparse = false; } //Run code if logic if met at column and row level if (logicparse == true) { int paramCount = 1; foreach (var param in item.Parameter) { string jparameters = Newtonsoft.Json.JsonConvert.SerializeObject(param); logger.Debug("Column Name(" + group.ID + ") - " + group.Name + " || Row Name(" + item.ID +") - " + item.Name); if (item.Function == "Maths") { Maths Maths = new Maths(); Maths parameters = (Maths)javaScriptSerializer.Deserialize(jparameters, typeof(Maths)); MathString = Maths.Output(jparameters,jCategory,group.ID,item.ID,MathString,PowOpen); PowOpen = Maths.PowOpen(jparameters, PowOpen); if (paramCount == item.Parameter.Count) { Expression e = new Expression(MathString); var Calculation = e.Evaluate(); bool DeciParse; decimal CalculationDeci; string Rounding; DeciParse = decimal.TryParse(Convert.ToString(Calculation), out CalculationDeci); Rounding = Convert.ToString(parameters.Rounding); if (Rounding == null || Rounding == "") { Rounding = "2"; } if (DeciParse == true) { decimal Output = CalculationDeci; MathematicalFunctions MathematicalFunctions = new MathematicalFunctions(); try { Output = MathematicalFunctions.Rounding(Convert.ToString(parameters.RoundingType), Rounding, Output); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } item.Output = Convert.ToString(Output); } else { item.Output = "0"; } } paramCount = paramCount + 1; } else if (item.Function == "ErrorsWarnings") { ErrorsWarnings Errors = new ErrorsWarnings(); ErrorsWarnings parameters = (ErrorsWarnings)javaScriptSerializer.Deserialize(jparameters, typeof(ErrorsWarnings)); item.Name = parameters.Type; item.Output = parameters.String1; } else if (item.Function == "Comments") { Comments Errors = new Comments(); Comments parameters = (Comments)javaScriptSerializer.Deserialize(jparameters, typeof(Comments)); item.Output = parameters.String1; } else if (item.Function == "Period") { DateFunctions DateFunctions = new DateFunctions(); Period Periods = new Period(); try { item.Output = Periods.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "Factors") { Factors Factors = new Factors(); Factors parameters = (Factors)javaScriptSerializer.Deserialize(jparameters, typeof(Factors)); try { item.Output = Factors.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } item.Type = parameters.OutputType; } else if (item.Function == "DateAdjustment") { Dates Dates = new Dates(); try { item.Output = Dates.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "DatePart") { DatePart DateParts = new DatePart(); try { item.Output = DateParts.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "MathsFunctions") { MathsFunctions MathsFunctions = new MathsFunctions(); try { item.Output = MathsFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "ArrayFunctions") { ArrayFunctions ArrayFunctions = new ArrayFunctions(); ArrayFunctions parameters = (ArrayFunctions)javaScriptSerializer.Deserialize(jparameters, typeof(ArrayFunctions)); try { item.Output = ArrayFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } if(parameters.Function == "Count") { item.Type = "Decimal"; } else { item.Type = parameters.LookupType; } } else if (item.Function == "StringFunctions") { StringFunctions StringFunctions = new StringFunctions(); StringFunctions parameters = (StringFunctions)javaScriptSerializer.Deserialize(jparameters, typeof(StringFunctions)); try { item.Output = StringFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } if(parameters.Type == "Len") { item.Type = "Decimal"; } else { item.Type = "String"; } } } //Expected results on the builder this sets the required ones if (item.ExpectedResult == null || item.ExpectedResult == "") { item.Pass = "******"; } else if (item.ExpectedResult == item.Output) { item.Pass = "******"; } else { item.Pass = "******"; } OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } else { //Ignores the row if logic is not met dynamic LogicReplace = Config.VariableReplace(jCategory, item.Name, group.ID, item.ID); if(Convert.ToString(LogicReplace) == Convert.ToString(item.Name)) { item.Output = null; } else { item.Output = Convert.ToString(LogicReplace); } item.Pass = "******"; OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } } } } } }