Symfony DIC and Parent Services not working - zend-framework

I'm integrating Symfony DIC in a zend framework application, that's going fine except for parent services.
In my DIC config I have a parent service PC_Service which will be extended by all my services.
The problem is that the entity manager is not available (NULL) in the services that extend PC_Service. When I inject the entitymanager via service.stats the entitymanger is set correctly.
...
<service id="pc.service" class="PC_Service" abstract="true">
<call method="setEntityManager">
<argument type="service" id="doctrine.entitymanager" />
</call>
</service>
...
<service id="service.stats" class="Application_Service_Stats" parent="pc.service" />
...
PC_Service
abstract class PC_Service
{
protected $_em;
public function setEntityManager($entityManager)
{
$this->_em = $entityManager;
}
}
Application_Service_Stats
class Application_Service_Stats extends PC_Service
{
... $this->_em should be set here.
}
I hope someone can tell me what I'm doing wrong.

Don't know if it's a typo but it should be doctrine.orm.default_entity_manager or doctrine.orm.entity_manager (alias of the previuos):
<service id="pc.service" class="PC_Service" abstract="true">
<call method="setEntityManager">
<argument type="service" id="doctrine.orm.default_entity_manager" />
</call>
</service>

The solution is to compile the service container near the end of the ZF bootstrap. This process has a step called ResolveDefinitionTemplatesPass which patches in the calls from parent services.
This is typically done by the Symfony Kernel, but of course it isn't present in a ZF integration.
protected function _initServiceContainerCompilation()
{
// Wait for the SC to get built
$this->bootstrap('Services');
// Doctrine modifies the SC, so we need to wait for it also
$this->bootstrap('Doctrine');
// Compiling the SC allows "ResolveDefinitionTemplatesPass" to run,
// allowing services to inherit method calls from parents
$sc = $this->getResource('Services');
$sc->compile();
}

Related

Mono WCF Rest Service With Multiple Contracts "no endpoints are defined in the configuration file"

I want to host a WCF Rest Service with multiple contracts via mono each implemented in a separate partial class. I read many posts on similar issues, yet there was no solution for mono. I incorporated or at least tested all suggestions I could find and by now my code looks a lot like other solutions, yet does not work.
The application runs successfully on my local machine but throws an error once I deploy it via mono.
Service 'MyWebServiceEndpoint' implements multiple ServiceContract types, and no endpoints are defined in the configuration file.
Here is one of the endpoints with the contract. All the others are very much like this one. They all are a partial class MyWebServiceEndpoint implementing another contract.
namespace MyServer.MyEndPoints {
public partial class MyWebServiceEndpoint : INotificationEndpoint {
public string GetNotifications(int limit) {
// Do stuff
}
}
[ServiceContract]
public interface INotificationEndpoint {
[OperationContract]
[WebGet]
string GetNotifications(int limit);
}
}
My App.config looks like this. I removed the IP and port, as they are the server address.
<system.serviceModel>
<services>
<service name="MyServer.MyEndPoints.MyWebServiceEndpoint" behaviorConfiguration="WebService.EndPoint">
<host>
<baseAddresses>
<add baseAddress="http://ip:port>"/>
</baseAddresses>
</host>
<endpoint address="/message"
binding="webHttpBinding"
contract="MyServer.MyEndPoints.IMessageEndpoint"
behaviorConfiguration="WebBehavior"/>
<endpoint address="/music"
binding="webHttpBinding"
contract="MyServer.MyEndPoints.IMusicEndpoint"
behaviorConfiguration="WebBehavior"/>
<endpoint address="/notification"
binding="webHttpBinding"
contract="MyServer.MyEndPoints.INotificationEndpoint"
behaviorConfiguration="WebBehavior"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WebService.EndPoint">
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
I open the service in C# like this.
WebServiceHost = new WebServiceHost(typeof(MyWebServiceEndpoint));
WebServiceHost.Open();
The Error message I receive on mono is:
Unhandled Exception:
System.InvalidOperationException: Service 'MyWebServiceEndpoint' implements multiple ServiceContract
types, and no endpoints are defined in the configuration file. WebServiceHost can set up default
endpoints, but only if the service implements only a single ServiceContract. Either change the
service to only implement a single ServiceContract, or else define endpoints for the service
explicitly in the configuration file. When more than one contract is implemented, must add base
address endpoint manually
I hope you have some hints or someone knows how to solve the issue. Thank you already for reading up to here.
I am not familiar with Mono, Does the Mono support Webconfig file? I advise you to add the service endpoint programmatically.
class Program
{
/// <param name="args"></param>
static void Main(string[] args)
{
WebHttpBinding binding = new WebHttpBinding();
Uri uri = new Uri("http://localhost:21011");
using (WebServiceHost sh = new WebServiceHost(typeof(TestService),uri))
{
sh.AddServiceEndpoint(typeof(ITestService), binding, "service1");
sh.AddServiceEndpoint(typeof(IService), binding, "service2");
ServiceMetadataBehavior smb;
smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
{
smb = new ServiceMetadataBehavior()
{
HttpGetEnabled = true
};
sh.Description.Behaviors.Add(smb);
}
sh.Opened += delegate
{
Console.WriteLine("service is ready");
};
sh.Closed += delegate
{
Console.WriteLine("service is closed");
};
sh.Open();
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface ITestService
{
[OperationContract]
[WebGet]
string GetData(int id);
}
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet]
string Test();
}
public class TestService : ITestService,IService
{
public string GetData(int id)
{
return $"{id},";
}
public string Test()
{
return "Hello " + DateTime.Now.ToString();
}
}
Result.
According to the official documentation, we had better not use Partial class.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/multiple-contracts
Besides, we could consider launching multiple service host for every service implemented class.
Feel free to let me know if the problem still exists.

Creating a admin controller using adminhtml id

I'm trying to add a controller accessible on admin menu through url:
https://dev.m2t2.com/admin_k1tgag/admin/helloWorld/index/key/0195fab99cc865bb756a77e8fe5ceedb6f8eee97de91d569398d383cef4f0d81/
Generated by the XML code inserted below. But it keeps returning
Invalid security or form key. Please refresh the page.
Router.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="adminhtml">
<module name="Study_Admin" before="Magento_Backend"/>
</route>
</router>
</config>
In menu i inserted:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add id="Study_Admin::greetings" title="Greetings" translate="title" module="Study_Admin" parent="Magento_Backend::content" sortOrder="50" dependsOnModule="Study_Admin" resource="Study_Admin::greetings"/>
<add id="Study_Admin::greetings_helloworld" title="Hello World" translate="title" module="Study_Admin" parent="Study_Admin::greetings" sortOrder="10" dependsOnModule="Study_Admin" action="adminhtml/helloWorld" resource="Study_Admin::greetings"/>
</menu>
</config>
But when i access the controller through the menu i have no success. I started debugging and i checked that non-custom controllers extends \Magento\Backend\App\Action class to pass validations inside magento routing core flow. I did the same but i still have no success.
Below my controller class:
<?php
namespace Study\Controller\Adminhtml\HelloWorld;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action\Context;
use ‌Magento\Framework\App\ActionInterface;
class Index extends \Magento\Backend\App\Action
{
const MENU_Id = "Study_Admin::greetings_helloworld";
protected $resultPageFActory;
public function __construct(Context $context, PageFactory $resultPageFActory)
{
parent::__construct($context);
$this->resultPageFActory = $resultPageFActory;
}
public function execute()
{
$resultPage = $this->resultPageFActory->create();
$resultPage->setActiveMenu(static::MENU_Id);
$resultPage->getConfig()->getTitle()->prepend(__('Hello World'));
return $resultPage;
// TODO: Implement execute() method.
}
}
The file structure is :
Thanx in advance, and take care.
It works... was just my namespace in Controller's class that had an error
'namespace Study\Admin\Controller\Adminhtml\Helloworld;'

REST API Versioning (V1 / V2 / V3) in Magento 2.3

Have clarification on implementing versioning on custom API in Magento 2.3
Current Scenario:
We have implemented custom REST API with some functionality.
API Spec:
API: https://example.domain.com/rest/default/V1/custom/module/list
Method: GET
Expected Scenario
We need to use same functionality with minor change in version 2.
API Spec
API: https://example.domain.com/rest/default/V2/custom/module/list
Method: GET
Note:
The both API end point service method should be a same.
The current scenario should not be break by handling expected scenario. Both API should be work as we expect.
Hope the below code will help for reference
/app/code/Custom/Module/etc/webapi.xml
<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/custom/module/list" method="GET">
<service class="Custom\Module\Api\StudentInterface" method="getList" />
<resources>
<resource ref="anonymous" />
</resources>
</route>
</routes>
/app/code/Custom/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Custom\Module\Api\StudentInterface" type="Custom\Module\Service\StudentService"/>
</config>
/app/code/Custom/Module/Api/StudentInterface.php
<?php
namespace Custom\Module\Api;
interface StudentInterface
{
/**
* Get Student list
*
* #return array
*/
public function getList();
}
/app/code/Custom/Module/Service/StudentService.php
<?php
namespace Custom\Module\Service;
class StudentService
{
/**
* {#inheritdoc}
*/
public function getList()
{
//To do get Student List
}
}
Is it possible to use same Service Method and return response based on REST API Verisoning (V1 / V2 / V3) ?

Service Fabric specify fabric url

Is it possible to define which url a service uses instead of the standard fabric:/AppName/ServiceName?
I can't find if this is configurable or not on an application level.
Yes, you can change the name of the service in the ApplicationManifest.xml to something other than the name taken from the service's class name.
Short: just change the name attribute in ApplicationManifest.xml for that service to something else.
In code: If I have this service:
public interface IJustAnotherStatelessService : IService
{
Task<string> SayHelloAsync(string someValue);
}
internal sealed class JustAnotherStatelessService : StatelessService, IJustAnotherStatelessService
{
// Service implementation
}
Registered in Program.cs like this:
ServiceRuntime.RegisterServiceAsync("JustAnotherStatelessServiceType",
context => new JustAnotherStatelessService(context)).GetAwaiter().GetResult();
And in the ServiceManifest.xml for that service
<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest ...>
<ServiceTypes>
<!-- This is the name of your ServiceType.
This name must match the string used in RegisterServiceType call in Program.cs. -->
<StatelessServiceType ServiceTypeName="JustAnotherStatelessServiceType" />
</ServiceTypes>
...
In the ApplicationManifest.xml you will get the suggested name:
<ApplicationManifest ...>
<DefaultServices>
<Service Name="JustAnotherStatelessService">
<StatelessService ServiceTypeName="JustAnotherStatelessServiceType" InstanceCount="[JustAnotherStatelessService_InstanceCount]">
<SingletonPartition />
</StatelessService>
</Service>
</DefaultServices>
</ApplicationManifest>
This will give you an Uri to you service like
fabric:/app_name/JustAnotherStatelessService
Now, go ahead and change the name in the application manifest:
<ApplicationManifest ...>
<DefaultServices>
<Service Name="AwesomeService">
<StatelessService ServiceTypeName="JustAnotherStatelessServiceType" InstanceCount="[JustAnotherStatelessService_InstanceCount]">
<SingletonPartition />
</StatelessService>
</Service>
</DefaultServices>
</ApplicationManifest>
And your service now answers to
fabric:/app_name/AwesomeService
You can use this uri builder (ServiceUriBuilder.cs) class from here: https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/ReferenceApp/Common/ServiceUriBuilder.cs
For stateless service you can easily get the proxy:
var serviceUri = new ServiceUriBuilder(ServiceName);
var proxyFactory = new ServiceProxyFactory();
var svc = proxyFactory.CreateServiceProxy<IServiceName>(serviceUri.ToUri());
For stateful service you have to specify the partition.
var serviceUri = new ServiceUriBuilder(StatefulServiceName);
var proxyFactory = new ServiceProxyFactory();
//this is just a sample of partition 1 if you are using number partitioning.
var partition = new ServicePartitionKey(1);
var svc = proxyFactory.CreateServiceProxy<IStatefulServiceName>(serviceUri.ToUri(), partition);

Configuring gwt-log's remoteLogger; use log4j to put it in a separate file

I have a (Smart)GWT application, that uses Spring on the server-side, and logs its stuff there via log4j. This works (deploying on tomcat6/ubuntu 10.04 LTS).
On the client-side I use the gwt-log remote logging library, configured properly. When running debug mode, I see the gwt-logs in the Eclipse 'Development Mode' pane. When deployed however, I don't see the gwt-log logs. I have configured things as follows:
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
...
<appender name="FILE_LOG2" class="org.apache.log4j.FileAppender">
<param name="File" value="${PuzzelVandaag-instance-root}WEB-INF/logs/Sytematic.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="--- %d [%.4t] %-5p %c{1} - %m%n"/>
</layout>
</appender>
...
<!-- this one works, normal server-side code -->
<category name="com.isomorphic">
<priority value="DEBUG" />
<appender-ref ref="FILE_LOG2" />
</category>
<!-- currently I use this to configure gwt-log stuff. Is this the right way? -->
<category name="gwt-log">
<level value="DEBUG" />
<appender-ref ref="FILE_LOG2"/>
</category>
The server-side package logging works, but I have troubles with the client-side. I am fairly sure the remote logging servlet works, as I don't see any errors on this. I have it configured as follows, in web.xml:
<servlet>
<servlet-name>gwt-log-remote-logger-servlet</servlet-name>
<servlet-class>com.allen_sauer.gwt.log.server.RemoteLoggerServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gwt-log-remote-logger-servlet</servlet-name>
<url-pattern>/[modulename]/gwt-log</url-pattern>
</servlet-mapping>
When I log stuff, I do a call like Log.debug("some msg"), whilst importing com.allen_sauer.gwt.log.client.Log.
All-in-all I think I followed the correct approach. I also run hosted mode with the -Dlog4j.debug parameter, and this is what it tells me:
log4j: Retreiving an instance of org.apache.log4j.Logger.
log4j: Setting [gwt-log] additivity to [true].
log4j: Level value for gwt-log is [DEBUG].
log4j: gwt-log level set to DEBUG
log4j: Adding appender named [STDOUT] to category [gwt-log].
log4j: Adding appender named [SmartClientLog] to category [gwt-log].
log4j: Adding appender named [FILE_LOG2] to category [gwt-log].
For completion, here is the relevant part of .gwt.xml:
<inherits name="com.allen_sauer.gwt.log.gwt-log-DEBUG"/>
<set-property name="log_DivLogger" value="DISABLED"/>
<!-- In gwt-log-3.0.3 or later -->
<inherits name="com.allen_sauer.gwt.log.gwt-log-RemoteLogger"/>
Am I missing something obvious? I am a log4j newbie... Any help would be greatly appreciated!
If you take a look at the com.google.gwt.logging.server.RemoteLoggingServiceImpl code you will see that it is using java.util.logging.Logger to perform it's logging.
You are using Log4j.
There are two options for getting your logs to appear in Log4j.
Implement your own RemoteLoggingService
Use slf4j to "bridge" java.util.logging with log4j logging
Option 1 is not too hard.
I have below the class I created for this. Remember to point your web.xml to this new class.
import java.util.logging.LogRecord;
import com.google.gwt.logging.shared.RemoteLoggingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.logging.Level;
import org.springframework.stereotype.Component;
public class MyRemoteLoggingServlet extends RemoteServiceServlet implements RemoteLoggingService {
private final MyLogger logger = MyLoggerFactory.getLogger(getClass());
#Override
public String logOnServer(LogRecord record) {
Level level = record.getLevel();
String message = record.getMessage();
if (Level.INFO.equals(level)) {
logger.info(message);
} else if (Level.SEVERE.equals(level)) {
logger.error(message);
} else if (Level.WARNING.equals(level)) {
logger.warn(message);
} else if (Level.FINE.equals(level)) {
logger.debug(message);
}
return null;
}
}
Option 2
In this option you use SLF4J for your logging and configure a bridge that will redirect the java.util.logging.Logger to Log4j.
I havent implemented this method myself, but you can read about it here:
JUL to SLF4J Bridge
I took this approach, works for me.
public class UILogging extends RemoteServiceServlet implements
RemoteLoggingService {
private static final String SYMBOL_MAPS = "symbolMaps";
private static StackTraceDeobfuscator deobfuscator = null;
private static Logger logger = Logger.getLogger(UILogging.class);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
setSymbolMapsDirectory(config.getInitParameter(SYMBOL_MAPS));
}
/**
* Logs a Log Record which has been serialized using GWT RPC on the server.
*
* #return either an error message, or null if logging is successful.
*/
public final String logOnServer(LogRecord lr) {
String strongName = getPermutationStrongName();
try {
if (deobfuscator != null) {
lr = deobfuscator.deobfuscateLogRecord(lr, strongName);
}
if (lr.getLevel().equals(Level.SEVERE)) {
logger.error(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.INFO)) {
logger.info(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.WARNING)) {
logger.warn(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.FINE)) {
logger.debug(lr.getMessage(),lr.getThrown());
} else if (lr.getLevel().equals(Level.ALL)) {
logger.trace(lr.getMessage(),lr.getThrown());
}
} catch (Exception e) {
logger.error("Remote logging failed", e);
return "Remote logging failed, check stack trace for details.";
}
return null;
}
/**
* By default, this service does not do any deobfuscation. In order to do
* server side deobfuscation, you must copy the symbolMaps files to a
* directory visible to the server and set the directory using this method.
*
* #param symbolMapsDir
*/
public void setSymbolMapsDirectory(String symbolMapsDir) {
if (deobfuscator == null) {
deobfuscator = new StackTraceDeobfuscator(symbolMapsDir);
} else {
deobfuscator.setSymbolMapsDirectory(symbolMapsDir);
}
}
}