I'm trying to build a small app, for learning purposes, using Dart, MongoDB and Objectory. For that I've created a basic model:
part of myapp;
class Member extends PersistentObject {
String get username => getProperty('username');
set username(String value) => setProperty('username',value);
String get password => getProperty('password');
set password(String value) => setProperty('password',value);
// more fields here
}
void registerClasses() {
objectory.registerClass(Member, () => new Member());
}
And inside my main app file I have:
library myapp;
import "package:redstone/server.dart" as app;
import "package:objectory/objectory.dart";
import "dart:core";
part "lib/member.dart";
Objectory objectory;
void main() {
objectory = new Objectory("mongodb://localhost/myapp", registerClasses, false);
objectory.initDomainModel().then((_) {
app.setupConsoleLog();
app.start(address: "127.0.0.1", port: 8080);
});
}
And when I run it I get the follwing error:
Breaking on exception: object of type NoSuchMethodError
Unhandled exception:
The null object does not have a method 'dataMapDecorator'.
NoSuchMethodError: method not found: 'dataMapDecorator'
Receiver: null
Arguments: [Instance of '_LinkedHashMap']
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 BasePersistentObject.BasePersistentObject (package:objectory/src/persistent_object.dart:10:46)
#2 PersistentObject.PersistentObject (package:objectory/src/persistent_object.dart:1:1)
#3 Member.Member (file:///Users/lucian/Projects/dart/eviq/bin/lib/member.dart:1:1)
#4 registerClasses.<anonymous closure> (file:///Users/lucian/Projects/dart/eviq/bin/lib/member.dart:74:45)
#5 Objectory.registerClass (package:objectory/src/objectory_base.dart:118:39)
#6 registerClasses (file:///Users/lucian/Projects/dart/eviq/bin/lib/member.dart:74:26)
#7 Objectory.initDomainModel (package:objectory/src/objectory_base.dart:141:28)
#8 main (file:///Users/lucian/Projects/dart/eviq/bin/eviq.dart:13:28)
#9 _startIsolate.isolateStartHandler (dart:isolate-patch/isolate_patch.dart:216)
#10 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:124)
Any idea of what I'm doing wrong? Thanks.
You are instatiating base Objectory class. There is concrete implementatins of Objectory for server side and browser environment.
Assuming that you are trying to use Objectory on server side you should use ObjectoryDirectConnectionImpl
see https://github.com/vadimtsushko/objectory/blob/master/example/console/blog_console.dart for example
library blog_example;
import 'package:objectory/objectory_console.dart';
import '../domain_model/domain_model.dart';
const Uri = 'mongodb://127.0.0.1/objectory_blog';
main(){
objectory = new ObjectoryDirectConnectionImpl(Uri,registerClasses,true);
var authors = new Map<String,Author>();
var users = new Map<String,User>();
objectory.initDomainModel().then((_) {
Third parameter of ObjectoryDirectConnectionImpl constructor command objectory to drop collections after opening db - usefull for samples and tests, you probably should make it false
Related
I'm trying to implement the SecretManager but I'm having problems when I call the client, can someone tell me what could be happening, the only thing that is evident is that the auth_io package is launching a null check on the "credFile" variable, I've already checked the forums on github but without success.
Variable that calls the null check inside the auth_io package:
credFile = File.fromUri(
Uri.directory(Platform.environment['HOME']!)
.resolve('.config/gcloud/application_default_credentials.json'),
);
I tried consuming SecretManager in two ways:
//Using package: gcp_secret_manager
import 'package:gcp_secret_manager/gcp_secret_manager.dart';
Future<void> getSecret() async {
final secretManager = await SecretManager.defaultCredentials();
final secret = await secretManager.getSecret('projects/123456789/secrets/secret-api-teste');
debugPrint(secret);
}
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:googleapis/secretmanager/v1.dart' as sm;
Future<void> getSecret() async {
final client = await auth.clientViaApplicationDefaultCredentials(
scopes: [FirestoreApi.cloudPlatformScope],);
final secretManagerApi = sm.SecretManagerApi(client);
final secret = await secretManagerApi.projects.secrets.get("projects/123456789/secrets/secret-api-teste");
debugPrint(secret.name);
}
Error:
E/flutter (11795): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value
E/flutter (11795): #0 clientViaApplicationDefaultCredentials (package:googleapis_auth/auth_io.dart:77:49)
I am using new_vesrion ^0.3.1 package in flutter to display alert dialog for showing to update the app if new version is available on store of flutter app but I am getting below written exception:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 1
E/flutter ( 5988): #0 List.[] (dart:core-patch/growable_array.dart:264:36)
E/flutter ( 5988): #1 NewVersion._getAndroidStoreVersion (package:new_version/new_version.dart:195:26)
E/flutter ( 5988): <asynchronous suspension>
E/flutter ( 5988): #2 _SplashScreenState._checkVersion (package:cardicare/appScreens/Splash_Screen.dart:124:20)
Below I have given my code written for showing alert dialog for new updates of flutter app:
void _checkVersion() async
{
final newVersion = NewVersion
(
androidId: androidAppId,
iOSId: iOSAppId
);
final status = await newVersion.getVersionStatus();
if(status!=null)
{
if(status.canUpdate)
{
newVersion.showUpdateDialog
(
context: context,
versionStatus: status,
dialogTitle: "Update!!!",
//dismissButtonText: "Skip",
dialogText: "Please update your app from "+"${status.localVersion}"+ " to "+ "${status.storeVersion}",
allowDismissal: false,
dismissAction: ()
{
SystemNavigator.pop();
},
updateButtonText: "Let's Update"
);
}
print("app version on Device "+"${status.localVersion}");
print("app version on store "+"${status.storeVersion}");
}
}
And _checkVersion() method is called in initState() of Splash screen.
So please help me to solve this issue.
I think i find the problem, i look into the library and compare to the return from google if u send GET to [https://play.google.com/store/apps/details?id=APP_ID&hl=en]
I think google have changed their return, before the version was returning on the ds:4 script, but now it returns at the ds:5
If u change the line 183 from the new_version.dart to
(elm) => elm.text.contains('key: \'ds:5\''),
The erros is gone, i think they have to update the library
#Edit
I have download the file new_version from GitHub and paste into my project, make some changes and works fine
If your app is not released yet it must be throwing an error
Try adding a try catch and if it fails then dont show the pop up
String storeVersion = "";
try{
storeVersion = status.storeVersion;
}catch(e){}
I read every documents that i found and set up codeception to write unit test for yii2 application.
My project using mongodb as database and when i run my unit test to test save action of my model then i see that db component not found.
It's true because i'm using mongodb and don't need db for sql. anyway when i change my settings to rename mongodb database setting to db and still using mongodb connection settings i see error that means yii2 are trying to use SQL activerecord methods.
My test class:
namespace common\tests;
use common\models\Developer;
use common\tests\fixtures\DeveloperFixture;
use Faker\Factory;
class DeveloperTest extends \Codeception\Test\Unit
{
/**
* #var \common\tests\UnitTester
*/
protected $tester;
/**
* #return array
*/
public function _fixtures()
{
return [
'user' => [
'class' => DeveloperFixture::class,
'dataFile' => codecept_data_dir() . 'developer.php'
]
];
}
/**
* Test to saving user in database.
* We are using Factory object to create dynamic test cases.
*/
public function testSaving()
{
// use the factory to create a Faker\Generator instance
$faker = Factory::create();
$developer = new Developer([
'name' => $faker->name,
'description' => $faker->sentences
]);
$this->assertTrue($developer->save(), 'Developer object saved into database.');
}
protected function _before()
{
}
protected function _after()
{
}
}
My commont/config/test-local.php
<?php
return yii\helpers\ArrayHelper::merge(
require __DIR__ . '/main.php',
require __DIR__ . '/main-local.php',
require __DIR__ . '/test.php',
[
'components' => [
'mongodb' => require_once ('conf.d/test-db.php')
],
]
);
My common/config/conf.d/test-db.php
<?php
return
[
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://mongodb/mytestdb', //Using docker container
];
My fixture class:
<?php
namespace common\tests\fixtures;
use yii\mongodb\ActiveFixture;
/**
* Class Developer
* Active fixture for using Developer model.
*
* #package common\tests\fixtures
*/
class DeveloperFixture extends ActiveFixture
{
public $modelClass = \common\models\Developer::class;
}
After that i run vendor/bin/codecept -c core/common run unit models/DeveloperTest
I see below error:
---------
1) DeveloperTest: Saving
Test tests/unit/models/DeveloperTest.php:testSaving
[yii\base\InvalidConfigException] Failed to instantiate component or class "db".
#1 /app/vendor/yiisoft/yii2/di/Instance.php:139
#2 /app/vendor/yiisoft/yii2/di/Container.php:428
#3 /app/vendor/yiisoft/yii2/di/Container.php:364
#4 /app/vendor/yiisoft/yii2/di/Container.php:156
#5 /app/vendor/yiisoft/yii2/di/Instance.php:167
#6 /app/vendor/yiisoft/yii2/di/Instance.php:137
#7 /app/vendor/yiisoft/yii2/test/DbFixture.php:41
#8 /app/vendor/yiisoft/yii2/base/BaseObject.php:109
#9 yii\base\BaseObject->__construct
#10 /app/vendor/yiisoft/yii2/di/Container.php:375
#1 /app/vendor/yiisoft/yii2/di/Container.php:428
#2 /app/vendor/yiisoft/yii2/di/Container.php:364
#3 /app/vendor/yiisoft/yii2/di/Container.php:156
#4 /app/vendor/yiisoft/yii2/di/Instance.php:167
#5 /app/vendor/yiisoft/yii2/di/Instance.php:137
#6 /app/vendor/yiisoft/yii2/test/DbFixture.php:41
#7 /app/vendor/yiisoft/yii2/base/BaseObject.php:109
#8 yii\base\BaseObject->__construct
#9 /app/vendor/yiisoft/yii2/di/Container.php:375
#10 /app/vendor/yiisoft/yii2/di/Container.php:156
--
There was 1 failure:
---------
1) DeveloperTest: Saving
Test tests/unit/models/DeveloperTest.php:testSaving
Developer object saved into database.
Failed asserting that false is true.
#1 /app/core/common/tests/unit/models/DeveloperTest.php:42
And when i change mongodb in test-local.php to db i see below error log:
---------
1) DeveloperTest: Saving
Test tests/unit/models/DeveloperTest.php:testSaving
[yii\base\UnknownMethodException] Calling unknown method: yii\mongodb\Command::checkIntegrity()
#1 /app/vendor/yiisoft/yii2/base/BaseObject.php:222
#2 /app/vendor/yiisoft/yii2/test/InitDbFixture.php:96
#3 /app/vendor/yiisoft/yii2/test/InitDbFixture.php:78
#4 /app/vendor/yiisoft/yii2/test/FixtureTrait.php:117
#5 /app/vendor/symfony/event-dispatcher/EventDispatcher.php:212
#6 /app/vendor/symfony/event-dispatcher/EventDispatcher.php:44
--
There was 1 failure:
---------
1) DeveloperTest: Saving
Test tests/unit/models/DeveloperTest.php:testSaving
Developer object saved into database.
Failed asserting that false is true.
#1 /app/core/common/tests/unit/models/DeveloperTest.php:42
ERRORS!
Tests: 1, Assertions: 1, Errors: 1, Failures: 1.
Anyone can help me?
This is a bug in core of framework module for codeception. You can duplicate database connection in common/config/test-local.php:
'db' => [
'class' => yii\mongodb\Connection::class,
'dsn' => 'mongodb://localhost:27017/app_test_db',
],
'mongodb' => [
'class' => yii\mongodb\Connection::class,
'dsn' => 'mongodb://localhost:27017/app_test_db',
],
I am sending emails from my ZF2 application. I want to create it as a service so that I can use it from any module and any controller.
I have the code to send the emails, need guidance to create service.
protected function sendEMail($msgSubj,$msgText, $fromEmail, $toEmail) {
$mail = new Mail\Message();
$mail->setFrom($fromEmail, $fromEmail);
$mail->addTo($toEmail, $toEmail);
$mail->setSubject($msgSubj);
$mail->setBody($msgText);
$transport = new Mail\Transport\Sendmail();
$transport->send($mail);
return true;
}
I am currently having this function defined in one of the controllers to send the email. However, my application is evolving and I need to send application from multiple modules and multiple controllers within modules.
I understand that this will be easier if I define sending email as a service and call it as required. I have read the documentation and it is considerably heavy. I am looking for examples where someone has done something similar.
Thanks in advance for your time.
2nd Edit on 2014-05-11
I have done the following
1> created a new service class SendEmail with the following code
namespace Application\Service;
class SendEmail {
public function __construct()
{
}
protected function sendEMail($msgSubj,$msgText, $fromEmail, $toEmail) {
$mail = new \Zend\Mail\Message();
$mail->setFrom($fromEmail, $fromEmail);
$mail->addTo($toEmail, $toEmail);
$mail->setSubject($msgSubj);
$mail->setBody($msgText);
$transport = new \Zend\Mail\Transport\Sendmail();
$transport->send($mail);
return true;
}
}
2> defined an entry in module.config.php for the Application Module
under "service_manager" -> "factories"
'SendEmail' => 'Application\Service\SendEmail',
3> defined the function in IndexController
public function getSendEmail( ) {
if ( !$this->sendEmail ) {
$this->sendEmail = $this->getServiceLocator( )->get( 'SendEmail' );
}
return $this->sendEmail;
}
4> at the place where I want to send the email I have the following code
$sendEmail = $this->getSendEmail( );
$sendEmail->sendEMail("subject of email","email body message", "from#email.com", "to#email.com");
5> I added Application\Service\SendEmail to the list of invokables
I am getting the following error
Zend\ServiceManager\Exception\ServiceNotCreatedException
File:
/var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1036
Message:
While attempting to create sendemail(alias: SendEmail) an invalid factory was registered for this instance type.
Stack trace:
#0 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php(612): Zend\ServiceManager\ServiceManager->createFromFactory('sendemail', 'SendEmail')
#1 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php(572): Zend\ServiceManager\ServiceManager->doCreate('SendEmail', 'sendemail')
#2 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php(504): Zend\ServiceManager\ServiceManager->create(Array)
#3 /var/www/zf2/dwam/module/UserAdmin/src/UserAdmin/Controller/IndexController.php(123): Zend\ServiceManager\ServiceManager->get('SendEmail')
#4 /var/www/zf2/dwam/module/UserAdmin/src/UserAdmin/Controller/IndexController.php(77): UserAdmin\Controller\IndexController->getSendEmail()
#5 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php(83): UserAdmin\Controller\IndexController->userLoginAction()
#6 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#7 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#8 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#9 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php(117): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#10 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php(114): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#11 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#12 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#13 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#14 /var/www/zf2/dwam/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(316): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#15 /var/www/zf2/dwam/public/index.php(17): Zend\Mvc\Application->run()
#16 {main}
Basically the service has not been created; what am I missing; What more needs to be done.
Edit on 2014-05-12 Found the solution; not sure if this is the best way though!!!
I would request the group of AlexP, nikoshr, EdChum, Eight-Bit Guru, Tad Donaghe to remove the hold so that I can publish the solution.
I have found the solution and I am posting the code that work well for me; Do comment on any other improvements that can be made.
1> created a new service class SendEmail with the following code
namespace Application\Service;
class SendEmail {
public function sendEMail($msgSubj,$msgText, $fromEmail, $toEmail) {
$mail = new \Zend\Mail\Message();
$mail->setFrom($fromEmail, $fromEmail);
$mail->addTo($toEmail, $toEmail);
$mail->setSubject($msgSubj);
$mail->setBody($msgText);
$transport = new \Zend\Mail\Transport\Sendmail();
$transport->send($mail);
return true;
}
}
2> defined in module.php for the Application Module create the function getServiceConfig()
'factories' => array (
'SendEmail' => function ( $sm ) {
return new \Application\Service\SendEmail( );
},
),
3> defined the function in IndexController
public function getSendEmail( ) {
if ( !$this->sendEmail ) {
$this->sendEmail = $this->getServiceLocator( )->get( 'SendEmail' );
}
return $this->sendEmail;
}
4> at the place where I want to send the email I have the following code
$sendEmail = $this->getSendEmail( );
$sendEmail->sendEMail("subject of email","email body message", "from#email.com", "to#email.com");
I am having trouble with zend framework and connection with database, I'm trying to create a login, the table is created, and the code apparently is fine, but gives me this:
An error occurred
Application error
Exception information:
Message: SQLSTATE[HY000] [1045] Access denied for user 'onetag51_teste'#'localhost' (using password: YES)
Stack trace:
#0 C:\xampp\Zend\library\Zend\Db\Adapter\Pdo\Mysql.php(109): Zend_Db_Adapter_Pdo_Abstract->_connect()
#1 C:\xampp\Zend\library\Zend\Db\Adapter\Abstract.php(860): Zend_Db_Adapter_Pdo_Mysql->_connect()
#2 C:\xampp\Zend\library\Zend\Db\Adapter\Abstract.php(930): Zend_Db_Adapter_Abstract->quote('pass1', NULL)
#3 C:\xampp\Zend\library\Zend\Auth\Adapter\DbTable.php(449): Zend_Db_Adapter_Abstract->quoteInto('`password` = ?', 'pass1')
#4 C:\xampp\Zend\library\Zend\Auth\Adapter\DbTable.php(368): Zend_Auth_Adapter_DbTable->_authenticateCreateSelect()
#5 C:\xampp\Zend\library\Zend\Auth.php(117): Zend_Auth_Adapter_DbTable->authenticate()
#6 C:\xampp\htdocs\Eulen\application\controllers\AuthenticationController.php(27): Zend_Auth->authenticate(Object(Zend_Auth_Adapter_DbTable))
#7 C:\xampp\Zend\library\Zend\Controller\Action.php(516): AuthenticationController->logininAction()
#8 C:\xampp\Zend\library\Zend\Controller\Dispatcher\Standard.php(308): Zend_Controller_Action->dispatch('logininAction')
#9 C:\xampp\Zend\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#10 C:\xampp\Zend\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#11 C:\xampp\Zend\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#12 C:\xampp\htdocs\Eulen\public\index.php(26): Zend_Application->run()
#13 {main}
Request Parameters:
array (
'controller' => 'authentication',
'action' => 'loginin',
'module' => 'default',
)
I was searching for a solution, and some of the possible errors were, spelling errors(I didn't find any), can't connect to phpmyadmin using my pass and user(if I go to the phpmyadmim site, I can enter using the username and password).
I have try several solution but I cant figure it out.
Am I missing something.
file config.ini:
resources.db.params.charset = "utf8"
resources.db.adapter = "pdo_mysql"
resources.db.params.host = localhost
resources.db.params.username = "onetag51_teste"
resources.db.params.password = "*******"
resources.db.params.dbname = "onetag51_eulenhugo"
Its better to put here the authenticationcontroller, maybe the problem is there..
<?php
class AuthenticationController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function logininAction()
{
// action body
$authAdapter =$this->getAuthAdapter();
$username='hugo';
$password='pass1';
$authAdapter->setIdentity($username)
->setCredential($password);
$auth =Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if($result->isValid())
{
echo 'valid';
}
else
{
echo 'invalid';
}
}
public function logoutAction()
{
// action body
}
private function getAuthAdapter()
{
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password');
return $authAdapter;
}
}
ive been talking to a friend of mine, and he told me that i need to set the permission for acesse the phpmyadmim through zend...
How can i do that?
You don't need to use quotations around your adpater, username, password and dbname in your config file. I don't in mine, hope this helps.
I found a bit more reading that might be helpful access denied for user # 'localhost' to database '' because it mentions
You need grant privileges to the user if you want external acess to database(ie. web pages).
in the answer.
There is also this link about adding the users to the database in mysql.
Hope this helps
So the problem was related with the priveleges, thanks for ARJMP, ive tryed changed the priveleges but thee host didnd let me do it, so what i did was create a local database using xamp and try the login with the database that ive created in xamp, and it worked...