How can I download a dynamically created server side file using Flex? - apache-flex

I want to Export a table from my database to an excel file on the server and then download it. The following is the code that I developed for this purpose:
import flash.net.FileReference;
import flash.net.URLRequest;
public function sqlDownloadExcel():void {
var http:HTTPService = new HTTPService;
var parm:Object = new Object;
var sql:String;
sql = "insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\\inetpub\wwwroot\\myApp\\App_Data\\myExport.xls;', 'SELECT * FROM [Sheet1$]') SELECT * FROM myTable";
parm.sql = sql;
parm.db = "myDatabase";
http.url = "http://mywebsite.com/SQLconnector/sqlconnector.asp?irand="+Math.random();
http.showBusyCursor = true;
http.request = sql;
http.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {sqlDownloadExcelResult(e);});
http.addEventListener(FaultEvent.FAULT, mssqlFault);
http.method = "POST";
sqlToken = http.send(parm);
}
public function sqlDownloadExcelResult(event:ResultEvent):void{
var request:URLRequest = new URLRequest("http://mywebsite/myApp/App_Data/myExport.xls");
var fileRef:FileReference = new FileReference();
fileRef.download(request);
}
The code creates the Excel file on the server correctly, but running the fileRef.download(request) functions causes the following error:
Error #2176: Certain actions, such as those that display a pop-up window, may only be invoked upon user interaction, for example by a mouse click or button press.
Any advice would be much appreciated.
Thank you

You can't do what you want. Security restrictions prevent your app from trying to download anything to the clieht machine without user input. That is why you're seeing the error.
I recommend creating the excel sheet on the server, saving it to the server, and then sending a URL back to your Flex app. Use navigateToURL() to open it; and the browser should handle it based on the client's browsers settings. It may download automatically; or open automatically; or it may prompt the user what it wants to do.
If necessary, you can create a server side script to routinely clean out the generated files.
Based on the code you provided, it looks like you are 90% of the way there. Just instead of using FileReference to try to download the file, use navigateToURL() to open that URLRequest.
Alternatively, you could modify your UI to say "You're file is ready, click here to get it" or something similar. Then you have user interaction and can open the download window after the user clicks the button.

Related

Storing Data in firebase using VBA

Is there any way to upload files using VBA to firebase?
Web code for uploading files in firebase
var storageRef = firebase.storage.ref("folderName/file.jpg");
var fileUpload = document.getElementById("fileUpload");
fileUpload.on(‘change’, function(evt) {
var firstFile = evt.target.file[0]; // get the first file uploaded
var uploadTask = storageRef.put(firstFile);
uploadTask.on(‘state_changed’, function progress(snapshot) {
console.log(snapshot.totalBytesTransferred); // progress of upload
});
});
But how do I use this in VBA? any help is appreciated. Also if you can point to me in right direction.
I did some research on Firebase. Currently you cannot use VBA to upload files directly to FB Storage, through API.
You can try using JS, as mentioned by you.
Another alternative will be Google Cloud Storage. Which is the back-end for firebase storage.
two ways of doing this.. Assuming there is a website where you can upload files, in such case you can use the standard IE object to navigate to a specific website, find the controls, select the files and using submit or click function upload the file..
The other way is to write a web-service and call it from vba. Both suggestions involves in calling the website/service.
Dim IE As Object
Set IE = CreateObject("internetexplorer.application")
IE.Navigate "Your upload page.."
Do While IE.ReadyState <> 4 Or IE.Busy = True
DoEvents
Loop
we don't have enough information so I just continue with the logic.
Find the upload document/filename field. insert your filename
IE.Document.getElementById("txt_upload_field").Value = myFileName
find the button/element to upload and perform click/submit action.
wait for your website and read the result
or you can write your own web service and perform a web-request using XMLHTTP. I personally would go for web-service.
there is also a third way. FTPing to your server..!

Download a file with Tidesdk

How can I download a file and store it locally? I've searched the doc and google and couldn't find an example of it.
I tried this:
this.copyRemote = function(path,path2){
reader = Ti.Network.createHTTPClient();
writer = Ti.Filesystem.getFile(path2);
reader.open('GET',path);
reader.receive(writer);
}
But Tidesdk crashes while trying to download the file, the last messages on console are:
[12:42:39:647] [Ti.Network.HTTPClient] [Debug] Changing readyState from 0 to 1 for url:https://buttonpublish.com/api/images/7/image257189x142.jpg
[12:42:39:671] [Ti.Proxy] [Debug] Looking up proxy information for: https://buttonpublish.com/api/images/7/image257189x142.jpg
[12:
Seems like there has been success on the TideSDK Google Group using the code below:
var httpClient = Ti.Network.createHTTPClient();
httpClient.open('GET', path);
httpClient.receive(function(data) {
var file = Ti.Filesystem.getFile(path2);
var fileStream = file.open(Ti.Filesystem.MODE_APPEND);
fileStream.write(data);
fileStream.close();
});
Hope that helps, at least to point in the right direction.
I found that this works for my needs, which are just to get the file onto the machine:
function downloadFile( url ){
Ti.Platform.openApplication( url );
}
This opens the URL using the machine's default browser. One downside to this approach is that the user is normally prompted to confirm the download. I use the downloadFile function in case I want to change how this works in the future.

Open print dialog for report from code

I am attempting to force open the print dialog so that all the user has to do is set the email address and press ok. I've found multiple tutorials on how to print a report to file or a printer without the print dialog, but that's not what I'm looking for.
Typically to email a report, the user displays the report, clicks the print icon in the tool bar, and then chooses email and sends it. I want to cut out the first two steps automatically.
This is one of my many attempts at doing this so far, but to no avail.
void emailInvoice()
{
Args args;
ReportRun rr;
Report rb;
PrintJobSettings pjs;
CustInvoiceJour record;
;
select record where record.RecId == 5637175089;
args = new Args("SalesInvoice");
args.record(record);
args.parmEnum(PrintCopyOriginal::OriginalPrint);
// Set report run properties
rr = new ReportRun(args,'');
rr.suppressReportIsEmptyMessage(true);
rr.query().interactive(false);
// set report properties
rb = rr.report();
rb.interactive(true);
// set print job settings
pjs = rr.printJobSettings();
pjs.fileName(strfmt("C:\\Users\\gbonzo\\Desktop\\%1.pdf", record.SalesId));
pjs.fitToPage(true);
// break the report info pages using the height of the current printer's paper
pjs.virtualPageHeight(-1);
// force PDF printing
pjs.format(PrintFormat::PDF);
pjs.setTarget(PrintMedium::Mail);
pjs.viewerType(ReportOutputUserType::PDF);
// lock the print job settings so can't be changed
// X++ code int the report may try to change the destination
// to the screen for example but this does not make
// sense when running a report here
pjs.lockDestinationProperties(true);
// Initialize the report
rr.init();
rr.run();
}
Thanks in advance for your help!
Have you tried to develop a RunBase standard dialog class (RunBaseBatchPrintable if you need to select the printer) that get all the dialog fields you need and from there, programatically run the report passing all the desired parameters? I'm prety sure it will work, and probably will left a cleaner code separating the report of the logic needed to the user interaction.
Read an example here:
http://waikeatng.blogspot.com.es/2010/10/using-runbasebatchprintable-class.html
You have to call the prompt() method of the ReportRun class before calling the run() method.
if (rr.prompt())
{
rr.run();
}
The prompt() method will show the print dialog. If you want it easier for your users you could use the SysMailer class, take a look to the quickSend() method.

API (Service) to work for both Windows Phone and Website

I created(in last stage) a ASP.NET website which requires database communications, So we created WCF services to connect to the database. If there is a Select statement those service returns DataTable.
Services are working fine and website also working fine
At the time of API creation i don't know that windows phone sdk does not support the DataTables.
I read some where that Windows Phone SDK doesn't support DataTable, i checked in my Visual Studio also there is no class called DataTable in System.Data namespace.
I am new to Windows Phone.
But now we want to create a WINDOWS PHONE APP which also works same as Website, so we want to use the existing API(WCF Service).
is there is any way to accomplish this task. most of the methods return type is DataTable.
we don't want to create two API's(means services). What should I do?
How to create a Service which works for both Windows Phone and Website.
we are ready to change the change the API and according to that ready to update Website also?
thanks
Just changed the API to return Stream instead of DataTable
System.IO.StringWriter reader = new System.IO.StringWriter();
dt.WriteXml(reader, XmlWriteMode.WriteSchema);//dt is datatable
return reader;
in website small minor changes, reading the stream and assign it to a datatable
StringReader xmlReader = new StringReader(stream);
DataTable dt = new DataTable();
dt.ReadXml(xmlReader);
Update:
This approach is not suggestible(this was my first web service application), I suggest to use JSON/XML responses(with returning DTOs) instead of returning DataTable..
Following links might land you in right direction.
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
http://mono.servicestack.net/ServiceStack.Hello/
Not sure why you used datatable. Do you mean dataset?
They are all XML under the covers. Try parsing them. Try something like this:
var resultNewDataSet = XElement.Parse(xmlContent);
var result = resultNewDataSet.Descendants("Table")
.Select(t => new
{
aaa = t.Descendants("aaa").First().Value,
bbb = t.Descendants("bbb").First().Value
});
foreach (var res in result)
{
System.Diagnostics.Debug.WriteLine("aaa: " + res.aaa + " / bbb: " + res.bbb);
}

Get updated image in flex image control after changing source not name of file(image)?

I am changing image through flex every time i change it saved into server directory with same name(which i am referring to show). So when i refresh my page my browser didn't send new request to server since it's already in request.so didn't getting new image.Tip:- when i clear browser history it will come with new image
You can try adding an additional time-stamp to the image source each time u make a new request, which would make the request look different for the browser.
Example :
var src:String = "image.png";
src = src + "?" + new Date().getTime().toString();
Since you mentioned that you're refreshing the browser, then I assume that your embedded SWF file will also need to be refreshed.
When you embed your SWF, you need to add a parameter that would be random across all time (i.e. datetime stamp, etc.)
var mySWF = "swf/YourEmbeddedFlashFile.swf?guid=" + rnd();
and declare a js function:
function rnd()
{
return String((new Date()).getTime()).replace(/\D/gi, '')
}

Resources