[Symfony 4][LiipImagine] Using liipImagine in a controller - dependency-injection

(before asking for help, i prefer to tell you my english sucks a lot really sorry in advance... And i'm a real beginner in php and symfony so that's why i'm here..)
My problem :
I try to use LiipImagine for a website with a photo gallery, because i need to create somes thumbnails when i upload photos, and i see in documentation that i can use LiipImagine in my controller with my upload method, so, before anything else, i try to copy paste the code in documentation, not work, try to find on internet but i always get the error "Service "liip_imagine.cache.mnagaer" not found"
I understand that i need to inject LiipImagine in my controller but i'm a bit confused, i don't know how to do it properly, and i don't know to how to properly use my filter after that..
My uploading method is :
/**
* #Route("/new", name="photo_new", methods={"GET","POST"})
*/
public function new(CategorieRepository $cat, Request $request): Response
{
$photo = new Photo();
$form = $this->createForm(PhotoType::class, $photo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
// Je récupère les informations du fichier uploadé
$photoUploade = $form->get("nom_photo")->getData();
// Je récupère le nom du fichier uploadé
$nomPhoto = pathinfo($photoUploade->getClientOriginalName(), PATHINFO_FILENAME);
// Je remplace les espaces dans le nom du fichier
$nomPhoto = str_replace(" ", "_", $nomPhoto);
// Je rajoute un string unique (pour éviter les fichiers doublons) et l'extension du fichier téléchargé
$nomPhoto .= uniqid() . "." . $photoUploade->guessExtension();
// J'enregistre le fichier uploadé sur mon serveur, dans le dossier public/images
$photoUploade->move("images", $nomPhoto);
// Pour enregistrer l'information en BDD
$photo->setnomPhoto($nomPhoto);
$entityManager->persist($photo);
$entityManager->flush();
return $this->redirectToRoute('photo_index');
}
If someone could help me to understand it i would really appreciate..

got it..
Need this class
use Liip\ImagineBundle\Service\FilterService;
Then inject it in the method and then
$minPhoto = $FilterService->getUrlOfFilteredImage("images/".$nomPhoto, 'mini');
it make my thumbnail with my "mini" filter

Related

Xamarin.Forms (iOS) Requesting tracking Authorization in release will not prompt the user but assume the user clicked denied

As of the newest iOS polices, you have the ask the user if you can track him or her. In debug, the below code will open a prompt asking the user wether he or she is ok with being tracked. If given the ok, the app continues, if denied the app ends (after the iMessage).
However, as soon as I put the app into release and deploy it to a real phone, the prompt is always skipped and instead the fail iMessage is shown and the app exits.
Why is the prompt missing on production? In debug, it works totally fine.
if (Device.RuntimePlatform == Device.iOS)
{
try
{
ATTrackingManager.RequestTrackingAuthorization((status) => {
if (status == ATTrackingManagerAuthorizationStatus.Authorized)
{
//start once at launch afterwards with timer
GetNewChatsCount();
SetButtons();
StartChatDownloadCounter();
}
else if (status == ATTrackingManagerAuthorizationStatus.Denied)
{
Device.BeginInvokeOnMainThread(async() =>
{
DependencyService.Get<IMessage>().VeryLongAlert("Leider kannst du in diesem Fall die App nicht nutzen. Wir benötigen diese Infos, um allen Kunden ein gesichertes Umfeld zu bieten. Installiere die App neu, wenn du deine Meinung änderst.");
await Task.Delay(8000);
Environment.Exit(0);
});
}
});
}
catch (Exception e)
{
}
}

Error on a query when my Connection is set using Gupta.Sql.Base.dll and some Connection related questions, SQLBase901

I made a project to test using a connection with Gupta.Sql.Base.dll (version 9.0.1.13768), we use version SQLBase901 (that's the SqlBase folder). I added that Gupta.Sql.Base.dll as a project reference, but the execution ends without exception in the line:
SQLBaseDataReader reader = command.ExecuteReader(); //Error here that closes the App with no Exception
The app simply closes with no exception being thrown. Here is the code:
private void button1_Click_1(object sender, EventArgs e)
{
string connectionString = "data source=storage; uid=sysadm;ini=c:\\sqlbase901\\sql.ini";
string queryString = "SELECT * FROM LAPOS_TRANSACCION";
int paramValue = 145;
using (SQLBaseConnection connection = new SQLBaseConnection(connectionString))
{
SQLBaseCommand command = new SQLBaseCommand(queryString, connection);
command.Parameters.Add("#cod_farmacia", paramValue);
try
{
connection.Open();
SQLBaseDataReader reader = command.ExecuteReader(); //Error here that closes the App with no Exception
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
The report shows the error raises in file ntdll.dll
-------Error
Nombre de la aplicación con errores: PruebaConexionSqlBase.vshost.exe, versión: 14.0.23107.0, marca de tiempo: 0x559b788a
Nombre del módulo con errores: ntdll.dll, versión: 10.0.18362.1049, marca de tiempo: 0x37fd3042
Código de excepción: 0xc0000374
Desplazamiento de errores: 0x000dfa1d
Identificador del proceso con errores: 0x3bb8
Hora de inicio de la aplicación con errores: 0x01d68c2c8f4b0e27
Ruta de acceso de la aplicación con errores: C:\Prueba\PruebaConexionSqlBase\PruebaConexionSqlBase\bin\Debug\PruebaConexionSqlBase.vshost.exe
Ruta de acceso del módulo con errores: C:\Windows\SYSTEM32\ntdll.dll
Identificador del informe: 478cec12-bee4-4dfe-9465-f9cc2deea3d6
Nombre completo del paquete con errores:
Identificador de aplicación relativa del paquete con errores:
EDIT: Another example with different code, same result, in this case the App closes when executing line: Adapter.Fill(ds, "EMPLOYEE");
//' Setup the SQLBase connection string
SQLBaseConnection conn = new SQLBaseConnection();
conn.ConnectionString = "data source=storage; uid=sysadm;ini=c:\\sqlbase901\\sql.ini";
//' Open a connection to SQLBase
conn.Open();
SQLBaseDataAdapter Adapter = new SQLBaseDataAdapter();
SQLBaseCommand cmd = new SQLBaseCommand();
cmd.CommandText = "SELECT * FROM OPERACION_MENSAJE";
cmd.Connection = conn;
Adapter.SelectCommand = cmd;
// Create a new DataSet
DataSet ds = new DataSet();
Adapter.Fill(ds, "OPERACION");
// Close the database connection
conn.Close();
The reason I want to test this connection method is that I had problems in specific cases with OLEDB (the current connection method I use) and also with ODBC:
ODBC: After some hours, the connector uses memory available on the PC, it's not releasing it.
OleDB: In some situations we have concurrency problems, the App having these problems is written in Delphi, it's a bit hard to reproduce the problem when it happens but in certain cases after a query a table keeps locked and then other client computers can't get an answer when sending their queries.
In your opinion, what's the best (most reliable and best performance) way to connect to a SqlBase database?
Thank you very much!!
You are asking:
what's the best (most reliable and best performance) way to connect to a SqlBase database.
but you are referring to SQLBase v9 - which is A-n-c-i-e-n-t...... SQLBase is now v12.3 64bit, and light years ahead of v9. So its difficult to answer your question. If you were running v12.nn, as you should be, ( or at the very least v11.7 ) then without doubt OLEDB is the fastest, easiest and most reliable connection method. Concurrency is not an issue. Forget ODBC - its just a bottleneck. We have 300 users on SQLBase v12 OLEDB - no issues. But v9 OLEDB is so old - and reference to 'ntdll.dll' , combined with Delphi, put this in the category of 'good luck with that one'.
My best advise is to upgrade your database to a modern, properly supported version , before wasting too much time on v9 OLEDB. Sorry I cant help more - maybe someone else has experience of v9 OLEDB.

Groovy:Invalid duplicate class definition

I'm new to Grails/Groovy. I have a Grails project to modify, after importing it in GGTS 3.1.0, I keep getting the following error :
Groovy:Invalid duplicate class definition of class UseUiresourcesPluginConfig : The sources D:\SVN\Transverse\KAIZEN-trunk\plugins\use-uiresources-plugin-1.0.4\grails-app\conf\UseUiresourcesPluginConfig.groovy
and
D:\SVN\Transverse\KAIZEN-trunk\grails-app\conf\UseUiresourcesPluginConfig.groovy are containing both a class of the name UseUiresourcesPluginConfig.
Both files are almost the same, the first contains :
resources {
// What URL patterns should be processed by the resources plugin
adhoc.patterns = [
'/images/*',
'/css/*',
'/js/*',
'/plugins/*'
]
mappers {
// Désactivation de la concaténation des fichiers en mode dev
bundle.excludes = ['**/*']
// Désactivation du cache
hashandcache.excludes = ['**/*']
// Désactivation de la minification en mode dev
yuicssminify.disable = true
googleclosurecompiler.disable = true
yuicssminify.disable = true
// On ne traite pas les fichiers JS (c'est le plugin Google Closure Compiler qui s'en charge)
yuijsminify.disable = true
}
}
I tried to refresh grails dependencies, to update/clean the project and to reimport it.
Do you have any idea ?
Best regards.
Thomas

Storing a message in flash generates encoding troubles

I have some encoding problems when using flash.message = "Message" to set an error message. When printing it out in the view later, like it was ISO8859-1 instead of UTF.
This is my code:
try {
assert xml.results.result.size() == 1
}
catch(AssertionError e) {
flash.message = "Fel, hittade mer än ett resultat. Detta ska inte hända, var god och radera en xxx för detta xxx"
println "Error, found more than one result. This should not occur, please remove one of the result for this id."
println e.getMessage()
}
It's a standard grails app and all I have done is to use generate-all for a domain controller.
try to use:
render(view: "view", ..., encoding: "UTF-8")
Be sure your file (in your IDE) is encoding in the same encoding as Grails property:
grails.views.gsp.encoding
Should be UTF-8 by default.

Error while testing a controller response. Response not being updated

I am trying to test the behaviour of a Grails controller. The controllers answers with a JSON Object. The next function fails
void testEnable() {
def controller = new UserController()
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
controller.params.enabled = "foo"
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
controller.params.enabled=true
controller.params.id=2
controller.enable()
/* Next line fails */
assertEquals('{"errors":"No se ha encontrado al usuario"}', controller.response.contentAsString)
}
I am getting the next error:
null expected:<{"errors":"No se [ha encontrado al usuario]"}> but was:<{"errors":"No se [puede completar la petición porque faltan parametros]"}>
However, If I split the test in two functions, both function passes.
void testEnableGoodParameters() {
def controller = new UserController()
controller.params.enabled=true
controller.params.id=2
controller.enable()
assertEquals('{"errors":"No se ha encontrado al usuario"}', controller.response.contentAsString)
}
void testEnableBadParameters() {
def controller = new UserController()
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
controller.params.enabled = "foo"
controller.enable()
assertEquals('{"errors":"No se puede completar la petición porque faltan parametros"}', controller.response.contentAsString)
}
So, It seems controller.response is no being changed. Does anyone knows why is this happening and how to get around it?
A MockHttpServletResponse is injected on Controller creation, not before every controller action call.
When you call controller method more than once in one test, all calls use the same injected response. From what I understand, render() method does not overwrite previously rendered response, but appends to it - so, in your example, when you call enable() for the third time, response already contains json objects rendered on previous calls.
Also, your error message doesn't look like it was thrown by the third assertion, but the first or second one.

Resources