Resizing the image while uploading image in Item page - acumatica

Whenever Image is uploaded to the Stock item page, I have to resize the image to thump size and upload the copy of the same.
How do I override the upload function to add my logic?

The upload function is HandleUpload of the PXImageUploader control in PX.Web.UI.
You can try to overwrite that function and then replace the control on the page with yours.
Another way will be to handle the resizing inside the InventoryItemMaint graph.
You can check the ImageUrl field update and do the resize there. Any time you upload a new picture the URL is basically updated. Please don't use the example below in production as it was never fully tested.
// Acuminator disable once PX1016 ExtensionDoesNotDeclareIsActiveMethod extension should be constantly active
public class InventoryItemMaintExt : PXGraphExtension<InventoryItemMaint>
{
public PXSelect<UploadFileRevision> uploadFileRevisions;
protected virtual void InventoryItem_ImageUrl_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e, PXFieldUpdated baseMethod)
{
baseMethod?.Invoke(sender, e);
if(e.Row is InventoryItem row)
{
if ((string)e.OldValue != row.ImageUrl) //ADD conditions so that this doesn't work any time user change the image if there are multiple attached
{
UpdateImageFileRevisionToResizedImage(sender, row);
}
}
}
private void UpdateImageFileRevisionToResizedImage(PXCache sender, InventoryItem row)
{
var fileNotes = PXNoteAttribute.GetFileNotes(sender, row);
UploadFileRevision uploadedFile = GetFile(sender.Graph, fileNotes, row.ImageUrl);
if (uploadedFile != null)
{
var data = ResizeImage(uploadedFile.Data);
uploadedFile.Data = data;
uploadFileRevisions.Update(uploadedFile);
}
}
//WARNING: DON'T USE THIS METHOD IN PRODUCTION.
// USE ANY OTHER RECOMMENDED METHOD TO RESIZE IMAGES
private static byte[] ResizeImage(byte[] data)
{
System.IO.MemoryStream myMemStream = new System.IO.MemoryStream(data);
System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream);
System.Drawing.Image newImage = fullsizeImage.GetThumbnailImage(200, 200, null, IntPtr.Zero);
System.IO.MemoryStream myResult = new System.IO.MemoryStream();
newImage.Save(myResult, System.Drawing.Imaging.ImageFormat.Jpeg); //Or whatever format you want.
return myResult.ToArray(); //Returns a new byte array.
}
private static UploadFileRevision GetFile(PXGraph graph, Guid[] fileIds,string fileUrl)
{
return (UploadFileRevision)PXSelectBase<UploadFileRevision,
PXSelectJoin< UploadFileRevision,
InnerJoin <UploadFile,
On<UploadFile.fileID, Equal<UploadFileRevision.fileID>,
And<UploadFile.lastRevisionID, Equal<UploadFileRevision.fileRevisionID>>>>,
Where<UploadFile.fileID, In<Required<UploadFile.fileID>>,
And<UploadFile.name,Equal<Required<UploadFile.name>>>>>.Config>.Select(graph, new object[]
{
fileIds,
fileUrl
});
}
}

Related

Insert a grid line when the record gets saved

I am trying to add a new record to a grid during the persist logic. However, even though the record does get added to the grid in the UI, when the page gets refreshed, the new line disappears. It is not getting persisted in the DB.
I am using the Bills page as reference.
Code sample
protected virtual void APTran_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
{
if (e.Row == null)
{
return;
}
APInvoice invoiceRow = this.Base.Document.Current;
if (invoiceRow != null)
{
APTran tranRow = new APTran();
tranRow = this.Base.Transactions.Insert(tranRow);
tranRow.InventoryID = 10043;
this.Base.Transactions.Update(tranRow);
tranRow.Qty = 3;
this.Base.Transactions.Update(tranRow);
}
}
Result after saving - Record is shown in the grid:
Result after cancelling - Record disappears from the grid:
Something like this I tend to override the Persist method and insert or update related records before calling base persist. Here is a possible example which goes inside your graph extension:
[PXOverride]
public virtual void Persist(Action del)
{
foreach(APInvoice invoiceRow in Base.Document.Cache.Inserted)
{
APTran tranRow = this.Base.Transactions.Insert();
tranRow.InventoryID = 10043;
tranRow = this.Base.Transactions.Update(tranRow);
tranRow.Qty = 3;
this.Base.Transactions.Update(tranRow);
}
del?.Invoke();
}

Running a long operation within an event handler

I need to run some address validation on Customer Location addresses using a 3rd party API to determine if the address is residential or commercial. This validation should run whenever an address field is changed. In other words, the validation should be run in the Address_RowUpdated event handler.
Because the function is calling a 3rd party API, I believe that it should be done in a separate thread, using PXLongOperation so that it does not hold up address saving and fails gracefully if the API is unavailable or returns an error.
However, I am not sure if the architecture of running a long operation within an event handler is supported or if a different approach would be better.
Here is my code.
public class CustomerLocationMaint_Extension : PXGraphExtension<CustomerLocationMaint>
{
protected virtual void Address_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
PX.Objects.CR.Address row = (PX.Objects.CR.Address)e.Row;
if (row != null)
{
Location location = this.Base.Location.Current;
PXCache locationCache = Base.LocationCurrent.Cache;
PXLongOperation.StartOperation(Base, delegate
{
RunCheckResidential(location, locationCache);
});
this.Base.LocationCurrent.Cache.IsDirty = true;
}
}
protected void RunCheckResidential(Location location, PXCache locationCache)
{
string messages = "";
PX.Objects.CR.Address defAddress = PXSelect<PX.Objects.CR.Address,
Where<PX.Objects.CR.Address.addressID, Equal<Required<Location.defAddressID>>>>.Select(Base, location.DefAddressID);
FValidator validator = new FValidator();
AddressValidationReply reply = validator.Validate(defAddress);
AddressValidationResult result = reply.AddressResults[0];
bool isResidential = location.CResedential ?? false;
if (result.Classification == FClassificationType.RESIDENTIAL)
{
isResidential = true;
} else if (result.Classification == FClassificationType.BUSINESS)
{
isResidential = false;
} else
{
messages += "Residential classification is: " + result.Classification + "\r\n";
}
location.CResedential = isResidential;
locationCache.Update(location);
Base.LocationCurrent.Update(location);
Base.Actions.PressSave();
// Display relevant messages
if (reply.HighestSeverity == NotificationSeverityType.SUCCESS)
String addressCorrection = validator.AddressCompare(result.EffectiveAddress, defAddress);
if (!string.IsNullOrEmpty(addressCorrection))
messages += addressCorrection;
}
PXSetPropertyException message = new PXSetPropertyException(messages, PXErrorLevel.Warning);
PXLongOperation.SetCustomInfo(new LocationMessageDisplay(message));
//throw new PXOperationCompletedException(messages); // Shows message if you hover over the success checkmark, but you have to hover to see it so not ideal
}
public class LocationMessageDisplay : IPXCustomInfo
{
public void Complete(PXLongRunStatus status, PXGraph graph)
{
if (status == PXLongRunStatus.Completed && graph is CustomerLocationMaint)
{
((CustomerLocationMaint)graph).RowSelected.AddHandler<Location>((sender, e) =>
{
Location location = e.Row as Location;
if (location != null)
{
sender.RaiseExceptionHandling<Location.cResedential>(location, location.CResedential, _message);
}
});
}
}
private PXSetPropertyException _message;
public LocationMessageDisplay(PXSetPropertyException message)
{
_message = message;
}
}
}
UPDATE - New Approach
As suggested, this code now calls the LongOperation within the Persist method.
protected virtual void Address_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
PX.Objects.CR.Address row = (PX.Objects.CR.Address)e.Row;
if (row != null)
{
Location location = Base.Location.Current;
LocationExt locationExt = PXCache<Location>.GetExtension<LocationExt>(location);
locationExt.UsrResidentialValidated = false;
Base.LocationCurrent.Cache.IsDirty = true;
}
}
public delegate void PersistDelegate();
[PXOverride]
public virtual void Persist(PersistDelegate baseMethod)
{
baseMethod();
var location = Base.Location.Current;
PXCache locationCache = Base.LocationCurrent.Cache;
LocationExt locationExt = PXCache<Location>.GetExtension<LocationExt>(location);
if (locationExt.UsrResidentialValidated == false)
{
PXLongOperation.StartOperation(Base, delegate
{
CheckResidential(location);
});
}
}
public void CheckResidential(Location location)
{
CustomerLocationMaint graph = PXGraph.CreateInstance<CustomerLocationMaint>();
graph.Clear();
graph.Location.Current = location;
LocationExt locationExt = location.GetExtension<LocationExt>();
locationExt.UsrResidentialValidated = true;
try
{
// Residential code using API (this will change the value of the location.CResedential field)
} catch (Exception e)
{
throw new PXOperationCompletedWithErrorException(e.Message);
}
graph.Location.Update(location);
graph.Persist();
}
PXLongOperation is meant to be used in the context of a PXAction callback. This is typically initiated by a menu item or button control, including built-in actions like Save.
It is an anti-pattern to use it anytime a value changes in the web page. It should be used only when a value is persisted (by Save action) or by another PXAction event handler. You should handle long running validation when user clicks on a button or menu item not when he changes the value.
For example, the built in Validate Address feature is run only when the user clicks on the Validate Address button and if validated requests are required it is also run in a Persist event called in the context of the Save action to cancel saving if validation fails.
This is done to ensure user expectation that a simple change in a form/grid value field doesn't incur a long validation wait time that would lead the user to believe the web page is unresponsive. When the user clicks on Save or a specific Action button it is deemed more reasonable to expect a longer wait time.
That being said, it is not recommended but possible to wrap your PXLongOperation call in a dummy Action and asynchronously click on the invisible Action button to get the long operation running in the proper context from any event handler (except Initialize):
using PX.Data;
using System.Collections;
namespace PX.Objects.SO
{
public class SOOrderEntry_Extension : PXGraphExtension<SOOrderEntry>
{
public PXAction<SOOrder> TestLongOperation;
[PXUIField(DisplayName = "Test Long Operation", Visible = false, Visibility = PXUIVisibility.Invisible)]
[PXButton]
public virtual IEnumerable testLongOperation(PXAdapter adapter)
{
PXLongOperation.StartOperation(Base, delegate ()
{
System.Threading.Thread.Sleep(2000);
Base.Document.Ask("Operation Done", MessageButtons.OK);
});
return adapter.Get();
}
public void SOOrder_OrderDesc_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
{
if (!PXLongOperation.Exists(Base.UID))
{
// Calling Action Button asynchronously so it can run in the context of a PXAction callback
Base.Actions["TestLongOperation"].PressButton();
}
}
}
}

Vaadin audio element doesn't work when I use it to play .m4a sound files (Vaadin 7.3.2)

I use this to display html5 audio in one of my Vaadin application. When I simply requst the data in browser, and save the file, it can be played - but it always fails to do so, when I try it in Vaadin.
Can you point out, what am I doing wrong?
public class AudioArea extends Audio {
public AudioArea(final int soundId) {
super();
StreamResource resource = new StreamResource(
new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] data = MyVaadinUI.request.getBinaryData(
soundId, BinaryDataSource.TYPE_SOUND, 0, 0);
if (data == null) {
return null;
}
return new ByteArrayInputStream(data);
}
}, "");
setSource(resource);
markAsDirty();
}
}
Are you sure that your browser supports the format? If you try it with plain html can you play it?
If the browser supports the format, then I suggest this:
Audio audio = new Audio("MyAudio");
audio.setSource(new ThemeResource("audio/myAudio.m4a"));
myLayout.addComponent(audio);
And you could put the file under your theme folder (or you can use FileResource instead).
EDIT
Maybe the missing MIME Type is the problem:
StreamResource resource = new StreamResource(
new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] data = MyVaadinUI.request.getBinaryData(
soundId, BinaryDataSource.TYPE_SOUND, 0, 0);
if (data == null) {
return null;
}
return new ByteArrayInputStream(data);
}
}, "") {
#Override
public String getMIMEType() {
return "audio/mp4";
}
};

How to download excel file from web application?

I'm using Wicket (not sure if it matters) but I'm using Workbook to create an excel file for a user to download. But I'm not sure how exactly to do this. What I would like to happen is the user clicks the button, a log is created and a prompt is given to the user to open (and save to temp files) or to save to their computer. The file is then deleted from the server side, or maybe it is stored in the User's session and deleted at end of session.
Can someone point me in the right direction? If I can have the file not saved in the session at all, that'd be create and have it just have it sent to the client using FileOutputStream somehow..
here is my current code:
private void excelCreator()
{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("SSA User ID " + currentSSAIDSelection2.getSsaUserId()));
Iterator<AuditLogEntry> auditLogEntrys = logList.iterator();
int i = 0;
while (auditLogEntrys.hasNext())
{
final AuditLogEntry auditLogEntry = auditLogEntrys.next();
Row row = sheet.createRow(i);
row.createCell(0).setCellValue(auditLogEntry.getTimeStamp());
row.createCell(1).setCellValue(auditLogEntry.getSourceName());
row.createCell(2).setCellValue(auditLogEntry.getCategory());
row.createCell(3).setCellValue(auditLogEntry.getSsaAdmin());
row.createCell(4).setCellValue(auditLogEntry.getAction());
i++;
}
try
{
FileOutputStream output = new FileOutputStream("ssaUserIDAccess.xls");
workbook.write(output);
output.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
You would have to create a DownloadLink with the temporary file as input. The temporary File must be deleted after download (file.delete())).
Alternatively you can try this:
IResourceStream stream = new ByteArrayResourceStream(data, "application/vnd.ms-excel");
RequestCycle.get().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(stream, filename).setContentDisposition(ContentDisposition.ATTACHMENT));
In this case data is the byte[] content of your workbook which can be for example retrieved with output.toByteArray().
In case anyone runs into this problem here is my solution. There wasn't a lot of straight forward answers on this but this is my solution:
My excelCreator method handles the creation of the excel Sheet, and returns it as a file.
private File excelCreator()
{
Workbook workbook = new HSSFWorkbook();
File excelfile = new File("userIDAccess.xls");
logList = getServer().findAuditLogs(getUserId(), null);
Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("User ID " + getUserId()));
Iterator<AuditLogEntry> auditLogEntrys = logList.iterator();
int i = 0;
while (auditLogEntrys.hasNext())
{
final AuditLogEntry auditLogEntry = auditLogEntrys.next();
Row row = sheet.createRow(i);
row.createCell(0).setCellValue(auditLogEntry.getTimeStamp());
row.createCell(1).setCellValue(auditLogEntry.getSourceName());
row.createCell(2).setCellValue(auditLogEntry.getCategory());
row.createCell(3).setCellValue(auditLogEntry.getSsaAdmin());
row.createCell(4).setCellValue(auditLogEntry.getAction());
i++;
}
try
{
FileOutputStream output = new FileOutputStream(excelfile);
workbook.write(output);
output.close();
}catch(Exception e)
{
e.printStackTrace();
}
return excelfile;
}
IModel excelFileModel = new AbstractReadOnlyModel()
{
public Object getObject()
{
return excelCreator();
}
};
I created an IModel to capture the file created inside my excelCreator() method and returned.
auditDownloadlink = new DownloadLink("auditDownloadlink", excelFileModel);
I pass the I.D. of the download link, and then pass the imodel.
finally,
I call,
auditDownloadlink.setDeleteAfterDownload(true);
auditDownloadlink.setCacheDuration(Duration.NONE);
This deletes the file after it is created. And the cache setting is a setting to make sure it is compatible with all browsers (That's how I interpreted it, but you may not need it).
The Imodel creates the File on the fly so it doesn't have to be stored anywhere, and then the file is deleted once it is downloaded.
Hope this helps someone!
You could create a Resource to do this, and make a ResourceLink.
public class ExcelProducerResource extends AbstractResource
{
public ExcelProducerResource()
{
}
#Override
protected ResourceResponse newResourceResponse( Attributes attributes )
{
final String fileName = getFileName();
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
resourceResponse.setCacheDuration( Duration.NONE );
resourceResponse.setFileName( fileName );
resourceResponse.setWriteCallback( new WriteCallback()
{
#Override
public void writeData( Attributes attributes ) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
writeToStream( outputStream );
outputStream.close();
}
} );
return resourceResponse;
}
void writeToStream(OutputStream outputStream) throws IOException
{
//.. do stuff here :)
}
String getFileName()
{
//.. do stuff here :)
}
}

with a winrt user control how do i dynamically create controls based on dependency property

I'm trying to create a user control that will display a collection of images. I have the user control created with a dependency property for the collection of images. I can databind to that property and display the images fine.
However, I have hard-coded in the size of the collection and I want it to take in an arbitrary number of images and display them.
I am not sure how to dynamically create the images based on the collection of images. I'm sure there is some event that I want to respond to and create my images based on the contents of the dependency property.
public sealed partial class ImageView : UserControl
{
public ImageView()
{
this.InitializeComponent();
scrollViewer.ZoomSnapPoints.Clear();
scrollViewer.ZoomSnapPoints.Add(0.2f);
scrollViewer.ZoomSnapPoints.Add(0.6f);
scrollViewer.ZoomSnapPoints.Add(1.0f);
scrollViewer.ZoomSnapPoints.Add(1.4f);
scrollViewer.ZoomToFactor(0.4f);
}
public static readonly DependencyProperty ImagesProperty = DependencyProperty.Register("Images",
typeof(List<VMImage>), typeof(ImageView), new PropertyMetadata(new List<VMImage>(12)));
public List<VMImage> Images
{
get { return (List<VMImage>)GetValue(ImagesProperty); }
set { SetValue(ImagesProperty, value); }
}
}
<ScrollViewer Height="700" Width="700"
x:Name="scrollViewer"
MinZoomFactor="0.2"
MaxZoomFactor="5.0"
ZoomSnapPointsType="Mandatory">
<Canvas Background="Black" Width="2000" Height="2000" >
<Image Canvas.Left="{Binding Images[0].Location.X}"
Canvas.Top="{Binding Images[0].Location.Y}"
Source="{Binding Images[0].Source}" ></Image>
<Image Canvas.Left="{Binding Images[1].Location.X}"
Canvas.Top="{Binding Images[1].Location.Y}"
Source="{Binding Images[1].Source}" ></Image>
</Canvas>
</ScrollViewer>
You should make your dependency property an ObservableCollection<VMImage>. This way you can attach a handler to its CollectionChanged event and get notified of changes. Just make sure in the property changed callback of your dependency property that you add the event handler to the new value and remove it from the old value.
public static readonly DependencyProperty ImagesProperty = DependencyProperty.Register("Images",
typeof(ObservableCollection<VMImage>), typeof(ImageView), new PropertyMetadata(null, OnImagesChanged));
public ObservableCollection<VMImage> Images
{
get { return (ObservableCollection<VMImage>)GetValue(ImagesProperty); }
set { SetValue(ImagesProperty, value); }
}
private static void OnImagesChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
// use wrapper to pass DependencyObject to handler
NotifyCollectionChangedEventHandler handler = (s, args) => OnCollectionChanged(target, args);
if (e.OldValue is ObservableCollection<object>)
(e.OldValue as ObservableCollection<object>).CollectionChanged -= handler;
if (e.NewValue is ObservableCollection<object>)
(e.NewValue as ObservableCollection<object>).CollectionChanged += handler;
var imageView = target as ImageView
if (imageView != null)
{
// collection has changed completely, replace all images
}
}
static void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var imageView = sender as ImageView;
if (imageView != null)
{
if (e.OldItems != null)
{
// remove images
}
if (e.NewItems != null)
{
// add images
}
}
}

Resources