CakePHP 4.x - bin/cake.php get deleted after running command - command

In an cakephp app, I need to periodically retrieve data from an api. I also need the admin to be able to launch the update manually.
So I created a model accessing the data; this way I can use it in a controller and in the command/cronjob.
In the controller, no problem, it's running fine.
The problem is when I run the task in the bash : the bin/cake.php file get deleted and I can't do anything (bake, run task, etc).
Here's my code (simplified version on what's failling):
// IN Table/ApisTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Http\Client;
class ApisTable extends Table{
public function getUrl(){
$http = new Client();
$response = $http->get('http://api.tvmaze.com/shows/1');
return $response->getStringBody();
}
}
// IN Entity/Api.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Api extends Entity{
}
//IN Command/TestCommand.php
namespace App\Command;
use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
class TestCommand extends Command {
public function execute(Arguments $a, ConsoleIo $io){
$this->loadModel('Apis');
$data = $this->Apis->getUrl();
$io->out($data);
}
}
The file is deleted when I run bin/cake test
Any idea ?

Solved :
After trying few thing on another computer, I solved it. I'll let the subject here, if someone else need it.
It was my antivirus who placed the file in quarantine when reaching another url.

Related

Typo3 Extension Scheduler Command Controller

here is a problem I encountered in TYPO3 Extension Development.
I've written an TYPO3-extension. It will display in browser the news in the DB. But I'd like to configure a scheduler task to recurrently update the news in the DB to be displayed.
In writing this scheduler task I've used a Command Controller.
namespace Vendor\Extension\Command;
class CheckNewsCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController
{
public function simpleCommand()
{
$newsRepository = $this->objectManager->get( \Vendor\Extension\Domain\Repository\NewsRepository::class );
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($newsRepository);
$all_news = $newsRepository->findAll();
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($all_news);
}
}
But the variable $all_news contains nothing, it equals to NULL !!! That means, the findAll() Function of the NewsRepository does NOT work at all !!!
In comparison, I've also used this NewsRepository in a normal Controller Class: Vendor\Extension\Controller\NewsController
namespace Vendor\Extension\Controller;
class NewsController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
public function listAction()
{
$newsRepository = $this->objectManager->get( \Etagen\EtSocNewsSt\Domain\Repository\NewsRepository::class );
$all_news = $newsRepository->findAll();
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($all_news);
}
And, in the NewsController, the function NewsRepository::findAll() DID really work, and returned all records in the DB.
So, who can tell me, why the Repository function will ONLY work in the class Vendor\Extension\Controller\NewsController, but NOT work in the class Vendor\Extension\Command\CheckNewsCommandController ?
The answer is EASY: You need to define the storagePid for your news records in the CommandController OR change the settings of the NewsRepository to IGNORE the storagePid.
How to set the storagePid for CommandController:
https://worksonmymachine.org/blog/commandcontroller-and-storagepid
How to set the repository to ignore storagePid:
http://typo3.sascha-ende.de/docs/development/database/how-to-ignore-the-page-id-pid-in-repository-database-query/

TYPO3 4.5: How to read constraint(s) in query

I need to use a REST service in order to get some data to a plugin. In order to do so, I have overriden the normal backend interface in typoscript with the following command :
objects.Tx_Extbase_Persistence_Storage_BackendInterface.className = Tx_extensionname_Persistence_Storage_RestBackend
This BackendInterface then returns Query Objects in my repository when I use to following:
Ex:
$query = $this->createQuery();
$query = $query->execute()->toArray();
Here, $query holds the response from the service as a TYPO3 Tx_Extbase_Persistence_QueryInterface object.
The problem is that I need to be able to do a call to the service while passing an ID parameter (appending to the endpoint with /ID). Ideally, I would do it in such a way that this repo function (called in the controller) would return what I want :
public function findById( $id ) {
$query = $this->createQuery();
$query->matching($query->equals('id', $id));
return $query->execute()->toArray();
}
The problem is that I need to be able to access the query constraint within my Tx_extensionname_Persistence_Storage_RestBackend. Normally, I would use the '$query->getConstraint()' method. However, we are using typo3 4.5 and this function is not yet defined for Tx_Extbase_Persistence_QueryInterface.
Modifying the typo3 core to add this function is not an option.
I tried to extend the Query Interface to add this functionnality in a subclass in order to then override the class in typoscript but then realized this wouldn't be portable enough. I need to be able to access the query constraint only using typo3 4.5 native functionnalities.
Well I fixed it. The only thing needed to do was :
Tx_Extbase_Persistence_QueryInterface.className = Tx_MyExtension_Persistence_RestQuery
class Tx_MyExtension_Persistence_RestQuery extends Tx_Extbase_Persistence_Query implements Tx_MyExtension_Persistence_RestQueryInterface
{
}
interface Tx_MyExtension_Persistence_RestQueryInterface extends Tx_Extbase_Persistence_QueryInterface {
public function getConstraint();
}

I have a trouble when i up code to host

This is my trouble:
Fatal error: Class 'Default_Model_Category' not found in
/home/u988704384/public_html/mutilmodules1/application/modules/default/controllers/IndexController.php
on line 89
But in localhost, it run normal.
Please help me solve it.
In file category.php:(/public_html/mutilmodules1/application/modules/default/models/)
<?php
class Default_Model_Category extends Zend_Db_Table
{
protected $_name = 'categories';
public function listinfo()
{
$data=$this->fetchall();
return $data;
}
}
In file IndexController.php: (/public_html/mutilmodules1/application/modules/default/controllers/)
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$category = new Default_Model_Category();
$this->view->entries = $category->listinfo();
}
}
The Zend Framework classes are either missing from your library folder, or not readable by the web server. First step is to see whether /home/u988704384/public_html/mutilmodules1/application/library/Zend/Application.php exists. If so, check the permissions on the library folder.
Could your current issue be as simple as a case issue? Your class is named Default_Model_Category but you seem to indicate that the file name is category.php. Try renaming the file to Category.php and see if that corrects the issue. I know I've run into this issue before when developing on my Mac, which doesn't care about case, but my LAMP server does.

Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'

Simplest example of this, I get a collection and try to output it via Web API:
// GET api/items
public IEnumerable<Item> Get()
{
return MyContext.Items.ToList();
}
And I get the error:
Object of type
'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]'
cannot be converted to type
'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'
This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:
MyContext.Configuration.ProxyCreationEnabled = false;
But that defeats the purpose of a lot of what I am trying to do. Is there a better way?
I would suggest Disable Proxy Creation only in the place where you don't need or is causing you trouble. You don't have to disable it globally you can just disable the current DB context via code...
[HttpGet]
[WithDbContextApi]
public HttpResponseMessage Get(int take = 10, int skip = 0)
{
CurrentDbContext.Configuration.ProxyCreationEnabled = false;
var lista = CurrentDbContext.PaymentTypes
.OrderByDescending(x => x.Id)
.Skip(skip)
.Take(take)
.ToList();
var count = CurrentDbContext.PaymentTypes.Count();
return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count });
}
Here I only disabled the ProxyCreation in this method, because for every request there is a new DBContext created and therefore I only disabled the ProxyCreation for this case .
Hope it helps
if you have navigation properties and you do not want make them non virtual, you should using JSON.NET and change configuration in App_Start to using JSON not XML!
after install JSON.NET From NuGet, insert this code in WebApiConfig.cs in Register method
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
If you have navigation properties make them non virtual. Mapping will still work but it prevents the creation of Dynamic Proxy entities which cannot be serialized.]
Not having lazy loading is fine in a WebApi as you don't have a persistent connection and you ran a .ToList() anyway.
I just disabled proxy classes on a per needed basis:
// GET: ALL Employee
public IEnumerable<DimEmployee> Get()
{
using (AdventureWorks_MBDEV_DW2008Entities entities = new AdventureWorks_MBDEV_DW2008Entities())
{
entities.Configuration.ProxyCreationEnabled = false;
return entities.DimEmployees.ToList();
}
}
Add the following code in Application_Start function of Global.asax.cs:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
This instruct the API to serialize every response into JSON and remove XML responses.
In my case the object being returned had a property within it with a type that did not have an argumentless/default constructor. By adding a zero-argument constructor to that type the object could be serialized successfully.
I had the same problem and my DTO was missing an parameter less constructor.
public UserVM() { }
public UserVM(User U)
{
LoginId = U.LoginId;
GroupName = U.GroupName;
}
First constructor was missing.
I got this error message and it turns out the problem was that I had accidentally set my class to use the same serialized property name for two properties:
public class ResultDto
{
//...
[JsonProperty(PropertyName="DataCheckedBy")]
public string ActualAssociations { get; set; }
[JsonProperty(PropertyName="DataCheckedBy")]
public string ExpectedAssociations { get; set; }
//...
}
If you're getting this error and you aren't sending entities directly through your API, copy the class that's failing to serialize to LINQPad and just call JsonConvert.SerializeObject() on it and it should give you a better error message than this crap. As soon as I tried this it gave me the following error message: A member with the name 'DataCheckedBy' already exists on 'UserQuery+ResultDto'. Use the JsonPropertyAttribute to specify another name.
After disable Proxy Creation, use eager loading (Include()) to load the proxy object.
In my Project EntityCollection returned from the WebApi action method.
Configuration.ProxyCreationEnabled = false not applicable. I have tried the below approach it is working fine for me.
Control Panel.
2.Turn on Windows Features on or off
Choose Internet Information Service
Check all the World Wide Web Components it would be better to check all the components in IIS.
Install the components.
Go to (IIS) type inetmgr in command prompt.
select the published code in the Virtual directory.
Convert into application
Browse it the application.
The answer by #Mahdi perfectly fixes the issue for me, however what I noticed is that if my Newtonsoft.JSON is 11.0 version then it doesn't fix the issue, but the moment I update Newtonsoft.JSON to latest 13.0 it starts working.

External Php class in Yii?

Hello I need to use evalmath.class.php within a Yii application. How can I include it from my controller?
Something like this:
public function actionFormulas() {
include('models/evalmath.class.php');
$m = new EvalMath;
...
}
But the above code does not work. How can I include an external class within a controller?
In your example, to use include/require you probably need to add some path info with dirname(__FILE__).'/../models/...' or similar, but to do it within the Yii framework, you would first create an alias (usually in your main config file) with setPathOfAlias :
Yii::setPathOfAlias('evalmath', $evalmath_path);
Then you can use Yii::import like so:
Yii::import('evalmath', true);
and proceed as you were:
$m = new EvalMath();
..etc...
class ServiceController extends Controller
{
public function actionIndex()
{
Yii::import('application.controllers.back.ConsolidateController'); // ConsolidateController is another controller in back controller folder
echo ConsolidateController::test(); // test is action in ConsolidateController