I am new to Flex and needed some help setting up Web service client.
I have a web service of method:
public String printEchoStr(String str);
I am facing problem while creating action script to call this service. I am getting error:
1067: Implicit coercion of a value of type String to an unrelated type
generated.webservices:PrintEcho.
I am not sure if this is the correct way.
Thanks,
-H
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns:srv="generated.webservices.*"
creationComplete="initFunc()">
<mx:Script>
<![CDATA[
import generated.webservices.EchoService;
import generated.webservices.PrintEchoStrResultEvent;
import generated.webservices.PrintEchoResultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.controls.Alert;
import generated.webservices.PrintEchoStr;
import generated.webservices.PrintEcho;
public var myService:EchoService = new EchoService();
private function initFunc():void{
myService.addprintEchoStrEventListener(argPrintEchoStr);
/*--------------
1067: Implicit coercion of a value of type String to an unrelated type
generated.webservices:PrintEcho. at line below
----------------*/
myService.printEchoStr(textAreaPrintEchoStr.text);
myService.addEventListener(FaultEvent.FAULT,myServices_faultHandler);
}
public function argPrintEchoStr(event:PrintEchoStrResultEvent):void{
trace(event.result);
}
private function myServices_faultHandler(event:FaultEvent):void {
Alert.show(event.fault.faultString,"error with WebServices");
}
]]>
</mx:Script>
<mx:TextArea id ="textAreaPrintEchoStr"
x="81" y="125"/>
</mx:Application>
Generated source of EchoService.as
EchoService.as
package generated.webservices
{
import mx.rpc.AsyncToken;
import flash.events.EventDispatcher;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import flash.utils.ByteArray;
import mx.rpc.soap.types.*;
/**
* Dispatches when a call to the operation printEcho completes with success
* and returns some data
* #eventType PrintEchoResultEvent
*/
[Event(name="PrintEcho_result", type="generated.webservices.PrintEchoResultEvent")]
/**
* Dispatches when a call to the operation printEchoStr completes with success
* and returns some data
* #eventType PrintEchoStrResultEvent
*/
[Event(name="PrintEchoStr_result", type="generated.webservices.PrintEchoStrResultEvent")]
/**
* Dispatches when the operation that has been called fails. The fault event is common for all operations
* of the WSDL
* #eventType mx.rpc.events.FaultEvent
*/
[Event(name="fault", type="mx.rpc.events.FaultEvent")]
public class EchoService extends EventDispatcher implements IEchoService
{
private var _baseService:BaseEchoService;
/**
* Constructor for the facade; sets the destination and create a baseService instance
* #param The LCDS destination (if any) associated with the imported WSDL
*/
public function EchoService(destination:String=null,rootURL:String=null)
{
_baseService = new BaseEchoService(destination,rootURL);
}
//stub functions for the printEcho operation
/**
* #see IEchoService#printEcho()
*/
public function printEcho(printEcho:PrintEcho):AsyncToken
{
var _internal_token:AsyncToken = _baseService.printEcho(printEcho);
_internal_token.addEventListener("result",_printEcho_populate_results);
_internal_token.addEventListener("fault",throwFault);
return _internal_token;
}
/**
* #see IEchoService#printEcho_send()
*/
public function printEcho_send():AsyncToken
{
return printEcho(_printEcho_request.printEcho);
}
/**
* Internal representation of the request wrapper for the operation
* #private
*/
private var _printEcho_request:PrintEcho_request;
/**
* #see IEchoService#printEcho_request_var
*/
[Bindable]
public function get printEcho_request_var():PrintEcho_request
{
return _printEcho_request;
}
/**
* #private
*/
public function set printEcho_request_var(request:PrintEcho_request):void
{
_printEcho_request = request;
}
/**
* Internal variable to store the operation's lastResult
* #private
*/
private var _printEcho_lastResult:PrintEchoResponse;
[Bindable]
/**
* #see IEchoService#printEcho_lastResult
*/
public function get printEcho_lastResult():PrintEchoResponse
{
return _printEcho_lastResult;
}
/**
* #private
*/
public function set printEcho_lastResult(lastResult:PrintEchoResponse):void
{
_printEcho_lastResult = lastResult;
}
/**
* #see IEchoService#addprintEcho()
*/
public function addprintEchoEventListener(listener:Function):void
{
addEventListener(PrintEchoResultEvent.PrintEcho_RESULT,listener);
}
/**
* #private
*/
private function _printEcho_populate_results(event:ResultEvent):void
{
var e:PrintEchoResultEvent = new PrintEchoResultEvent();
e.result = event.result as PrintEchoResponse;
e.headers = event.headers;
printEcho_lastResult = e.result;
dispatchEvent(e);
}
//stub functions for the printEchoStr operation
/**
* #see IEchoService#printEchoStr()
*/
public function printEchoStr(printEchoStr:PrintEchoStr):AsyncToken
{
var _internal_token:AsyncToken = _baseService.printEchoStr(printEchoStr);
_internal_token.addEventListener("result",_printEchoStr_populate_results);
_internal_token.addEventListener("fault",throwFault);
return _internal_token;
}
/**
* #see IEchoService#printEchoStr_send()
*/
public function printEchoStr_send():AsyncToken
{
return printEchoStr(_printEchoStr_request.printEchoStr);
}
/**
* Internal representation of the request wrapper for the operation
* #private
*/
private var _printEchoStr_request:PrintEchoStr_request;
/**
* #see IEchoService#printEchoStr_request_var
*/
[Bindable]
public function get printEchoStr_request_var():PrintEchoStr_request
{
return _printEchoStr_request;
}
/**
* #private
*/
public function set printEchoStr_request_var(request:PrintEchoStr_request):void
{
_printEchoStr_request = request;
}
/**
* Internal variable to store the operation's lastResult
* #private
*/
private var _printEchoStr_lastResult:PrintEchoStrResponse;
[Bindable]
/**
* #see IEchoService#printEchoStr_lastResult
*/
public function get printEchoStr_lastResult():PrintEchoStrResponse
{
return _printEchoStr_lastResult;
}
/**
* #private
*/
public function set printEchoStr_lastResult(lastResult:PrintEchoStrResponse):void
{
_printEchoStr_lastResult = lastResult;
}
/**
* #see IEchoService#addprintEchoStr()
*/
public function addprintEchoStrEventListener(listener:Function):void
{
addEventListener(PrintEchoStrResultEvent.PrintEchoStr_RESULT,listener);
}
/**
* #private
*/
private function _printEchoStr_populate_results(event:ResultEvent):void
{
var e:PrintEchoStrResultEvent = new PrintEchoStrResultEvent();
e.result = event.result as PrintEchoStrResponse;
e.headers = event.headers;
printEchoStr_lastResult = e.result;
dispatchEvent(e);
}
//service-wide functions
/**
* #see IEchoService#getWebService()
*/
public function getWebService():BaseEchoService
{
return _baseService;
}
/**
* Set the event listener for the fault event which can be triggered by each of the operations defined by the facade
*/
public function addEchoServiceFaultEventListener(listener:Function):void
{
addEventListener("fault",listener);
}
/**
* Internal function to re-dispatch the fault event passed on by the base service implementation
* #private
*/
private function throwFault(event:FaultEvent):void
{
dispatchEvent(event);
}
}
}
myService.printEchoStr(textAreaPrintEchoStr.text);
printEchoStr method of EchoService class expects a PrintEcho object, but you're passing textAreaPrintEchoStr.text, which is a String
Related
I am building my own CMS system. And i did a lot of work with symfony in the past, now i wanna do all a bit more pro :) I want to render basic controller for admin dashboard witch contains a menu, systemnotifications on route "/admin" and then i want to set another controller for example "test" on route "/admin/test" and my problem is that all object notifications from controller named AdminController are not available in this second route "/admin/test", only on route "/admin"
Here my adminControler controller:
class AdminController extends Controller
{
/**
* #Route("/admin", name="adminDashboard")
*/
public function adminDashboard()
{
$loggedUser = $this->getUser()->getId();
$systemnotifications = $this->forward('App\Controller\SystemNotificationController::notif', [
'loggedUser' => $loggedUser
]);
return $this->render('admin/index.html.twig', [
'systemnotifications' => $systemnotifications
]);
}
}
Here my test controller:
class TestController extends Controller
{
/**
* #Route("/admin/test", name="test")
*/
public function test()
{
return $this->render('admin/dashboard/index.html.twig', [
]);
}
}
In twig is set, that adminController extends base.html.twig, and Test controller extends index.html.twig (this one witch is rendered from adminController.
My question is how to handle it properly with Symfony best practice. How i should set the Admin Controller for get systemnotifications object where is another Test Controller launched ?
Please help :)
There are two ways to do that the first is inyect in the twig the variable. example see this doc.
# config/packages/twig.yaml
twig:
# ...
globals:
# the value is the service's id
user_management: '#App\DataProvider\UserDataProvider'
# config/services.yaml
services:
'App\DataProvider\UserDataProvider':
arguments:
- '#session'
autoconfigure: false
The other way is more complicate, if you for example wants the responsability to render specific part of the page, like ... the barnav or the messages
Add this piece of code to the default twig:
{% block user_control %}
{{ render(controller('LayoutCoreBundle:User:index')) }}
{% endblock %}
<?php
namespace App\Controller;
use App\Event\ShowUserEvent;
use App\Event\ThemeEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use \stdClass;
class UserController extends EmitterController
{
/**
* #return \Symfony\Component\HttpFoundation\Response
*/
public function indexAction()
{
if (!$this->getDispatcher()->hasListeners(ThemeEvents::THEME_NAVBAR_USER)) {
return new Response();
}
/** #var ShowUserEvent $userEvent */
$userEvent = $this->triggerMethod(ThemeEvents::THEME_NAVBAR_USER, new ShowUserEvent());
$userClass = $userEvent->getUser();
$user = new stdClass();
$user->id = $userClass->getIdentifier();
$user->idEmployee = $userClass->getIdEmployee();
$user->setCompanyLogo = $userClass->getCompanyLogo();
$user->companyName = $userClass->getCompanyName();
$user->company = $userClass->getCompany();
$user->avatar = $userClass->getAvatar();
$user->fullName = $userClass->getName();
$user->menu = $userClass->getMenu();
$user->role = $userClass->getRolname();
return $this->render(
'header/index.html.twig',
[
'userJson' => $user,
]
);
}
}
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class EmitterController extends AbstractController
{
/**
* #var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* #param EventDispatcherInterface $dispatcher
*/
public function __construct(EventDispatcherInterface $dispatcher)
{
$this->eventDispatcher = $dispatcher;
}
/**
* #return EventDispatcherInterface
*/
protected function getDispatcher()
{
return $this->eventDispatcher;
}
/**
* #param string $eventName
*
* #return bool
*/
protected function hasListener($eventName)
{
return $this->getDispatcher()->hasListeners($eventName);
}
/**
* Will look for a method of the format "on<CamelizedEventName>" and call it with the event as argument.
*
*
* Then it will dispatch the event as normal via the event dispatcher.
*
* #param $eventName
* #param Event $event
*
* #return Event
*/
protected function triggerMethod($eventName, Event $event)
{
$method = sprintf('on%s', Container::camelize(str_replace('.', '_', $eventName)));
if (is_callable([$this, $method])) {
call_user_func_array([$this, $method], [$event]);
}
if ($event->isPropagationStopped()) {
return $event;
}
$this->getDispatcher()->dispatch($eventName, $event);
return $event;
}
}
interface ThemeEvents
{
/**
* Used to receive notification data
*/
public const THEME_NOTIFICATIONS = 'theme.notifications';
/**
* Used to receive message data
*/
public const THEME_MESSAGES = 'theme.messages';
/**
* Used to receive task data
*/
public const THEME_TASKS = 'theme.tasks';
/**
* Used to receive the current user for the navbar
*/
public const THEME_NAVBAR_USER = 'theme.navbar_user';
/**
* Used to receive breadcrumb data
*/
public const THEME_BREADCRUMB = 'theme.breadcrumb';
/**
* Used to receive the current user for the sidebar
*/
public const THEME_SIDEBAR_USER = 'theme.sidebar_user';
/**
* Used to receive the sidebar menu data
*/
public const THEME_SIDEBAR_SETUP_MENU = 'theme.sidebar_setup_menu';
}
class ShowUserEvent extends ThemeEvent
{
/**
* #var UserInterface
*/
protected $user;
/**
* #var bool
*/
protected $showProfileLink = true;
/**
* #var bool
*/
protected $showLogoutLink = true;
/**
* #var NavBarUserLink[]
*/
protected $links = [];
/**
* #param UserInterface $user
* #return ShowUserEvent
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* #return UserInterface
*/
public function getUser()
{
return $this->user;
}
/**
* #return NavBarUserLink[]
*/
public function getLinks()
{
return $this->links;
}
/**
* #param NavBarUserLink $link
* #return ShowUserEvent
*/
public function addLink(NavBarUserLink $link)
{
$this->links[] = $link;
return $this;
}
/**
* #return bool
*/
public function isShowProfileLink()
{
return $this->showProfileLink;
}
/**
* #param bool $showProfileLink
* #return ShowUserEvent
*/
public function setShowProfileLink($showProfileLink)
{
$this->showProfileLink = $showProfileLink;
return $this;
}
/**
* #return bool
*/
public function isShowLogoutLink()
{
return $this->showLogoutLink;
}
/**
* #param bool $showLogoutLink
* #return ShowUserEvent
*/
public function setShowLogoutLink($showLogoutLink)
{
$this->showLogoutLink = $showLogoutLink;
return $this;
}
}
class ThemeEvent extends Event
{
}
And then only you need a evensuscriber
class NavbarUserSubscriber implements EventSubscriberInterface
{
/**
* #var Security
*/
protected $security;
/**
* #param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* #return array
*/
public static function getSubscribedEvents(): array
{
return [
ThemeEvents::THEME_NAVBAR_USER => ['onShowUser', 100],
ThemeEvents::THEME_SIDEBAR_USER => ['onShowUser', 100],
];
}
/**
* #param ShowUserEvent $event
* #throws \Exception
*/
public function onShowUser(ShowUserEvent $event)
{
if (null === $this->security->getUser()) {
return;
}
/** #var User $user */
$user = $this->security->getUser();
$event->setUser($user);
}
}
#templates/header/index.html.twig
<script type="text/javascript">
var user = {{ userJson | json_encode() | raw }};
</script>
I've got three classes. The File-Class has a reference to Foobar and Game inherits from Foobar. There are some other Classes which also inherit from Foobar but i left them out as they aren't relevant here. I also left out some unrelevant fields and their getters and setters.
The plan is that every Game has two images, the mainImage and the secondaryImage. I've put those fields into a seperate class from which Game inherits because i need them for a few other classes too.
My problem is that if I load the games from the database as soon as i try to iterate over them I get the following exception:
Notice: Undefined index: in C:\xampp\htdocs\Symfony\vendor\doctrine\mongodb-odm\lib\Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo.php line 1293
For reference here are the lines of ClassMetadataInfo.php
public function getPHPIdentifierValue($id)
{
$idType = $this->fieldMappings[$this->identifier]['type'];
return Type::getType($idType)->convertToPHPValue($id);
}
Here are my classes
File-Class:
namespace Project\MainBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class File
{
/**
* #MongoDB\Id(strategy="INCREMENT")
*/
protected $id;
/**
* #MongoDB\ReferenceOne(targetDocument="Foobar", inversedBy="mainImage")
*/
private $mainImage;
/**
* #MongoDB\ReferenceOne(targetDocument="Foobar", inversedBy="secondaryImage")
*/
private $secondaryImage;
/**
* Get id
*/
public function getId()
{
return $this->id;
}
public function setMainImage($mainImage)
{
$this->mainImage = $mainImage;
return $this;
}
public function getMainImage()
{
return $this->mainImage;
}
public function setSecondaryImage($secondaryImage)
{
$this->secondaryImage = $secondaryImage;
return $this;
}
public function getSecondaryImage()
{
return $this->secondaryImage;
}
}
Foobar-Class:
namespace Project\MainBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\MappedSuperclass
*/
abstract class Foobar
{
/**
* #MongoDB\Id(strategy="INCREMENT")
*/
protected $id;
/**
* #MongoDB\ReferenceOne(targetDocument="File", mappedBy="mainImage")
*/
protected $mainImage;
/**
* #MongoDB\ReferenceOne(targetDocument="File", mappedBy="secondaryImage")
*/
protected $secondaryImage;
/**
* Get id
*/
public function getId()
{
return $this->id;
}
/**
* Set mainImage
*/
public function setMainImage($file)
{
$file->setMainImage($this);
$this->mainImage = $file;
return $this;
}
/**
* Get mainImage
*/
public function getMainImage()
{
return $this->mainImage;
}
/**
* Set secondaryImage
*/
public function setSecondaryImage($file)
{
$file->setSecondaryImage($this);
$this->secondaryImage = $file;
return $this;
}
/**
* Get secondaryImage
*/
public function getSecondaryImage()
{
return $this->secondaryImage;
}
}
Game-Class:
namespace Project\MainBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class Game extends Foobar
{
/**
* #MongoDB\String
*/
private $name;
/**
* Set name
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*/
public function getName()
{
return $this->name;
}
}
Though it doesn't really matter but here is my function i want to execute:
$dm = $this->get('doctrine_mongodb')->getManager();
$games_all = $dm->getRepository("ProjectMainBundle:Game")->createQueryBuilder()->sort('id', 'ASC')->getQuery()->execute();
foreach ($games_all as $singlegame) { // it breaks here
// Here i would do stuff
}
Is this a bug in Doctrine ODM or am I doing something wrong? Are the classes correct? I have tried everything but it just wont work.
I think it is too late for your question, but maybe there are other users having the same problem (as me).
The problem is related to Foobar being a MappedSuperclass. Had the same problem as described by you and at https://github.com/doctrine/mongodb-odm/issues/241.
Solution is to not reference the abstract class Foobar (=MappedSuperclass) but a concrete implementation (=Document) - as in your case - Game.
See also Doctrine ODM returns proxy object for base class instead of sub-classed document
I am trying to show the page displayed using StageWebView as a bitmap. As per the documentation we need to use DrawViewPortToBitMapData. While displaying the bitmap in a
UIComponent, the image is getting stretched. How can I prevent that?
bitmapData = new BitmapData(webView.viewPort.width, webView.viewPort.height, false,
0x000000 );
webView.drawViewPortToBitmapData(bitmapData);
webViewBmp = new Bitmap(bitmapData);
webView.stage = null;
uiComponent = new UIComponent;
uiComponent.width=webView.viewPort.width;
uiComponent.height=webView.viewPort.height;
uiComponent.addChild(webViewBmp);
I dont think you need to apply width/height to the uicomponent. it should be ok just by adding the bitmap to it. What you seem to be doing is stretching the uicomponent even though you have already added the bitmap at its correct size.
You should set scale to 1 on uiComponet. If you set applicationDPI (let's say to 160dpi), Flex is automatically scalling uiComponent according to the device DPI, setting scaleX and scaleY to runtimeDPI/160.
Try something like this:
uiComponent.scaleX=160/parentApplication.runtimeDPI;
uiComponent.scaleY=160/parentApplication.runtimeDPI;
so scaleX and scaleY ends with:
runtimeDPI/160 (done by flex) * 160/runtimeDPI = 1 :)
I know this is old, but this worked for me:
var r:Rectangle = wView.viewPort;
var bd:BitmapData = new BitmapData(r.width, r.height);
wView.drawViewPortToBitmapData(bd);
var bmp:Bitmap = new Bitmap(bd);
bmp.width = bd.width * (Capabilities.screenResolutionX / 320);
bmp.height = bd.height * (Capabilities.screenResolutionY / 480);
Hope it helps!
Use uiComponent.unscaledWidth & unscaledHeight. This is my working component, altered flexcapacitor code - original here: http://flexcapacitor.googlecode.com/svn-history/r5/trunk/mobilelibrary/src/com/flexcapacitor/controls/WebView.as
look at takeSnapshot:
snapshotBitmapData = new BitmapData(_webView.viewPort.width, _webView.viewPort.height);
webView.drawViewPortToBitmapData(snapshotBitmapData);
webViewBitmap = new Bitmap(snapshotBitmapData);
webViewBitmap.width = unscaledWidth;
webViewBitmap.height = unscaledHeight;
addChild(webViewBitmap);
hideWebView();
full code:
package ctrls {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.LocationChangeEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.media.StageWebView;
import flash.ui.Keyboard;
import mx.core.FlexGlobals;
import mx.core.UIComponent;
/** #copy flash.media.StageWebView#ErrorEvent.ERROR */
[Event(name="error", type="flash.events.ErrorEvent")]
/** #copy flash.media.StageWebView#Event.COMPLETE */
[Event(name="complete", type="flash.events.Event")]
/** #copy flash.media.StageWebView#LocationChangeEvent.LOCATION_CHANGING */
[Event(name="locationChanging", type="flash.events.LocationChangeEvent")]
/** #copy flash.media.StageWebView#LocationChangeEvent.LOCATION_CHANGE */
[Event(name="locationChange", type="flash.events.LocationChangeEvent")]
/**
* This class wraps the standard StageWebView with a UIComponent.
* This allows it to be sized and positioned in the same way
* any UIComponent would. <br/><br/>
*
* The StageWebView class documentation follows:<br/>
* #copy flash.media.StageWebView
* */
public class WebView extends UIComponent {
//==================================================================================================
protected var _webView:StageWebView;
private var _source:String;
private var _visibleChanged:Boolean;
private var _sourceChanged:Boolean;
/** #copy flash.media.StageWebView#viewPort */
public function get viewPort():Rectangle { return _webView ? _webView.viewPort : null; }
/** #copy flash.media.StageWebView#dispose() */
public function dispose():void { hideWebView(true); }
/** #copy flash.media.StageWebView#assignFocus() */
public function assignFocus(direction:String = "none"):void { webView.assignFocus(direction); }
/** #copy flash.media.StageWebView#drawViewPortToBitmapData() */
public function drawViewPortToBitmapData(bitmap:BitmapData):void { webView.drawViewPortToBitmapData(bitmap); }
/** #copy flash.media.StageWebView#title */
public function get title():String { return _webView ? _webView.title : null; }
/** #copy flash.media.StageWebView#isHistoryBackEnabled() */
public function get isHistoryBackEnabled():Boolean { return _webView ? _webView.isHistoryBackEnabled : false; }
/** #copy flash.media.StageWebView#isHistoryForwardEnabled() */
public function get isHistoryForwardEnabled():Boolean { return _webView ? _webView.isHistoryForwardEnabled : false; }
/** #copy flash.media.StageWebView#historyBack() */
public function historyBack():void { if(_webView) _webView.historyBack(); }
/** #copy flash.media.StageWebView#historyForward() */
public function historyForward():void { if(_webView) _webView.historyForward(); }
/** #copy flash.media.StageWebView#reload() */
public function reload():void { webView.reload(); }
/** #copy flash.media.StageWebView#stop() */
public function stop():void { if(_webView) webView.stop(); }
/** Load the URL passed in or load the URL specified in the source property
* #see flash.media.StageWebView#loadURL() */
public function load(url:String = null):void { webView.loadURL(url ? _source = url : source); }
override public function set visible(value:Boolean):void {
super.visible = value;
_visibleChanged = true;
invalidateProperties();
invalidateSize();
}
/** #private */
public function get source():String { return _source; }
/**
* Source URL for stage web view.
* #see flash.media.StageWebView#loadURL()
* */
[Bindable]
public function set source(value:String):void {
_source = value;
_sourceChanged = true;
invalidateProperties();
invalidateSize();
}
//==================================================================================================
/**
* Wrapper for StageWebView
*
* #copy flash.media.StageWebView
*/
public function WebView() {
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
focusEnabled = false;
}
/** #private */
public function get webView():StageWebView {
if(!_webView) webView = new StageWebView();
return _webView; }
/** #copy flash.media.StageWebView */
public function set webView(value:StageWebView):void {
if(_webView == value) return;
if(_webView) {
_webView.removeEventListener(Event.COMPLETE, completeHandler);
_webView.removeEventListener(ErrorEvent.ERROR, errorHandler);
_webView.removeEventListener(FocusEvent.FOCUS_IN, focusInViewHandler);
_webView.removeEventListener(FocusEvent.FOCUS_OUT, focusOutViewHandler);
_webView.removeEventListener(LocationChangeEvent.LOCATION_CHANGING, locationChangingHandler);
_webView.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangeHandler); }
_webView = value;
_webView.addEventListener(Event.COMPLETE, completeHandler);
_webView.addEventListener(ErrorEvent.ERROR, errorHandler);
_webView.addEventListener(FocusEvent.FOCUS_IN, focusInViewHandler);
_webView.addEventListener(FocusEvent.FOCUS_OUT, focusOutViewHandler);
_webView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, locationChangingHandler);
_webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangeHandler);
_webView.stage = visible ? stage : null;
_visibleChanged = false;
if(source) _webView.loadURL(_source);
_sourceChanged = false;
invalidateDisplayList();
}
/** Hides the web view #see flash.media.StageWebView#stage */
public function hideWebView(destroy:Boolean = false):void {
if(_webView == null) return;
_webView.stage = null;
if(!destroy) return;
_webView.viewPort = null;
_webView.dispose();
_webView = null;
}
/** Displays the web view #see flash.media.StageWebView#stage */
public function showWebView():void {
if(_webView != null) {
webView.stage = stage;
return; }
_visibleChanged = true;
invalidateProperties();
invalidateSize();
invalidateDisplayList(); }
/** #copy mx.core.UIComponent#commitProperties() */
override protected function commitProperties():void {
super.commitProperties();
if(_visibleChanged) {
webView.stage = visible ? stage : null;
_visibleChanged = false; }
if(_sourceChanged) {
webView.loadURL(source);
_sourceChanged = false; }}
//==================================================================================================
/** Flag indicating if a snapshot is being shown */
[Bindable]
public var isSnapshotVisible:Boolean;
/**
* When calling takeSnapshot or setting snapshotMode to true this
* property will contain the bitmap data of the view port.
* */
public var snapshotBitmapData:BitmapData;
/**
* When calling takeSnapshot or setting snapshotMode a snapshot of
* the Stage Web View is taken and added to the stage. This is a
* reference to the displayed bitmap.
* */
public var webViewBitmap:Bitmap;
/**
* #private
* */
public function get snapshotMode():Boolean {
return isSnapshotVisible;
}
/**
* When set to true hides the stage web view and displays a non-interactive
* snapshot of the Stage Web View when the property was set to true.
* */
public function set snapshotMode(value:Boolean):void {
value ? takeSnapshot() : removeSnapshot();
}
/**
* Creates a snapshot of the Stage Web View at the point of this call
* and displays that instead of the actual Stage Web View.
* Use removeSnapshot to dispose of the snapshot and show the web contents again.
*
* #see isSnapshotVisible
* #see flash.media.StageWebView#drawViewPortToBitmapData()
* */
public function takeSnapshot():BitmapData {
destroySnapshot();
snapshotBitmapData = new BitmapData(_webView.viewPort.width, _webView.viewPort.height);
webView.drawViewPortToBitmapData(snapshotBitmapData);
webViewBitmap = new Bitmap(snapshotBitmapData);
webViewBitmap.width = unscaledWidth;
webViewBitmap.height = unscaledHeight;
addChild(webViewBitmap);
hideWebView();
isSnapshotVisible = true;
return snapshotBitmapData;
}
/**
* Removes the bitmap snapshot of the Stage Web View from the display list
* and displays the actual Stage Web View.
* #copy flash.media.StageWebView#drawViewPortToBitmapData()
* */
public function removeSnapshot():void {
destroySnapshot();
showWebView();
}
/**
* Removes the web view snapshot from the display list and disposes of the
* bitmap data
* */
private function destroySnapshot():void {
if (webViewBitmap) {
if (webViewBitmap.parent) removeChild(webViewBitmap);
if (webViewBitmap.bitmapData) webViewBitmap.bitmapData.dispose();
webViewBitmap = null;
}
if (snapshotBitmapData) {
snapshotBitmapData.dispose();
snapshotBitmapData = null;
}
isSnapshotVisible = false;
}
//==================================================================================================
/**
* If enabled adds support for the back and search keys.
* Back key navigates back in web view history and search navigates forward.
* */
public var navigationSupport:Boolean;
/**
* If enabled adds a keyboard listener to the stage.
* This handles when the component does not have focus
* */
public var addKeyHandlerToStage:Boolean;
/**
* KeyCode to use when navigation support is enabled.
* Default is Keyboard.BACK
* */
public var backKeyCode:int = Keyboard.BACK;
/**
* KeyCode to use when navigation support is enabled.
* Default is Keyboard.SEARCH
* */
public var forwardKeyCode:int = Keyboard.SEARCH;
/**
* #copy mx.core.UIComponent#measure()
* */
override protected function measure():void {
super.measure();
measuredWidth=480;
measuredMinWidth=120;
measuredHeight=320;
measuredMinHeight=160;
}
/**
* #copy mx.core.UIComponent#updateDisplayList()
* */
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
// NOTE: IF THE WEBVIEW IS NOT BEING SIZED CORRECTLY
// check if focusEnabled is true. If it is then the soft keyboard may not be dispatching the
// deactivate event because the webview has focus when it is dispatched. set to false
// position according to the container rather than the stage
var runtimeDPI:int = FlexGlobals.topLevelApplication.runtimeDPI;
var applicationDPI:int = FlexGlobals.topLevelApplication.applicationDPI;
var point:Point = localToGlobal(new Point());
var scaleFactor:Number = runtimeDPI / applicationDPI;
var scaledWidth:int = width * scaleFactor;
var scaledHeight:int = height * scaleFactor;
webView.viewPort = new Rectangle(point.x, point.y, scaledWidth, scaledHeight);
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/** When the stage property is available add it to the web view */
public function addedToStage(event:Event):void {
// adds support for keyboard events when not in focus
if (navigationSupport && addKeyHandlerToStage)
stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler);
_visibleChanged = true;
invalidateProperties();
invalidateDisplayList();
}
/** When removed from the stage remove the web view */
protected function removedFromStage(event:Event):void {
hideWebView();
// removes support for keyboard events when not in focus
if (navigationSupport && addKeyHandlerToStage)
stage.removeEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler );
}
/** Dispatches a focus in event when the web view gains focus. */
protected function focusInViewHandler(event:FocusEvent):void {
//webView.assignFocus();
if (hasEventListener(event.type))
dispatchEvent(event);
}
/** Dispatches a focus out event when the web view gains focus. */
protected function focusOutViewHandler(event:FocusEvent):void {
//webView.assignFocus(FocusDirection.TOP);
if (hasEventListener(event.type))
dispatchEvent(event);
}
/** Dispatches a focus in event when the web view gains focus. */
override protected function keyDownHandler(event:KeyboardEvent):void {
if (navigationSupport) {
if (event.keyCode == backKeyCode && webView.isHistoryBackEnabled ) {
webView.historyBack();
event.preventDefault();
}
if (navigationSupport && event.keyCode == forwardKeyCode && webView.isHistoryForwardEnabled ) {
webView.historyForward();
}
}
super.keyDownHandler(event);
}
/** Dispatched when the page or web content has been fully loaded */
protected function completeHandler(event:Event):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
/** Dispatched when the location is about to change */
protected function locationChangingHandler(event:Event):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
/** Dispatched when the location has changed */
protected function locationChangeHandler(event:Event):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
/** Dispatched when an error occurs */
protected function errorHandler(event:ErrorEvent):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
}}
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="init();" initialize="initializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
import sandacreative.sqlite.events.StatementSuccessEvent;
import sandacreative.sqlite.SQLiteManager;
private var database:SQLiteManager = SQLiteManager.getInstance();
protected function initializeHandler(event:FlexEvent):void
{ trace("inside initializehandler");
database.start("Users.db", "Users", "CREATE TABLE Users(UserId VARCHAR(150) PRIMARY KEY, UserName VARCHAR(150))");
database.addEventListener(SQLiteManager.COMMAND_EXEC_SUCCESSFULLY, onSelectResult);
database.addEventListener(SQLiteManager.COMMAND_EXEC_FAILED, function():void {
trace("fail!");
});
readEntries();
}
private function insertEntry():void
{
var sql:String = "INSERT INTO Users VALUES('"+nameField.text+"');";
database.executeCustomCommand(sql);
}
// SQLite Ends Here*/
import flash.media.Camera;
import sandacreative.WebCam;
import sandacreative.Base64;
import mx.core.UIComponent;
import mx.graphics.codec.JPEGEncoder;
private var webCam:WebCam;
private function init():void {
webCam = new WebCam(160, 120);
var ref:UIComponent = new UIComponent();
preview.removeAllChildren();
preview.addChild(ref);
ref.addChild(webCam);
}
</fx:Script>
<mx:Panel width="180" height="160" id="preview" title="Snapshotr" x="158" y="343"/>
<mx:Button label="Save" id="submit" x="280" y="521" width="100" enabled="true" click="insertEntry();"/>
init() initiates a cam and that works properly .. while initiliseHandler() creates a sqlite table. But the table is not created and when i try to save it shows the error
Error: Error #3104: A SQLConnection must be open to perform this operation.
at Error$/throwError()
at flash.data::SQLStatement/checkAllowed()
at flash.data::SQLStatement/checkReady()
at flash.data::SQLStatement/execute()
at sandacreative.sqlite::SQLiteManager/executeCustomCommand()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\sqlite\SQLiteManager.as:238]
at sandacreative::Main/insertEntry()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\Main.mxml:34]
at sandacreative::Main/__submit_click()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\Main.mxml:153]
SQLiteManager.as
package sandacreative.sqlite
{
import sandacreative.sqlite.events.StatementSuccessEvent;
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
public class SQLiteManager extends EventDispatcher implements ISQLiteManager
{
/**
* Database file name and extension
*/
public var dbFullFileName:String;
/**
* Database Name
*/
public var tableName:String;
/**
* SQL command to create the database
*/
public var createDbStatement:String;
// datsbase apis instances
protected var connection:SQLConnection;
protected var statement:SQLStatement;
protected var sqlFile:File;
// repeated sql command
protected var repeateFailCallBack:Function;
protected var repeateCallBack:Function;
protected var repeateSqlCommand:String = "";
// events strings
public static var COMMAND_EXEC_SUCCESSFULLY:String = "commandExecSuccesfully";
public static var DATABASE_CONNECTED_SUCCESSFULLY:String = "databaseConnectedSuccessfully";
public static var COMMAND_EXEC_FAILED:String = "commandExecFailed";
public static var DATABASE_READY:String = "databaseReady";
// Singleton instance.
protected static var instance:SQLiteManager;
/**
* Enforce singleton design pattern.
*
* #param enforcer
*
*/
public function SQLiteManager(enforcer:AccessRestriction)
{
if (enforcer == null)
throw new Error("Error enforcer input param is undefined" );
}
/**
* Opens a database connection.
*
* #param dbFullFileName the database file name for instance: Users.sql
* #param tableName holds the database name, for instance: Users
* #param createTableStatement holds the create database statment for instance: CREATE TABLE Users(userId VARCHAR(150) PRIMARY KEY, UserName VARCHAR(150))
*
*/
public function start(dbFullFileName:String, tableName:String, createTableStatement:String):void
{
this.dbFullFileName = dbFullFileName;
this.tableName = tableName;
this.createDbStatement = createTableStatement;
connection = new SQLConnection();
sqlFile = File.applicationStorageDirectory.resolvePath(dbFullFileName);
try
{
connection.open(sqlFile);
this.dispatchEvent(new Event(DATABASE_CONNECTED_SUCCESSFULLY));
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
fail();
}
}
/**
* Close connection
*
*/
public function close():void
{
connection.close();
}
/**
* Test the table to ensure it exists. Sends a fail call back function to create the table if
* it doesn't exists.
*
*/
public function testTableExists():void
{
var sql:String = "SELECT * FROM "+tableName+" LIMIT 1;";
executeCustomCommand(sql, this.onDatabaseReady, this.createTable );
}
/**
* Method to create the database table.
*
*/
private function createTable():void
{
statement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = createDbStatement;
statement.execute();
statement.addEventListener(SQLEvent.RESULT, onDatabaseReady);
}
/**
* Common sql command: select all entries in database
*
* #param callback
* #param failCallback
*
*/
public function executeSelectAllCommand(callback:Function=null, failCallback:Function=null):void
{
var sql:String = "SELECT * FROM "+tableName+";";
executeCustomCommand(sql, callback, failCallback);
}
/**
* Common sql command: delete all entries in database
*
* #param callback
*
*/
public function executeDeleteAllCommand(callback:Function=null):void
{
var sql:String = "DELETE * FROM "+tableName+";";
executeCustomCommand(sql, callback);
}
/**
* Method to execute a SQL command
*
* #param sql SQL command string
* #param callback success call back function to impliment if necessery
* #param failCallBack fail call back function to impliment if necessery
*
*/
public function executeCustomCommand(sql:String, callBack:Function=null, failCallBack:Function=null):void
{
statement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = sql;
if (callBack!=null)
{
statement.addEventListener(SQLEvent.RESULT, callBack);
}
else
{
statement.addEventListener(SQLEvent.RESULT, onStatementSuccess);
}
statement.addEventListener(SQLErrorEvent.ERROR, function():void {
fail();
});
try
{
statement.execute();
}
catch (error:SQLError)
{
this.handleErrors(error, sql, callBack, failCallBack);
}
}
/**
* Utility method to clean bad characters that can break SQL commands
*
* #param str
* #return
*
*/
public static function removeBadCharacters(str:String):String
{
var retVal:String = str.split("'").join("’’");
return retVal;
}
// ------------------------------HANDLERS----------------------------
/**
* Method to handle SQL command that create the dataabase.
* If the method was created due to a fail SQL command method checks if need to repeate any SQL command.
*
* #param event
*
*/
private function onDatabaseReady(event:Event=null):void
{
var evt:Event = new Event(DATABASE_READY);
this.dispatchEvent(evt);
if (repeateSqlCommand != "")
{
this.executeCustomCommand(repeateSqlCommand, repeateCallBack, repeateFailCallBack);
repeateSqlCommand = "";
repeateFailCallBack = null;
repeateCallBack = null;
}
}
/**
* Handle successful calls
* #param event
*
*/
private function onStatementSuccess(event:SQLEvent):void
{
var results:Object = statement.getResult();
var evt:StatementSuccessEvent = new StatementSuccessEvent(COMMAND_EXEC_SUCCESSFULLY, results);
this.dispatchEvent(evt);
}
/**
* Error handler
*
* #param error
* #param sql
* #param callBack
* #param failCallBack
*
*/
private function handleErrors(error:SQLError, sql:String, callBack:Function, failCallBack:Function):void
{
trace("Error message:", error.message);
trace("Details:", error.details);
if (error.details == "no such table: '"+tableName+"'")
{
repeateSqlCommand = sql;
repeateFailCallBack = failCallBack;
repeateCallBack = callBack;
createTable();
}
else
{
if (failCallBack != null)
{
failCallBack();
}
else
{
fail();
}
}
}
/**
* Handler for fail calls
*
* #param event
*
*/
private function fail(event:Event=null):void
{
var evt:Event = new Event(COMMAND_EXEC_FAILED);
this.dispatchEvent(evt);
close();
}
/**
* Method function to retrieve instance of the class
*
* #return The same instance of the class
*
*/
public static function getInstance():SQLiteManager
{
if( instance == null )
instance = new SQLiteManager(new AccessRestriction());
return instance;
}
}
}
class AccessRestriction {} // can this happen ?
ISQLiteManager.as
package sandacreative.sqlite
{
/**
* Describes the contract for Objects that serve as a central point to access SQLite database.
*
* #author Elad Elrom
*
*/
public interface ISQLiteManager
{
function start(dbFullFileName:String, tableName:String, createTableStatement:String):void
function close():void
}
}
StatementSucessEvent.as
package sandacreative.sqlite.events
{
import flash.events.Event;
public class StatementSuccessEvent extends Event
{
/**
* Holds the event string name
*/
public static var COMMAND_EXEC_SUCCESSFULLY:String = "command_exec_succesfully";
/**
* Holds results object
*/
public var results:Object;
/**
* Default constructor
*
* #param type event name
* #param videoList video list collection
*
*/
public function StatementSuccessEvent(type:String, results:Object)
{
super(type);
this.results = results;
}
}
}
I took this code from Elad Elrom
Is that because i used both applicationComplete and Initilize together ? Please help
The error is kind of obvious. Your database hasn't been created/connected yet before your button is pressed. Also, the createTable function is never called because you never keep state on your connection property.
Before any statement is executed, you should always check that the DB is connected. For all you know, the connection failed.
And thirdly (and probably most important), you are doing a synchronous execution because you used connection.open. For this to work, you need to do connection.begin() before executing any statements and finish with connection.commit(). I think the better way for you to go here is to use connection.openAsync instead to create an asynchronous execution which is easier to manage and probably what you wanted to do. Only use synchronous if the order of the statements are important (like in a transaction or if one statement is dependent on another).
When attempting to use Joshua Bloch's "Builder Pattern" [Item 2 in Effective Java Second Edition] with reflection [object = constructors[index].newInstance(constructorParameterValues);] the following exception occurs:
java.lang.IllegalAccessException: Class info.soaj.core.util.SjUtilReflection can not access a member of class info.soaj.core.attribute.SjAttributesForThrowable with modifiers "private"
Note: This has been resolved. The accessible (private) constructor was being discarded and a non-accessible (override = false) was being attempted. Bottom Line: Programmer Error
An example Builder Class follows:
package info.soaj.core.attribute;
import info.soaj.core.attribute.internal.SjAttributesForStronglyTypedWrappers;
import info.soaj.core.internal.string.SjPopulatedClassName;
import info.soaj.core.internal.string.SjPopulatedMethodName;
import info.soaj.core.util.internal.SjUtilThrowable;
import java.io.Serializable;
/**
* <p>
* The "Builder" pattern as documented by Joshua Bloch ("Effective Java" -
* Second Edition) is utilized to handle the variable number of required and
* optional parameters.
* </p>
*
* <p style="font-family:Verdana; font-size:10px; font-style:italic"> Copyright
* (c) 2006 - 2008 by Global Technology Consulting Group, Inc. at <a
* href="http://gtcGroup.com">gtcGroup.com </a>. </p>
*
* #author MarvinToll#gtcGroup.com
* #since v. 1.0
*/
public class SjAttributesExample implements Serializable {
/** UID */
private static final long serialVersionUID = 1L;
/** The name of class throwing the exception. */
protected final SjPopulatedClassName classname;
/** The name of method throwing the exception. */
protected final SjPopulatedMethodName methodname;
/**
* Suppresses logging; default is <code>false</code>.
*/
protected final boolean suppressLoggingOnly;
/**
* Constructor - private
*
* #param builderThrowable
*/
private SjAttributesExample(final BuilderThrowable builderThrowable) {
this.classname = builderThrowable.classname;
this.methodname = builderThrowable.methodname;
this.suppressLoggingOnly = builderThrowable.suppressLoggingOnly;
}
/**
* This static member immutable class is used to implement the builder
* pattern.
*
* #author MarvinToll#gtcGroup.com
* #since v. 1.0
*/
public static class BuilderThrowable {
/** Class name. */
private static final String CLASS_NAME = BuilderThrowable.class
.getName();
// Required attributes.
/** The name of class throwing the exception. */
protected final SjPopulatedClassName classname;
/** The name of method throwing the exception. */
protected final SjPopulatedMethodName methodname;
// Optional attributes.
/** Prevents action from occurring. Default is false. */
protected boolean suppressLoggingOnly = false;
/**
* Constructor
*
* #param classname
* #param methodname
*/
public BuilderThrowable(final String classname, final String methodname) {
super();
final String Method_Name = "BuilderThrowable";
// What happens when handling an exception throws an exception?
try {
this.classname = new SjPopulatedClassName(classname,
new SjAttributesForStronglyTypedWrappers(CLASS_NAME,
Method_Name));
this.methodname = new SjPopulatedMethodName(methodname,
new SjAttributesForStronglyTypedWrappers(CLASS_NAME,
Method_Name));
} catch (final RuntimeException e) {
// Log the contextual details.
SjUtilThrowable.logExceptionOccuredWhileThrowingException(
CLASS_NAME, Method_Name, e);
throw e;
}
return;
}
/**
* This method sets a flag to suppress logging.
*
* #param isLoggingSuppressed
* #return BuilderThrowable
*/
public BuilderThrowable suppressLoggingOnly(
final boolean isLoggingSuppressed) {
this.suppressLoggingOnly = isLoggingSuppressed;
return this;
}
/**
* This method is used for instantiating this class.
*
* #return SjAttributesForThrowable
*/
#SuppressWarnings("synthetic-access")
public SjAttributesExample build() {
return new SjAttributesExample(this);
}
}
/**
* This method returns an attribute.
*
* #return String - Returns the <code>classname</code> attribute.
*/
public String getClassname() {
return this.classname.getString();
}
/**
* This method returns an attribute.
*
* #return String - Returns the <code>methodname</code> attribute.
*/
public String getMethodname() {
return this.methodname.getString();
}
/**
* This method returns an attribute.
*
* #return boolean - Returns the <code>suppressLoggingOnly</code> attribute.
*/
public boolean isLoggingSuppressed() {
return this.suppressLoggingOnly;
}
}
Note: This has been resolved. The accessible (private) constructor was being discarded and a non-accessible (override = false) was being attempted. Bottom Line: Programmer Error