DatePicker.Value.Set Error binding to datasource - entity-framework-5

I have a bindingsource control called binding, on a form in VS2012, and a DateTimePicker control bound to it.
for the binding properties I have MinDate = 1/01/1753 and MaxDate = 31/12/9998
Value has been set by picking Today from the calender 5/04/2013 11:27 AM
I set a bindingsource up using
var dset = base.Context.ContactEvents;
var qry = dset.Where(p => p.Id > 0).OrderBy(x => x.Id);
qry.Load();
this.bindingSource.DataSource = dset.Local.ToBindingList();
The bindingsource is used in the following manner;
public void RefreshBindingDataSourceAndPosition(BindingSource binding)
{
binding.DataSource = this.bindingSource.DataSource; // error raised here
binding.Position = this.bindingSource.Position;
}
The error information is
System.ArgumentOutOfRangeException crossed a native/managed boundary
HResult=-2146233086
Message=Value of '1/01/0001 12:00:00 AM' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'.
Parameter name: Value
Source=System.Windows.Forms
ParamName=Value
StackTrace:
at System.Windows.Forms.DateTimePicker.set_Value(DateTime value)
InnerException:
I can work around the problem by not binding the Data Picker , and setting it in the EventsBindingSource_CurrentChanged event
However it seems odd to have to do this. How can I get the databinding working?
[Update]
This problem is similar to the one described here
I have tried to reproduce the problem in a simpler project so as to try and isolate the cause, however it works in the simpler project. Also the project works on another computer.
The problem occurs on my computer with both SQL Server 2012 and 2008R2. I have tried altering the date format and country in control panel. Also I have tried different settings for the format property. I have also tried setting the date field to support null.
When I copy the error to the clipboard it shows the following ;
System.Reflection.TargetInvocationException occurred
HResult=-2146232828
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
InnerException: System.ArgumentOutOfRangeException
HResult=-2146233086
Message=Value of '1/01/0001 12:00:00 AM' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'.
Parameter name: Value
Source=System.Windows.Forms
ParamName=Value
StackTrace:
at System.Windows.Forms.DateTimePicker.set_Value(DateTime value)
InnerException:
My EF class is as follows
public class ContactEvent : LoggedEntity
{
public virtual SortableBindingList<ContactEventAttendee> Attendees { get; private set; }
public virtual ContactEventType ContactEventType { get; set; }
public string Details { get; set; }
public DateTime? EventTime { get; set; }
public virtual SortableBindingList<ContactEventItem> Items { get; private set; }
public int State { get; set; }
public string Title { get; set; }
public override string ToString()
{
return "Contact Events";
}
}
it inherits from
public abstract class LoggedEntity
{
public LoggedEntity()
{
this.RowId = Guid.NewGuid();
this.RowVersionId = 0;
AppDomain dm = AppDomain.CurrentDomain; // Gets the current application domain for the current Thread.
object s = AppDomain.CurrentDomain.GetData("SiteNumber");
this.SourceSiteNumber = Convert.ToInt32(s);
}
public LoggedEntity(int SiteNumber)
{
// the following 3 are used to identify the version
this.RowId = Guid.NewGuid();
this.RowVersionId = 0;
this.SourceSiteNumber = SiteNumber;
}
public int Id { get; set; }
public Guid RowId { get; set; }
[ConcurrencyCheck]
public int RowVersionId { get; set; }
public int SourceSiteNumber { get; set; }
}
[update]
A similar problem is here
[update]
Another here makes me think I need to look at how keys are being processed.
[update]
I noticed the following in the output window
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
[update]
This led me to
here
and after turning on the debug options I found an error
Invalid object name 'dbo.__MigrationHistory'.
however that is a known bug in EF5
[Update]: I found another person with similar unsolved issues here
Discovered I dont have problems when running the .EXE
[update] I can skip over the error by disabling "Break when exceptions cross App Domain or managed/native boundary
in Tools->Options->Debugging->General
[update] I adding the following, so I could inspect the control properties.
private void EventsBindingSource_BindingComplete(object sender, BindingCompleteEventArgs e)
{
// If the BindingComplete state is anything other than success,
// set the ErrorProvider to the error message.
if (e.BindingCompleteState != BindingCompleteState.Success)
{
errorProvider1.SetError((Control)e.Binding.BindableComponent, e.ErrorText);
var errdesc = e.ErrorText;
var ctrl = (Control)e.Binding.BindableComponent;
var info = string.Format(
"{0} {1}",errdesc,
ctrl.ToString());
Debug.Print(info);
// "Value of '1/1/0001 12:00:00 AM' is not valid for 'Value'.
'Value' should be between 'MinDate' and 'MaxDate'.\r\nParameter name:
Value System.Windows.Forms.DateTimePicker, Value: 1/1/1900 12:00:00 AM"
}
else
{
errorProvider1.SetError((Control)e.Binding.BindableComponent, "");
}
}

The cause of the exception may be that the DatePicker's DataBinding "Value" property has been set to a BindingSource field.
Only the DatePicker's DataBinding "Text" property needs to be set for the data binding to work correctly.
Check if there is a value in the DatePicker's DataBinding "Value" property field, once removed the issue should go away.

It seems that the key problem is the property is a Nullable DateTime. Probably the null value used to transcribe the DateTimePicker component is '1 / 01/0001 12:00:00 AM 'which creates a problem related to the configuration of MinValue and MaxValue. Using the Advanced tab of the DataBinding has an option to set the value to be used to null One way to solve this would be setting the value to null as MinDate, or we can set the MinDate with the value '01 / 01/0001 12:00 : 00 AM '. Despite my limited experience, I believe that this may be the source of your problems. the link http://msdn.microsoft.com/en-us/library/aa480734.aspx can see something else on the Advanced tab of the property DataBinding.

Related

There is no implicit reference conversion from table to ITableEntity in Azure Function

I am writing my first Azure Function and Azure table code. I am getting issue when I write Get query function. I have the following code that would try to get all the jobs from the table.
public static class GetJobStatus
{
[FunctionName("GetJobStatus")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
[Table("JobTable")] CloudTable jobTable,
ILogger log)
{
log.LogInformation("Get job status.");
string jobId = req.Query["jobid"];
TableQuery<JobTable> query = new TableQuery<JobTable>();
var segment = await jobTable.ExecuteQuerySegmentedAsync(query, null);
var data = segment.Select(JobExtension.ToJob);
return new OkObjectResult("");
}
}
But, I get compile time errors on these statements:
TableQuery<JobTable> query = new TableQuery<JobTable>();
var segment = await jobTable.ExecuteQuerySegmentedAsync(query, null);
I am trying to paste the actual error messages that appear on hover:
and, get the following on the ExecuteQuerySegmentedAsync method
My JobTable inherits from ITableEntity (Azure.Data.Tables):
public class JobTable : ITableEntity
{
public string Id { get; set; }
public DateTime CreatedTime { get; set; }
public JobRequest Request { get; set; }
//ITableEntity Members
public virtual string PartitionKey { get; set; } = "Job";
public virtual string RowKey { get => Id; set => Id = value; }
public DateTimeOffset? Timestamp { get; set; }
public ETag ETag { get; set; }
}
I have the following nuget packages installed:
I was trying to implement from this article, but it uses older nuget packages, and I was getting trouble.
Update #1:
As per the suggestions from Gaurav Mantri, to be consistent, I have removed Azure.Data.Tables and started using Microsoft.WindowsAzure.Storage.Table. That fixed the compile time errors. But now I get the following runtime error:
Microsoft.Azure.WebJobs.Host: Error indexing method 'GetJobStatus'. Microsoft.Azure.WebJobs.Extensions.Tables: Can't bind Table to type 'Microsoft.WindowsAzure.Storage.Table.CloudTable'.
Update #2:
I couldn't make it work, so I reverted all my code and references to use Microsoft.Azure.Cosmos.Table as described in the article I was referncing. Everything works as expected now. But, I still would like to see how I can use the newer libraries. For the original issue that was receiving, it was solved by Gaurav's suggestion so I will accept the answer for now.
I believe you are running into this issue is because you are using two different SDKs - Azure.Data.Tables and Microsoft.WindowsAzure.Storage.Table.
Your JobTable entity implements ITableEntity from Azure.Data.Tables and you are using that with your CloudTable from Microsoft.WindowsAzure.Storage.Table.
Can you try by removing Azure.Data.Tables package and just use Microsoft.WindowsAzure.Storage.Table?

How to interpret datetime as User's local timezone in Acumatica

We have a button "Start" that populates the dateStarted field to DateTime.Now..
When retrieving datetime, it always shows the server's date/time instead of user's local timezone version. How do i make it work like lastModifiedDateTime/CreatedDateTime that whenever we view it it's formatted as user's local timezone. I tried UseTimeZone = true/false but nothing is working
Here is my code that is not working
#region DateStarted
public abstract class dateStarted : PX.Data.IBqlField
{
}
protected DateTime? _DateStarted;
[PXDBDateAndTime(DisplayNameDate = "Date Started", DisplayNameTime = "Time", UseTimeZone = true)]
public virtual DateTime? DateStarted
{
get
{
return this._DateStarted;
}
set
{
this._DateStarted = value;
}
}
#endregion
It sounds like just using PX.Common.PXTimeZoneInfo.Now is enough to do the job.
PX.Common.PXTimeZoneInfo also has UtcNow, UtcToday, and Today if needed
Look up the code of class PXDBDateAndTime in Source Code screen SM204570. For debugging purpose you can copy the whole attribute and rename it to something else like PXDBDateAndTimeDebug:
[PXDBDateAndTimeDebug(DisplayNameDate = "Date Started", DisplayNameTime = "Time", UseTimeZone = true)]
With that approach you can debug SetUseTimeZone and GetTimeZone methods. The time zone used is coming from LocaleInfo.GetTimeZone method and you should debug that too:
public static PXTimeZoneInfo GetTimeZone()
{
if (!PXContext.PXIdentity.IsAnonymous() && PXContext.PXIdentity.TimeZone != null)
{
return PXContext.PXIdentity.TimeZone;
}
return PXTimeZoneInfo.Invariant;
}
The issue here is that from your question we can't tell if there's actually a problem with Acumatica time zone handling or if the user profile time zone is properly configured in your instance or if the result you're expecting is actually a valid ISO conversion as done by the DotNet framework. Debugging step by step should reveal what's going on.
After analyzing how CreatedDateTime and LastModifiedDatetime and other dates behave the same, the problem is in the input. So i created the following code to save the correct datetime with regards to the current user's timezone.
public static class DateTimeHelper
{
public static DateTime? Now()
{
var test = LocaleInfo.GetTimeZone();
PXTimeZoneInfo timezone = LocaleInfo.GetTimeZone();
DateTime dt = DateTime.UtcNow;
dt = PXTimeZoneInfo.ConvertTimeFromUtc(dt, timezone);
return dt;
}
}
and the implementation:
public PXAction<CQLMChecklists> startButton;
[PXUIField(DisplayName = "Start", Visible = true)]
[PXButton()]
public virtual void StartButton()
{
if (Document.Current != null)
{
CQLMChecklists doc = Document.Current;
Actions.PressSave();
CommenceChecklist(DateTimeHelper.Now(), DateTimeHelper.Now().Value, ref doc);
Document.Update(doc);
}
Actions.PressSave();
}

Entity Framework deleting object upon Update

I have a problem where Entity Framework (Core) is deleting an object upon update. I think this is related to Automapper (map DTO Resource to object). I have other objects mapped the exact same way as this object and updates work just fine.
public async Task<IActionResult> UpdateFeedback(Guid Id, [FromBody] FeedbackResource feedbackResource)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
//removing or else get a tracking error with EF
feedbackResource.FeedbackType = null;
var feedback = await feedbackRepository.GetFeedback(Id);
if (feedback == null)
return NotFound();
//if I use this line to map, EF will delete the object upon save.
mapper.Map<FeedbackResource, Feedback>(feedbackResource, feedback);
// if I map manually, i get no error
//feedback.Title = feedbackResource.Title;
//feedback.Details = feedbackResource.Details;
//feedback.IsGoodFeedback = feedbackResource.IsGoodFeedback;
//feedback.IsReviewed = feedbackResource.IsReviewed;
//feedback.FeedbackTypeId = feedbackResource.FeedbackTypeId;
//if(feedbackResource.IsReviewed){
// feedback.ReviewDate = DateTime.Now;
// feedback.ReviewedBy = UserId;
//} else {
// feedback.ReviewDate = null;
// feedback.ReviewedBy = null;
//}
await uow.CompleteAsync();
return Accepted(feedback);
}
I have no idea what to troubleshoot here and cannot see this issue on any google search.
I was faced with a similar situation (ef core 1.1). I will assume that your problem is similar to mine.
Also a similar problem is described here
I have the following models:
1) ApplicatonUser - standard user from EF
2) AnyDAL - any class in DB, which have link to user
public class AnyDAL
{
public long Id { get; set; }
public long UserId { get; set; }
public ApplicationUser User { get; set; }
}
3) AnyDTO - model that comes from the browser side. Like your's [FromBody] FeedbackResource feedbackResource
public class AnyDTO
{
public long Id { get; set; }
public long UserId { get; set; }
/// It is root of all evil. See below.
/// And yes, it is bad practice.
public ApplicationUser User { get; set; }
}
Scenario:
1) get AnyDAL from the database;
2) map AnyDTO on AnyDAL using AutoMapper _mapper.Map(DTO, DAL);
3) SaveChanges()
In one case, SaveChanges() leads to Delete, in other to Update.
What we should know: in my case property AnyDTO.User is always null after deserialization.
The choice between delete and update depends on the value of property AnyDAL.User before mapping:
1)AnyDAL.User is null - we get Update.
2)AnyDAL.User is NOT null - we get Delete.
In other words. If property AnyDAL.User changed from some value to null - entity will be deleted. Despite the fact that AnyDAL.UserId remains the same.
There is two ways to solve it:
1) Remove property User from AnyDTO;
2) Property AnyDTO.User should always has value.
For me, this issue ended up being caused by an interaction between the automapper and EntityFramework. This was described well by Automapper creating new instance rather than map properties
This is a little old but I ran into the same issue with EF Core 2.2 and based on this
EntityFrameworkCore it is still an issue in 3.0
The issue seems to be that the navigation property being null is causing the entity to be deleted.
I was able to resolve by configuring lazy loading
Install this package
Microsoft.EntityFrameworkCore.Proxies
Enable lazy loading in the configuration
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies();
for me, this was resolved if I marked as Detached the entity, use automapper to map, then mark entity as Modified.
_context.Entry(product).State = EntityState.Detached;
_mapper.Map<ProductVM, Product>(viewModelProduct, product);
_context.Entry(product).State = EntityState.Modified;
_context.SaveChanges();

ContentManager.Create does nothing

I am trying to build a service in Orchard that allows me to create content through a custom form on a page. The service and the content type definitions look fine to me, but somehow, eventhough I don't get any errors or other signs in the Orchard log files, creating new content using the IContentManager does nothing for me.
Parts involved
The controller accepting the form values
[HttpPost]
public ActionResult Create(CreateSopViewModel viewModel)
{
if(!ModelState.IsValid)
{
var shape = _shape.CreateContent();
shape.Header = _shape.Parts_Title(Title: "New item");
// Add the original fields to the shape.
shape.Title = viewModel.Title;
shape.Description = viewModel.Description;
shape.InitialComments = viewModel.InitialComments;
return new ShapeResult(this, shape);
}
// Store the new procedure in the database
_service.CreateContentItem(
viewModel.Title,viewModel.Description,viewModel.InitialComments);
// Redirect the user back to the homepage.
return Redirect("~/");
}
The service that contains the CreateContentItem method:
public void CreateContentItem(string title, string description, string initialComments)
{
// Initialize a new content item based on the SOP type
var customPart = _services.ContentManager.New<MyCustomPart>("CustomContentType");
customPart.Description = description;
customPart.Identifier = BuildIdentifier(title);
customPart.ContentItem.As<TitlePart>().Title = title;
_services.ContentManager.Create(customPart.ContentItem);
}
The content part + record
public class MyCustomPart: ContentPart<MyCustomPartRecord>
{
[Required]
public string Identifier
{
get { return Record.Identifier; }
set { Record.Identifier = value; }
}
[Required]
public string Description
{
get { return Record.Description; }
set { Record.Description = value; }
}
}
public class MyCustomPartRecord: ContentPartRecord
{
public virtual string Identifier { get; set; }
public virtual string Description { get; set; }
}
The migration
SchemaBuilder.CreateTable(typeof(MyCustomPartRecord).Name, table => table
.ContentPartRecord()
.Column<string>("Description")
.Column<string>("Identifier"));
ContentDefinitionManager.AlterPartDefinition("StandardOperationalProcedurePart", builder => builder
.Attachable(true));
ContentDefinitionManager.AlterTypeDefinition("CustomContentType", builder => builder
.DisplayedAs("Custom Content Type")
.WithPart("TitlePart")
.WithPart("MyCustomPart")
.Creatable(true));
Question
Again, I don't get any errors, not in the log and not in Visual Studio. However, my new content item doesn't get created or at least, I can't see it in the admin section of the site under Content.
What is going on and how can I debug this behavior?
I had a similar problem, which was solved when I used the overloaded Create method taking a VersionOptions enum value:
content.Create(customPart.ContentItem, VersionOptions.Published);
This should work even if the content item is not creatable, as mine isn't.
I had a similar issue. In my case the item did appear eventually, but not right away.
The solution for me was to do:
_contentManager.Flush();
I was having this issue, in my case it was that I actually had an error in the database (trying to put 100+ characters into a field that would only hold 100!).
I found the error I was getting (null id in Orchard.Indexing.Models.IndexingTaskRecord entry (don't flush the Session after an exception occurs) ), actually masked the issue. I had to go hunt in the logs to find the real problem.
So anyway, my advice is if you see that contentmanager.create seems to be doing nothing, and any errors don't seem to help, check the logs carefully. They can be found in the logs sub-folder of the appdata folder in the main Orchard.Web project. Because as I've found in the last 48 hours, often the answer is there.

Retrieving values of ReadOnly fields from DynamicData DetailsView in Edit Mode on Updating using LinqDataSource

I have several tables in my database that have read-only fields that get set on Inserting and Updating, namely: AddDate (DateTime), AddUserName (string), LastModDate (DateTime), LastModUserName (string).
All of the tables that have these values have been set to inherit from the following interface:
public interface IUserTrackTable
{
string AddUserName { get; set; }
DateTime AddDate { get; set; }
string LastModUserName { get; set; }
DateTime LastModDate { get; set; }
}
As such, I have the following method on the Edit.aspx page:
protected void DetailsDataSource_Updating(object sender, LinqDataSourceUpdateEventArgs e)
{
IUserTrackTable newObject = e.NewObject as IUserTrackTable;
if (newObject != null)
{
newObject.LastModUserName = User.Identity.Name;
newObject.LastModDate = DateTime.Now;
}
}
However, by the time it hits this method, the e.OriginalObject has already lost the values for all four fields, so a ChangeConflictException gets thrown during the actual Update. I have tried adding the four column names to the DetailsView1.DataKeyNames array in the Init event handler:
protected void Page_Init(object sender, EventArgs e)
{
// other things happen before this
var readOnlyColumns = table.Columns.Where(c => c.Attributes.SingleOrDefaultOfType<ReadOnlyAttribute>(ReadOnlyAttribute.Default).IsReadOnly).Select(c => c.Name);
DetailsView1.DataKeyNames = DetailsView1.DataKeyNames.Union<string>(readOnlyColumns).ToArray<string>();
DetailsView1.RowsGenerator = new CustomFieldGenerator(table, PageTemplates.Edit, false);
// other things happen after this
}
I've tried making that code only happen on PostBack, and still nothing. I'm at a lose for how to get the values for all of the columns to make the round-trip.
The only thing the CustomFieldGenerator is handling the ReadOnlyAttribute, following the details on C# Bits.
UPDATE: After further investigation, the values make the round trip to the DetailsView_ItemUpdating event. All of the values are present in the e.OldValues dictionary. However, they are lost by the time it gets to the LinqDataSource_Updating event.
Obviously, there are the "solutions" of making those columns not participate in Concurrency Checks or other ways that involve hard-coding, but the ideal solution would dynamically add the appropriate information where needed so that this stays as a Dynamic solution.
i Drovani, I assume you want data auditing (see Steve Sheldon's A Method to Handle Audit Fields in LINQ to SQL), I would do this in the model in EF4 you can do it like this:
partial void OnContextCreated()
{
// Register the handler for the SavingChanges event.
this.SavingChanges += new EventHandler(context_SavingChanges);
}
private static void context_SavingChanges(object sender, EventArgs e)
{
// handle auditing
AuditingHelperUtility.ProcessAuditFields(objects.GetObjectStateEntries(EntityState.Added));
AuditingHelperUtility.ProcessAuditFields(objects.GetObjectStateEntries(EntityState.Modified), InsertMode: false);
}
internal static class AuditingHelperUtility
{
internal static void ProcessAuditFields(IEnumerable<Object> list, bool InsertMode = true)
{
foreach (var item in list)
{
IAuditable entity = item as IAuditable;
if (entity != null)
{
if (InsertMode)
{
entity.InsertedBy = GetUserId();
entity.InsertedOn = DateTime.Now;
}
entity.UpdatedBy = GetUserId();
entity.UpdatedOn = DateTime.Now;
}
}
}
}
Sadly this is not possible with EF v1

Resources