How to keep focus on a field that threw an exception? - acumatica

I have some validation code for the entry of a field (EmployeeID) and when it fails validation I e.Cancel the upcoming events and throw an exception:
protected virtual void _(Events.FieldUpdating<EMPTimeEntries,EMPTimeEntries.employeeID> e)
{
DateTime timeNow = PX.Common.PXTimeZoneInfo.Now;
timeNow = timeNow.AddMinutes(-5).AddHours(4);
EMPTimeEntries alreadyScanned = SelectFrom<EMPTimeEntries>.
Where<EMPTimeEntries.employeeID.IsEqual<#P.AsString>.
And<EMPTimeEntries.clockTime.IsGreater<#P.AsDateTime>>>.
View.Select(this, e.NewValue, timeNow);
if ((alreadyScanned == null))
{
}
else
{
e.Cancel = true;
// Acuminator disable once PX1050 HardcodedStringInLocalizationMethod [Justification]
throw new PXSetPropertyException<EMPTimeEntries.employeeID>("The Employee has scanned within 5 minutes already!", PXErrorLevel.Error);
}
}
The issue is that the user input progresses though to the next field, I wish to interrupt this behavior and keep focus on the field that failed validation.
As you see in the picture above, employeeID has failed validation the exception and message are thrown, but the focus is on the Employee Name. IF keystrokes matter I typed in 54 and hit tab, I wish for the tab not to happen.
Any help greatly appreciated.

Related

Notes Window Not Updating on Bill

I am updating the Notes on a Bill via some custom code in a graph extension. My problem is that the window that pops open when you click on the Notes icon in the upper-right corner of the screen does not reflect the changes that I made to the notes in code. If I use the < > buttons to scroll to another Bill and then back to the one that I updated, it shows the changes. So, I'm not sure how to get the notes to refresh.
This is on the AP301000 screen. I have tried Base.Document.View.RequestRefresh(), Base.Document.View.Clear() and calling the Base.Actions.PressSave() after my code changes the note for the Bill.
TIA!
Here's Code:
protected void APTran_RowInserted(PXCache cache, PXRowInsertedEventArgs e)
{
var row = (APTran)e.Row;
if (row == null)
return;
//*********************** copy notes and file attachments from PO lines and header to the Bill **********************************
if ((row.PONbr != null) && (row.POLineNbr != null))
{
POOrderEntry poEntry = (POOrderEntry)PXGraph.CreateInstance(typeof(POOrderEntry));
poEntry.Clear();
POOrder poHeader = poEntry.Document.Search<POOrder.orderNbr>(row.PONbr);
poEntry.Document.Current = poHeader;
POLine poLine = poEntry.Transactions.Search<POLine.lineNbr>(row.POLineNbr);
if (poLine != null)
{
PXNoteAttribute.CopyNoteAndFiles(poEntry.Caches[typeof(POLine)], poLine, cache, row); //// - use this for Notes and Files.
// making of copy of what the note is on the APInvoice at this point because the PXNoteAttribute.CopyNoteAndFiles() below
// will replace what is in the notes with what is in the PO instead of appending.
string oldNote = PXNoteAttribute.GetNote(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current);
PXNoteAttribute.CopyNoteAndFiles(poEntry.Caches[typeof(POOrder)], poHeader, Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current);
PXNoteAttribute.SetNote(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current, oldNote);
Base.Actions.PressSave();
string poNote = PXNoteAttribute.GetNote(poEntry.Caches[typeof(POOrder)], poHeader);
if (!string.IsNullOrEmpty(poNote))
{
//string oldNote = PXNoteAttribute.GetNote(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current);
if ((oldNote == null) || !oldNote.Contains(poNote))
{
string newNote = "";
if (string.IsNullOrEmpty(oldNote))
newNote = poNote;
else
newNote = oldNote + Environment.NewLine + poNote;
//These 2 lines will not update the note without the PressSave();
//Guid noteGuid = (Guid)PXNoteAttribute.GetNoteID(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current, null);
//PXNoteAttribute.UpdateNoteRecord(Base.Caches[typeof(APInvoice)], noteGuid, newNote);
PXNoteAttribute.SetNote(Base.Caches[typeof(APInvoice)], Base.Document.Current, newNote); // Sets the note but, screen does not refresh.
//Base.Caches[typeof(APInvoice)].Update(Base.Document.Current); //Does not refresh Notes on screen.
//PXNoteAttribute.GetNoteID<APInvoice.noteID>(Base.Caches[typeof(APInvoice)], Base.Document.Current); // Does not update the screen.
//Base.Caches[typeof(Note)].IsDirty = true; /// No Effect.
//Base.Caches[typeof(Note)].Clear(); //this has no effect on refreshing the notes that are seen on the screen.
//Base.Caches[typeof(NoteDoc)].Clear();
//Base.Actions.PressSave(); // blanks out the header if the Bill has never been saved. Does not refresh note on screen.
//Base.Document.View.Clear();
//Base.Document.View.RequestRefresh(); // this wipes out the new note if adding a second PO.
}
}
}
}
}
Here's the fix for this that I deployed. I'm thinking that there is a better way to do this but, seems to be working ok for now. I added this:
[PXOverride]
public void Persist(Action persist)
{
persist();
APInvoice invoice = (APInvoice)Base.CurrentDocument.SelectSingle();
if (invoice.Status == "H")
throw new PXRedirectRequiredException(Base, "Reloading Notes...");
}
So, I overrode the Persist() in order to refresh the page but, I only do that if the Bill is still on Hold. This refreshes the Notes that are shown on the screen.

FormBuilder Code execution suddenly jumps to FormCompletion delegate

I have below code in Bot framework app.
You can see in below code I have commented ValidateStartDate delegate, the reason behind it is that if I include delegate in formflow then after the delegate execution code jumps directly to BookingComplete delegate of "context.Call(Booking, BookingComplete);" i.e end of conversation.But ideally, it should execute rest of the fields from form builder.
Note that here StartDate is of type String, and I am manually validating date part.Also, no visible exception occurs during code execution
public static IForm<ConferenceBooking> BuildForm()
{
return new FormBuilder<ConferenceBooking>().Message("Tell me meeting details!")
.Field(nameof(title))
.Field(nameof(StartDate))//, validate: ValidateStartDate
.Field(nameof(EntryTime), validate:ValidateCallTime)
.Build();
}
Below is delegate part for StartDate
private static Task<ValidateResult> ValidateStartDate(ConferenceBooking state, object response)
{
var result = new ValidateResult();
DateTime startDt = Convert.ToDateTime(GetDate(Convert.ToString(response)));
if (startDt == null || startDt == DateTime.MinValue)
{
result.IsValid = false;
result.Feedback = "I could not understand this format.";
}
else if (startDt.Date < DateTime.Now.Date)
{
result.IsValid = false;
result.Feedback = "Sorry, back dated bookings are not allowed";
}
else
{
result.IsValid = true;
result.Value = startDt;
}
return Task.FromResult(result);
}
I have also noticed this behavior before and this was always due to an exception. The FormBuilder appears to catch all exceptions and exits the form in the catch block. This is why you don't see any exceptions popping up. Try going over your code step by step or executing it from outside the form.

Error: Reference Nbr. cannot be found in the system.."}

I customized the ARPaymentEntry in which it creates a Journal Voucher Entry with created Credit Memo, it retrieves the Credit Memo applies the open invoice that is also applied in the current payment. when I create the instance to call the Credit Memo and add the Invoice in ARAdjust table, an error occurs when trying to insert it, giving a Reference Nbr cannot be found in the system, although when I'm trying to manually applying it I could see the open invoice.
public void ReleaseCreditMemo(string refNbr)
{
try
{
ARPaymentEntry docGraph = PXGraph.CreateInstance<ARPaymentEntry>();
List<ARRegister> list = new List<ARRegister>();
ARPayment payment;
ARRegister invoice = PXSelect<ARRegister, Where<ARRegister.docType, Equal<Required<ARRegister.docType>>, And<ARRegister.refNbr, Equal<Required<ARRegister.refNbr>>>>>.Select(docGraph, ARInvoiceType.CreditMemo, refNbr);
docGraph.Document.Current = PXSelect<ARPayment, Where<ARPayment.docType, Equal<Required<ARPayment.docType>>, And<ARPayment.refNbr, Equal<Required<ARPayment.refNbr>>>>>.Select(docGraph, ARInvoiceType.CreditMemo, refNbr);
payment = docGraph.Document.Current;
list.Add(payment);
foreach (ISARWhTax item in ARWhLine.Select())
{
decimal? _CuryAdjgAmt = payment.CuryOrigDocAmt > invoice.CuryDocBal ? invoice.CuryDocBal : payment.CuryOrigDocAmt;
decimal? _CuryAdjgDiscAmt = payment.CuryOrigDocAmt > invoice.CuryDocBal ? 0m : invoice.CuryDiscBal;
ARAdjust adj = new ARAdjust();
adj.AdjdBranchID = item.AdjdBranchID;
adj.AdjdDocType = ARInvoiceType.Invoice;
adj.AdjdRefNbr = item.AdjdRefNbr;
adj.AdjdCustomerID = item.CustomerID;
adj.AdjdDocDate = invoice.DocDate;
adj.CuryAdjgAmt = _CuryAdjgAmt;
adj.CuryAdjdDiscAmt = _CuryAdjgDiscAmt;
if (docGraph.Document.Current.CuryUnappliedBal == 0m && docGraph.Document.Current.CuryOrigDocAmt > 0m)
{
throw new PXLoadInvoiceException();
}
//This line code below OCCURS THE ERROR
docGraph.Adjustments.Insert(adj);
}
docGraph.Save.Press();
PXLongOperation.StartOperation(docGraph, delegate() { ARDocumentRelease.ReleaseDoc(list, false); });
}
catch (Exception ex)
{
throw new PXException(ex.Message);
}
}
I would look at the selector of the field causing the error ("Reference Nbr.") as having a selector on a field will validate the entered value to the selector's select statement (unless validatevalue=false for the selector). Maybe the selector will give you some pointers as to what is missing or causing the validation to fail.
I figured it out it that after the code below executes it does not immediately updates the View. So what I did is to execute my code at ARPayment_RowSelected event with a conditional statement if the document is released.
PXLongOperation.StartOperation(this.Base, delegate() { ARDocumentRelease.ReleaseDoc(list, false); });

Event firing continuously

I wrote a method which changes backcolor of the rows before painting gridview in devexpress. It works fine but I realized that my code begins slowing down. Then I've found that the event firing continuously. It never stops. How can I handle this? Is there any way to stop firing event manually after gridview painted or should I try to solve this problem with an another event or another method???
Here is my event:
private void gvStep_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
try
{
DataRowView drw = (DataRowView)gvStep.GetRow(e.RowHandle);
byte actionTypeID = (byte)drw.Row["ActionType"];
//string colorCode = (new DivaDs()).GetBackColor(actionTypeID);
string colorCode = divaDs.GetBackColor(actionTypeID);
Color backColor = ColorTranslator.FromHtml(colorCode);
e.Appearance.BackColor = backColor;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}
public string GetBackColor(byte actionTypeID)
{
string color = string.Empty;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[DivaSqlSiteConnString].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(#"Select BackColor from ActionTypes where ID = #actionTypeID"))
{
SqlParameter param = new SqlParameter("#actionTypeID", actionTypeID);
cmd.Parameters.Add(param);
cmd.Connection = conn;
conn.Open();
color = cmd.ExecuteScalar().ToString();
conn.Close();
}
}
return color;
}
My best guess is that some part of your code is just really slow.
The event only fires for each visible cell in the grid. If you attempt to debug the event, focus will shift to the debugger, and when you return to the application the cells need to be redrawn, causing the event to fire again, thus giving the impression that the event fires continuously. It does not, however.
Here are some pointers to improve performance:
You are constructing a new DivaDs every time the event fires
Instead, consider reusing the same instance of the class as a member variable
What happens in the constructor?
Take a closer look at the GetBackColor method or ColorTranslator.FromHtml and see if any modifications can be made to improve performance.
Update
It appears you are querying the database for each cell in the grid. This is a really bad idea.
A simple solution would be to preload all ActionTypes and their background colors (or at least the subset of ActionTypes that is displayed in the grid) before setting the grid's data source.
// member variable
private Dictionary<byte, Color> actionTypeColorDict;
void BuildActionTypeColorDictionary()
{
string connectionString = ConfigurationManager
.ConnectionStrings[DivaSqlSiteConnString].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
// load all action type IDs and corresponding background color:
cmd.CommandText = #"SELECT ActionTypeID, BackColor FROM ActionTypes";
DataTable actionTypeTable = new DataTable();
adapter.Fill(actionTypeTable);
// build a dictionary consisting of action type IDs
// and their corresponding colors
actionTypeColorDict = actionTypeTable.AsEnumerable().ToDictionary(
r => r.Field<byte>("ActionTypeID"),
r => ColorTranslator.FromHtml(r.Field<string>("ColorCode")));
}
}
Call the BuildActionTypeColorDictionary method before setting the data source of the grid. In the RowStyle or CustomDrawCell events, use the new dictionary member to determine the background color. See the following modified version of your RowStyle code:
private void gvStep_RowStyle(object sender,DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
try
{
DataRow row = gvStep.GetDataRow(e.RowHandle);
if (row == null)
return;
byte actionTypeID = row.Field<byte>("ActionImage");
// look up color in the dictionary:
e.Appearance.BackColor = actionTypeColorDict[actionTypeID];
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}
How do you know it's firing continuously? Are you debbuging?
This code runs whenever the grid is redrawn, meaning whenever the form gets focus.
This event runs for each cell - so it will run quite a few times.
If you put a break-point in this event you'll never get out of it. It will break, you will debug, when it's done it will return focus to the form - causing the form to be redrawn using this event and the break-point is reached again.
And just a side note - Whenever I use that event I have to put e.Handled = true; in the code so that the cell isn't "drawn" by anyone but me :)
Finally, I found it. RowStyle event only fires same time with gridview's row count
private void gvStep_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
try
{
DataRowView drw = (DataRowView)gridView1.GetRow(e.RowHandle);
if (drw == null)
return;
byte actionTypeID = (byte)drw.Row["ActionImage"];
string colorCode = divaDs.GetBackColor(actionTypeID);
Color backColor = ColorTranslator.FromHtml(colorCode);
e.Appearance.BackColor = backColor;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}

Error while editing grid view record

I got following error while i am clicked edit button on grid view for 2 page
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
can you please specify what should i have to do to remove this error
following is the code for edit command, It works well when i am on first page but gives erro if i goes to another any page in grid view
protected void GVviewReminder_RowCommand(object sender, GridViewCommandEventArgs e)
{
lblError.Text = "";
if (e.CommandName == "Edit")
{
GridViewRow selectedRow = GVviewReminder.Rows[Convert.ToInt32(e.CommandArgument)];
string ID = selectedRow.Cells[1].Text;
Response.Redirect("edit_health_reminder.aspx?HealthReminderIsOpen=true&id=" + ID);
}
}
The error log says index out of range so look at collections.
GVviewReminder.Rows[Convert.ToInt32(e.CommandArgument)]
selectedRow.Cells[1].Text

Resources