How to create "Browse for folder" dialog in Adobe FLEX? - apache-flex

Know someone, how to create "Browse for folder" dialog in Adobe FLEX? And it is possible?
Thanx.

If it's an Air app you can do :
var f : File = new File;
f.addEventListener(Event.SELECT, onFolderSelected);
f.browseForDirectory("Choose a directory");
If it's a pure As3 app, you cannot Browse for folder, you can just browse for file via FileReference class.

in Web, for multiple file upload, (for single file upload, use FileRefernce)
private var _refAddFiles:FileReferenceList;
private function browse():void
{
_refAddFiles = new FileReferenceList();
var fileFilter:FileFilter=new FileFilter("*.jpg","*.jpg;*.jpeg;");
_refAddFiles.addEventListener(Event.SELECT, onSelectFile);
_refAddFiles.browse([fileFilter]);
}
<mx:Button click="browse"/>
This will work, and what you want to do after selection,
private function onSelectFile(event:Event):void
{
_arrUploadFiles = [ ];
if (_refAddFiles.fileList.length >= 1)
{
for (var k:Number = 0; k < _refAddFiles.fileList.length; k++)
{
_arrUploadFiles.push({ name: _refAddFiles.fileList[k].name,
file: _refAddFiles.fileList[k]});
}
}
}

This is a quick function set to create a nice folder browser in Flex:
private var file:File = new File();
private function pickFile(event:MouseEvent):void {
file.addEventListener(Event.SELECT, openFile);
file.browseForDirectory("Select folder...");
}
private function openFile(event:Event):void{
folderPath.text = file.nativePath;
}
The first function deals with the folder browser, the second one populates a text input with the full folder path.
Howto:
On the stage, create a simple mx:button and add a call to the pickFile() function for the click event:
<mx:Button click="{pickFile(event);}" />
Then, put also on the stage an mx:TextInput component, to show the folder path after selection:
<mx:TextInput id="folderPath" editable="false" />
This way you have a button to click in order to show the system folder browser, and a text input to show the full folder path after selection.
To improve the button look, you can embed a nice folder icon :-)
Just my 2c. :-)

Related

GTK# - Changing propeties of widgets

I'm trying to make a program that works like Total Commander (I have to do it for school). I use dotnet for the program and Glade for designing the window. I got the window to load properly, however I am not able to access the ui elements and change it's properties. I gave the element's id and widget name but it still says it cannot find it and that it's missing propety. Here's code of MainWindow.cs:
using System;
using Gtk;
using UI = Gtk.Builder.ObjectAttribute;
namespace GtkNamespace
{
class MainWindow : Window
{
[UI] private MainWindow window = null;
[UI] private Button _button2 = null;
public MainWindow() : this(new Builder("MainWindow.glade")) { }
private MainWindow(Builder builder) : base(builder.GetObject("MainWindow").Handle)
{
builder.Autoconnect(this);
DeleteEvent += Window_DeleteEvent;
}
private void Window_DeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
}
}
}
The [UI] part works for buttons, but not for widgets and other ui elements. If you'd like, I can get it on github.
Let's say you have a Button with id buttonClickme in your glade file,
if you want to access it, you can do
Button buttonClickme = (Gtk.Button)builder.GetObject("buttonClickme");
Later you can use this object to change/read any property of this widget.
buttonClickme.Name = "newName";
Console.WriteLine("Changed button name :" + buttonClickme.Name);
buttonClickme.Label = "New Label";
Similarly, you can access any object mentioned in your .glade file.
example of my glade file
<object class="GtkButton" id="buttonClickme">
<property name="label" translatable="yes">button</property>
<property name="name">buttonClickme</property>
<signal name="clicked" handler="on_buttonClickme_clicked" swapped="no"/>
</object>

How can i upload a file to server (asp.net web form) with ajax?

My project is an online mock toefl test. In speaking section I want to upload a recorded file (audio) to server. for recording im not using flash and its only js.
I searched and find something useful but the server is php. and i cant turn the codes to asp.net (web form). please help me out.
In php i used this code in js :
function uploadAudio(mp3Data){
var reader = new FileReader();
reader.onload = function(event){
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
console.log("mp3name = " + mp3Name);
fd.append('fname', mp3Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
//console.log(data);
log.innerHTML += "\n" + data;
});
};
reader.readAsDataURL(mp3Data);
}
and this code in upload.php:
<?php
if(!is_dir("recordings")){
$res = mkdir("recordings",0777);
}
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
//echo ($decodedData);
$filename = urldecode($_POST['fname']);
// write the data out to the file
$fp = fopen('recordings/'.$filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
How can i do this in asp.net, tanks.
You can use jQuery File Uploader on an aspx page. Your client can simply communicate withe an ashx handler at the server side.
https://evolpin.wordpress.com/2011/09/11/asp-net-ajax-file-upload-using-jquery-file-upload-plugin/
One method, and perhaps the most simple solution, is to just use the <asp:FileUpload> control, and hide it from view. Then again, although this works well if you want the user to choose the files they're uploading, it might not be the best solution if you want to implement some kind of HTML5 drag'n'drop solution, etc.
Coincidentally, I spent pretty much all of last week studying how to upload files via javascript to ASP.NET web forms. I developed a drag and drop interface that uses HTML5, and also developed a fail-over method with which the user could choose and upload their files via the <asp:FileUpload> control.
Due to the feature being low-priority, we only fully developed the <asp:FileUpload> control, but I'm happy to share that feature with you here:
HTML
We're going to create an ASP file upload control, and hide certain parts of it. The rest of it, we can add styles to (or do whatever in javascript and CSS) to make it look fancy and customized. The CONTINUE BUTTON
<!-- Allow user to upload the file via the fallbackuploader -->
<div id="fallbackUploader" class="uploader-item-fallbackuploader uploader-item fallbackuploader step-container">
<div class="fallbackuploader-item-uploadcontrols fallbackuploader-item uploadcontrols">
<!-- Uploader Label (note: this serves as the visible "choose files" button too) -->
<label id="uploader_choose_files_button" class="uploadcontrols-item uploadcontrols-item-label button animated" for="mainContent_subContent_fbu_fileuploader">
Choose Files
</label>
<!-- Choose Files button (**NOTE: you'll want to make this control invisible. Try not to set the display to none, as that may cause ASP to omit rendering it -->
<asp:FileUpload ID="fbu_fileuploader" CssClass="uploadcontrols-item-aspfileloader uploadcontrols-item aspfileloader" runat="server" />
<!-- Continue button (NOTE: this button triggers the event that on the server side that will actually handle the file upload -->
<asp:Button ID="fbu_fileuploaderButton" runat="server" Text="Continue" ClientIDMode="Static"
CssClass="uploadcontrols-item-button-upload uploadcontrols-item-button uploadcontrols-item button-upload button continue-button hidden disabled animated" />
<!-- Cancel button -->
<div id="chooseFilesCancelButton" class="uploadcontrols-item-uploadcontrols-item-button
uploadcontrols-item cancel-button hidden disabled button animated">
Go Back
</div>
</div>
</div>
Javascript
// Organizational container for the file uploader controls.
var aspUploadControlsContainer = $('.fallbackuploader-item-uploadcontrols');
// ASP control that chooses and loads the file.
var aspFileLoader_ele = aspUploadControlsContainer.children('.uploadcontrols-item-aspfileloader'),
// element that represents the "choose files" button.
aspUploaderChooseFilesLabel = aspUploadControlsContainer.find('.uploadcontrols-item-label'),
// ASP button that loads the file
aspFileLoaderButton_ele = aspUploadControlsContainer.children('.uploadcontrols-item-button'),
// the element created by the actual ASP "<asp:FileUpload>" control tag.
aspFileUploadControl_ele = aspUploadControlsContainer.find('input.uploadcontrols-item-aspfileloader'),
// the message/alert container
messagebox_ele = $('.uploader-item-messagebox');
// ------------------------------------------------------------
// Bind the 'click' and 'change' events to the file uploader
// ------------------------------------------------------------
function bindAspUploadControlEvents() {
aspFileLoader_ele.on('change', function () { // add the on-change event for the file uploader.
console.log('File changed ...');
if (!aspUploaderChooseFilesLabel.hasClass('upload-disabled')) {
console.log('Choose-files label not disabled ...');
fileSelected(); // perform the file-selected actions.
}
});
};
// ------------------------------------------------------------
// Validate the selected file name and adjust the uploader.
// ------------------------------------------------------------
function fileSelected() {
console.log('File selected...');
var f = aspFileLoader_ele.val() || '';
f = f.replace('C:\\fakepath\\', '') || ''; // get the file name <-- ASP.NET masks the path as C:\\fakepath\\ for security purposes...we'll just take that part out.
var xlRegex = /.(xlsx|xls)$/i; // set the regex to test for accepted file extensions.
if (f.length && !(f.match(xlRegex))) {
// --------------------------- FAILED - show a message -----------------------------------------------------------------
console.log('File-name invalid. Displaying error message ...');
convertCFlabelToButton(); // <-- converting the label to a button and visa versa is probably a round-about way of doing what we wanted, but we were doing some other stuff with it that kind of made it a necessary evil :)
deactivateChooseFilesCancelButton(); // if nothing selected, disable and hide cancel button <-- these functions just do some fluffy stuff that you probably won't need.
deactivateUploaderContinueButton(function () { // if nothing selected, disable and hide continue button <-- these functions just do some fluffy stuff that you probably won't need.
messagebox_ele.text("You've selected a file with an invalid file name. Please make sure the file extension ends with \".xlsx\".").show(); // show the error message.
});
} else if (f.length && f.match(xlRegex)) {
// --------------------------- PASSED -----------------------------------------------------------------
console.log('File-name validated. Hiding messages...');
messagebox_ele.text('').hide(); // reset and hide any messages
console.log('Messages hidden.');
convertCFbuttonToLabel(f, function () { // this converts the button to a label with the given file name as its text
activateUploaderContinueButton(function () { // show and enable the choose-files continue-button
activateChooseFilesCancelButton() // show and enable the choose-files cancel-button
});
});
} else {
// --------------------------- FAILED - hide message -----------------------------------------------------------------
console.log('No file detected. Returning to default state ...');
messagebox_ele.text('').hide(); // hide any messages
// reset the label to defaults
convertCFlabelToButton();
// ------------------------------------------------------------------------------------------------------------------------------
};
}
CODE-BEHIND
Now we just need to add the VB.NET (or C#) to handle the click-event for the continue button.
Protected Sub fbu_fileuploaderButton_Click(sender As Object, e As EventArgs) Handles fbu_fileuploaderButton.Click
If fbu_fileuploader.HasFile Then
Dim FileName As String = Path.GetFileName(Path.GetRandomFileName())
Dim Extension As String = Path.GetExtension(fbu_fileuploader.PostedFile.FileName)
Dim FolderPath As String = ResolveUrl("~/" & ConfigurationManager.AppSettings("FolderPath"))
Dim FilePath As String = Server.MapPath(FolderPath + FileName)
fbu_fileuploader.SaveAs(FilePath)
GetExcelSheets(FilePath, fbu_fileuploader.PostedFile.FileName, FileName, Extension, "Yes")
End If
End Sub
Other Caveats
We did a couple things in the above code that I did not explain, such as the "FolderPath" application setting (we used this in CODE-BEHIND section to determine where the file should be saved). If you've never used application settings in the web.config, it's very simple. For the sake of the above example, we would add the following snippet between our <configuration> tags:
<appSettings>
<add key="FolderPath" value="uploads/"/>
</appSettings>
I can then access the value of this appSetting using
ResolveUrl("~/" & ConfigurationManager.AppSettings("FolderPath"))
or
ResolveUrl(String.Format("~/{0}", ConfigurationManager.AppSettings("FolderPath")))
Also, I stopped with the function to "getExcelSheets" because that's more specific to my application, and probably beyond the scope of this tutorial.
Additional Resources
I have a good habit of methodically saving useful bookmarks. Here is what I have from my "File Uploader" section...
CodeProject.com - File Upload with ASP.NET
Reading files in Javascript using File APIs
Stack Overflow - jQuery Ajax File Upload to ASP.NET web service with
JSON response
Drag and Drop Asynchronous File Upload <-- DEFINITELY THE MOST
USEFUL
I solved my problem. thank you guys. I used web services. in svc file i wrote these codes:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
public void upload(string data)
{
byte[] base64EncodedBytes = System.Convert.FromBase64String(data);
string strFileDestination = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "somefile.mp3";
File.WriteAllBytes(strFileDestination, base64EncodedBytes);
}
}
in js file i wrote this:
function uploadAudio(mp3Data) {
var reader = new FileReader();
reader.onload = function (event) {
Service.upload(event.target.result, helloWorldCallback, onFail);
function helloWorldCallback(result) {
alert(result);
}
function onFail(e) {
alert(e.get_message);
}
};
reader.readAsDataURL(mp3Data);
}

Adobe Air Mobile + Camera - Retaining image

I have a page that displays data about an object. At the top of the page is room for an icon, showing a picture of that object. Tapping this icon brings up a new page that allows the user to take a new picture, and save it as a temporary new picture for the object (not put in database, but should persist for the session)
Initial page:
private var source:Object = new Object();
protected function onInitialize():void {
source = navigator.poppedViewReturnedObject;
}
When setting source for the image later...
if (source != null) {
pic.source = source.object;
}
else {
pic.source = "no_picture_available_image.png";
}
2nd Page (User can take picture, and view new picture):
[Bindable]
private var imageSource:Object = null;
<s:Image id="pic" width="90%" height="75%" horizontalCenter="0" source="{imageSource}" />
After taking picture...
protected function mediaPromiseLoaded(evt:Event):void {
var loaderInfo:LoaderInfo = evt.target as LoaderInfo;
imageSource = loaderInfo.loader;
}
This does show the picture just taken correctly on this page.
To get back to old page, i use navigator.popView, and use:
override public function createReturnObject():Object {
return imageSource;
}
Unfortunately, it doesn't work. The imageSource isn't null when it is read from navigator.poppedViewReturnedObject, but no image is shown.
Does the LoaderInfo not persist after popping the view? Are the camera pics not automatically saved? I can't find answers to any of these questions, and I can't debug using the phone in my current environment.
After thinking about this a bit, don't return LoaderInfo.loader as the poppedViewReturnedObject. If I remember correctly, a DisplayObject can only be set as the source of one Image. Instead, return LoaderInfo.loader.content.bitmapData. That BitmapData should be the raw data used to display the image. This data can be used repeatedly to create images and can be set as the source of an Image.
Problem turned out to be in my first page's image declaration - I didn't set a width. Seemingly, the object being displayed couldn't handle not having a specified width.
Note that passing back the loader did work fine.

Can I print an HTMLLoader (pdf) in Adobe Air?

I'm using AlivePDF to create a PDF file, then save it to the desktop. I can then use an HTMLLoader to display my lovely PDF file.
Now, the print button in Adobe Reader works fine. However, there will be young children using the app, so I'd like to have a big "Print" button right above it.
I figured I could just start up a print job and feed it my HTMLLoader. This won't work because the HTML loader rasterizes the content.
Any suggestions?
One answer I have found in order to solve this problem is called Cross-scripting PDF content. The idea is that a PDF can have embedded JavaScript, which can be called from the JavaScript within the HTML page "housing" said PDF (object tag only, no embed).
This site was of particular help. I had to simplify the JavaScript from that page down quite a bit. I kept getting syntax errors.
I also need my program to generate the PDF and the HTML content. I cannot ship a single PDF with embedded JS and an HTML file pointing to it. They need to be dynamically generated by the user. Here is a basic rundown:
private function printText(text:String):void
{
var p:PDF=new PDF(Orientation.PORTRAIT, Unit.MM, Size.LETTER);
p.addPage();
p.addText(text, 100, 100);
p.addJavaScript(this.getJavascript());
var f:FileStream=new FileStream();
var html:File=File.desktopDirectory.resolvePath("exported.html");
f.open(html, FileMode.WRITE);
f.writeUTF(this.getHtml());
f.close();
var file:File=File.desktopDirectory.resolvePath("exported.pdf");
f.open(file, FileMode.WRITE);
var bytes:ByteArray=p.save(Method.LOCAL);
f.writeBytes(bytes);
f.close();
Now that we have our two files, HTML and PDF, we can view the PDF, and create a giant purple print button for our younger / sight-impared users.
if (HTMLLoader.pdfCapability == HTMLPDFCapability.STATUS_OK)
{
var win:PrintTitleWindow; //the window w/giant button
var htmlLoader:HTMLLoader=new HTMLLoader();
var url:URLRequest=new URLRequest(html.url);
htmlLoader.width=880;
htmlLoader.height=(appHeight - 150); //i figure out the height elsewhere
htmlLoader.load(url);
var holder:UIComponent=new UIComponent();
holder.addChild(htmlLoader);
win=PrintTitleWindow(PopUpManager.createPopUp(mainWindow, PrintTitleWindow, true));
win.width=900;
win.height=(appHeight - 50);
win.addChild(holder);
win.addContent(htmlLoader);
PopUpManager.centerPopUp(win);
}
}
Here is the JS and HTML I used. I'm adding these in here for laughs. I'm sure there is a better way to do this, but I'm tired and it is late.
private function getJavascript():String
{
return 'function myOnMessage(aMessage) { print({ bUI: true, bSilent: false, bShrinkToFit: true }); } function myOnDisclose(cURL,cDocumentURL) { return true; } function myOnError(error, aMessage) { app.alert(error); } var msgHandlerObject = new Object(); msgHandlerObject.onMessage = myOnMessage; msgHandlerObject.onError = myOnError; msgHandlerObject.onDisclose = myOnDisclose; this.hostContainer.messageHandler = msgHandlerObject;';
}
private function getHtml():String
{
return '<html><head><script>function callPdfFunctionFromJavascript(arg) { pdfObject = document.getElementById("PDFObj");pdfObject.postMessage([arg]);}</script></head><body><object id="PDFObj" data="exported.pdf" type="application/pdf" width="100%" height="100%"></object></body></html>';
}
The PrintTitleWindow is a simple title window with the print button on it. The code to print is simple.
myHtmlLoader.window.callPdfFunctionFromJavascript('Print');
Eh Voila! I have a gigantor-print-button like so:
(source: cetola.net)
Hitting that big purple print button is the same as hitting the print icon in the PDF toolbar. The difference for me is that my users, who could be elementary or middle-school kids, won't have to look around for the stupid button.
So, it's a long way around the block. Still, if you need to print and can't rely on that adobe toolbar button, here's your answer :) .

Create a button with an icon in actionscript

I want to create buttons with icons in Flex dynamically using Actionscript.
I tried this, with no success:
var closeButton = new Button();
closeButton.setStyle("icon", "#Embed(source='images/closeWindowUp.png");
I found an answer that works for me. In my .mxml file, I create Classes for the icons I will use:
// Classes for icons
[Embed(source='images/closeWindowUp.png')]
public static var CloseWindowUp:Class;
[Embed(source='/images/Down_Up.png')]
public static var Down_Up:Class;
[Embed(source='/images/Up_Up.png')]
public static var Up_Up:Class;
In the Actionscript portion of my application, I use these classes when dynamically creating buttons:
var buttonHBox:HBox = new HBox();
var closeButton:Button = new Button();
var upButton:Button = new Button();
var downButton:Button = new Button();
closeButton.setStyle("icon", SimpleWLM.CloseWindowUp);
buttonHBox.addChild(closeButton);
upButton.setStyle("icon", SimpleWLM.Up_Up);
buttonHBox.addChild(upButton);
downButton.setStyle("icon", SimpleWLM.Down_Up);
buttonHBox.addChild(downButton);
You can use this one option of dynamic change of button icon.
Embed your icons
[Embed(source='com/images/play.png')]
[Bindable]
public var imagePlay:Class;
[Embed(source='com/images/pause.png')]
[Bindable]
public var imagePause:Class;
Using one button to toggle play and pause of video
private function playpause():void
{
if (seesmicVideo.playing)
{
seesmicVideo.pause();
btn_play.setStyle("icon",imagePlay);
}
else
{
seesmicVideo.play();
btn_play.setStyle("icon",imagePause);
}
}
The error is in the quotes, there should be no quotes around the #Embed:
closeButton.setStyle("icon", #Embed(source="images/closeWindowUp.png"));
I was able to use an icon in my button with the following code:
<mx:Button id="buttonPlay" label="Play" click="playButtonClicked();" enabled="false" icon="#Embed('./play.png')"/>
the file play.png is in the same folder of the mxml file.
I am using Flash Builder version 4.6.
Edit: the question was about ActionScript and not MXML, but I leave this answer just for reference.
I'm assuming you're adding it to the stage?
Also, I think your Embed is missing a close quote / paren.
closeButton.setStyle("icon", "#Embed(source='images/closeWindowUp.png");
should be:
closeButton.setStyle("icon", "#Embed(source='images/closeWindowUp.png')");

Resources