“The page has expired due to inactivity” appears when using a services methods - Laravel 5.5 - laravel-5.5

According to other asked questions like this one, I did many doings to prevent this request expired message but there is no solution for my issue.
In the long run I recognized that the message appears when I call a service method inside a controller which run on form action!
Here is my codes samples with some descriptions:
My route:
Route::post('Material/{id}', 'MaterialController#updateMaterial')->name('updateMaterial');
Material Controller Constructor:
public function __construct(CustomService $srv)
{
$this->middleware('admin')->only(['updateMaterial']);
$this->srv= $srv;
}
srv is a protected attribute in MaterialController class.
updateMaterial Method:
public function updateMaterial($id,Request $request)
{
$this->validate($request, [...]);
$material = $this->srv->updateMaterial($request, $id);
if ($material)
return view('panel._materials.edit-material')
->with('material', $material)
->with('success', 1);
}
I also have a provider for CustomService with name CustomServiceProvider and here is the register method of the provider:
public function register()
{
$this->app->bind(CustomService::class,function($app){
return new CustomService();
});
}
and I registered it as a provider in config/app.php.
So when I return something before calling service updateMaterial method, it's OK. but when the method runs, the issue appears!
I don'n have any idea about!
Update:
And here is updateMaterial of CustomService:
public function updateMaterial($request, $id)
{
$material = Material::find($id);
if (!$material)
return false;
if ($request->has('unit'))
$material->unit = $request['unit'];
if ($request->has('price'))
$material->price = $request['price'];
if ($request->has('type'))
$material->type = $request['type'];
if ($request->has('is_active'))
$material->is_active = $request['is_active'];
$material->updated_at = Carbon::now();
$material->save();
return $material;
}
I also create a new project with Laravel 5.5.0 and without adding any complexity I just added a post route and call it in form action, but nothing changed!

This is just an issue for Windows users on Local Environment. I suffered a lot with this also when on Windows. Once you deploy to your production server, you won't have any issue at all.
It's important to note that this is not an issue with Laravel 5.5 version only. I first saw this issue in version 5.2.
I think a good fix for this would maybe be using something like Homestead or Vessel from Fideloper. Honestly I only suffered this problem when using Windows.

Related

Ember - Change current route from browser console

I am not at all Ember developer, but I would like to change current route from browser console. Is it possible at all to access correctly Ember, e.g. Ember.Router.prototype.transitionTo('/feed')?
Version of the website is 3.16.9
After a lot of research, I have found out possible solutions that you can use. I was trying to achieve it on Linkedin website via Chrome Extension
function runEmbedded(path) {
const namespaces = window.Ember.Namespace.NAMESPACES;
let application;
namespaces.forEach(function (namespace) {
if (namespace instanceof window.Ember.Application) {
application = namespace;
return false;
}
});
application.__container__.lookup('router:main').transitionTo(path);
}
const payload = '/some/new-path'
script.text = `(${runEmbedded.toString()})('${payload}');`;
document.documentElement.appendChild(script);
Second solution/hack:
Another possible hack to use, when the website is not listening to pushState/replaceState actions from History API is to push state 2 times and then go back. Please remember that's only a hack.
history.pushState({}, '', msg.payload);
history.pushState({}, '', msg.payload);
history.back();

unable to access controller functions in command line or console application

I am preparing a console application and making a connection to database using container of entity manager. This works fine. Code is below
protected function execute(InputInterface $input, OutputInterface $output)
{
// get Doctrine
$this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
// find all disc that are not treated by Manager in last week i.e sysdate - 6
$pendingApprovals = $this->em->getRepository('GMRestBundle:TDtlsDisc')->getPendingManagerAppoval();
// for each unapproved disc, start sending emails
$repository = $this->em->getRepository('GMRestBundle:TDtlsDisc');
$emailReminder = new SubmitDisclosureController();
foreach($pendingApprovals as $labManagerReview) {
$tDtlsDiscEntity = $repository->findByDiscId($labManagerReview['DISC_ID']);
$emailReminder->sendMailToLabManager($tDtlsDiscEntity);
}
}
Now, the issue is it is giving error when I call thsi $emailReminder->sendMailToLabManager($tDtlsDiscEntity); which will in turn makes a connection of orm and get some data from database. This sendMailToLabManager is in SubmitDisclosureController and the code is below.
public function sendMailToLabManager($tDtlsDiscEntity)
{
$repository = $this->getDoctrine()->getRepository('GMRestBundle:TXrefDiscSso');
$entityRepository = $this->getDoctrine()->getRepository('GMRestBundle:TDtlsEntity');
$discId = $tDtlsDiscEntity->getDiscId();
.......
In console application, I am no able to use any controller which access DB by making another connection to doctrine object. Same controller if I called through another action controller in web, it works well.
Error: Call to a member function has() on null
I see this above error message now.
You should create a service which provides the function instead of using the controller. After that you have to insert the EntityManager via dependency injection in to the the service.
If your command extends ContainerAwareCommand you can use $this->get() inside your command to retrieve the service you have defined before.

PhpUnit unable to access external url

On my local windows PC I am running XAMPP and it is serving a testpage on it (e.g. http://localhost/testsite/testpage.html)
Now on the same machine I have an instance of laravel 5.2 running and I have one named route in it called testroute.
I write a phpunit test cases
public function testBasicExample1() {
$this->visit('testroute')->see('Something'); //Passes
}
public function testBasicExample2() {
$this->visit('http://www.google.com')->see('Google'); //Passes
}
public function testBasicExample3() {
$this->visit('http://localhost/testsite/testpage.html')->see('Something Else');
//Fails as it is unable to reach the desired page (Received status code [404])
}
in TestCase.php
$baseUrl = 'http://localhost:8000';
and in .env APP_URL=http://localhost:8000
Is it know that localhost sites cannot be accessed in phpunit?
Update:
I figured out even http://www.google.com is not working, it is redirecting to the laravel's welcome route. (test passed as there was text 'Google' in that page as well). Basically it was trying to assess http://localhost:8000/www.google.com and that redirects to welcome page.
I am not sure how in laravel's phpunit I can access external url.
I banged my head against a wall for a long time with this. I don't believe it is possible / functional to test external sites with the Laravel click() or visit() methods. If it is, I'm not seeing it.
Though my need was to just check all my links, perhaps this hack may be helpful to you. I went back to basic php to assert the sites returned properly.
$sites = \App\Website::pluck('website');
foreach($sites as $site) {
$file_headers = #get_headers($site);
if (strpos($file_headers[0], '404 Not Found') || $file_headers[0] == null) {
$exists = false;
echo " Failed on: ".$site." ";
}
else {
$exists = true;
}
$this->assertTrue($exists);
}
It doesn't quite get you all the way to what you want (seeing something), but for me it was good enough to be able to see the link was live and successful.
Testing is slow as it is going out to x # of sites.
HTH

Microsoft Dynamics CRM - Pass Parameters from Web Service to IPlugins

We are building some plugins in Microsoft Dynamics CRM by inheriting from IPlugin. We have these configured so they fire whenever an Account is updated.
The problem is the plugins are calling our services, which causes our service to respond with an update. We are doing some pretty hacky things right now to prevent these cyclical updates from happening.
We were wondering if there was a way to pass a value to the IOrganizationService service (the web service) that a plugin can look at. Our other system could send a flag ("hey, don't bothing sending an update!") and the plugin could skip calling back.
Can we pass parameters from web service to the plugins?
Good idea could be usage of custom flag-field. For example you add bit field and call it CallFromExternalSystem. So when you make an update from your external system through IOranizationService you just fill this flag with true field and in plugin you can check condition that this field is present in fields list so you have no need to call external system endpoint again.
We decided the correct solution was to use the value found in IPluginExecutionContext.InputParameters["Target"]. In the case of an Update, this returns an Entity containing attributes for all the attributes that were updated.
We basically have a list of attribute names we cared about. We loop through names and see if any of them appear in the entity attribute list. If so, we send an update to our other system. The good news is, Dynamics CRM ignores updates where the values don't actually change, so trying to update a value to itself is no-op.
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity entity = (Entity)context.InputParameters["Target"];
string[] fields = new string[] { "name", "statecode", "address1_line1" };
bool hasUpdates = fields.Where(f => entity.Attributes.Contains(f)).Any();
if (!hasUpdates)
{
return;
}
}

Flash Builder (Mobile) - Dynamic Web Service URL

For my Flash Builder 4.6 Project I have a http service defined which looks at a url from our website.
What I'd like to be able to do though is to change the web service url on the fly within the app. i.e. using the existing url as default but having an admin/settings screen to change where the web service points (either stored in our sqlite database or in local memory).
This would be so that we could allow our customers to host their own version of the website/database but still be able to use/download the app through the app stores.
Has anyone had any experience with doing this?
EDIT: Adding some more details after the comments below.
When I created the HTTP Service through the FlashBuilder wizard it creates two web service classes a super class and a sub class which inherits from the super class. All of the code that the wizard populates goes into the super class.
I can assume that the code I need to put in would be in the sub class. But I do not know which function I'd put it in or how.
Below is a sample of the Super's constructor:
// initialize service control
_serviceControl = new mx.rpc.http.HTTPMultiService("websitehere");
var operations:Array = new Array();
var operation:mx.rpc.http.Operation;
var argsArray:Array;
operation = new mx.rpc.http.Operation(null, "loginRequest");
operation.url = "login.php";
operation.method = "GET";
argsArray = new Array("un","pw");
operation.argumentNames = argsArray;
operation.serializationFilter = serializer0;
operation.properties = new Object();
operation.properties["xPath"] = "/";
operation.contentType = "application/x-www-form-urlencoded";
operation.resultType = valueObjects.Data;
operations.push(operation);
_serviceControl.operationList = operations;
I'm not sure what property of the _serviceControl variable I would need to alter.
Also when I search for my website in my code it brings back a .fml file inside a .model directory which seems to get auto refreshed if I change the service url through the wizard. Would this not cause an issue?
I then have the challenge of accessing the user defined url. Within the app we use an sqlite database to store data but I think it would probably be better to use a 'SharedObject' which we also use to know what account they are logged into. How reliable is this? I assume I would be able to access this via the Service?
Though the awkward thing is that we were planning to have this configurable on a settings screen that would have been accessed after logging in. But to log in it would already need to know which server to point to.
if im reading your question correctly then your main ambition is to dynamically change the url for the services based on a user defined variable.
This is very easy to accomplish and even easier to accomplish if you are using parsley / spicelib.
a few points
dont change the code in the super file, this will get overwritten whenever the service gets refreshed. change everything in its generated sub-Class.
Shared Objects are very good for small quantities of data but should never be used for massive datasets i.e storing a big arraycollection.
Anyway here is how i achieve this.
In the SubClass you can change the constructor function.
Here is how i change my urls based on a config variable but you can just as easily use a SharedObject instead.
public function SubClassConstructor(){
if(CONFIG::DOMAIN_IDENT == "development" || CONFIG::DOMAIN_IDENT == "dev" || CONFIG::DOMAIN_IDENT == "d"){
_serviceControl.endpoint = "http://yoururl1";
}
else if(CONFIG::DOMAIN_IDENT == "production" || CONFIG::DOMAIN_IDENT == "prod" || CONFIG::DOMAIN_IDENT == "p"){
_serviceControl.endpoint = "http://yoururl2";
}
}
Of course this isn't exactly what your looking for but its a working solution, of course you can use Bindings to a Global ApplicationModel or direct reference to the SharedObject i guess you already know how to use the SharedObject.
Ask if you need any further help or guidance.
As cghrmauritius' solution didn't quite work for me, I am posting up the final solution that did work in my situation.
public function subConstructor()
{
super();
_serviceControl.baseURL = "http://url1";
}
Obviously for my final solution I need to implement the shareobject as well but overriding the url was my main priority.