Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 when I run my web service client - axis2

I create a Dynamic web project with name 'testUpdate' (and of course I don't forget to change the dynamic web module version to 2.5 and in configuration I choose Axis 2 web service
I add to my Dynamic web project these two classes :
SimpleService .java and PWCBHandler.java
I right click on SimpleService.java -> New ->Other -> Web Service to create my web service
I don't forget to copy all the jar files from rampart distribution to testUpdate/ WebContent/WEB_INF/lib and all .mar modules into testUpdate/ WebContent/WEB_INF/modules
I change services.xml file so it looks like
<service name="SimpleService" >
<module ref="rampart" />
<Description>
</Description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass" locked="false">com.gismo.SimpleService</parameter>
<parameter name="InflowSecurity">
<action>
<items>UsernameToken</items>
<passwordCallbackClass>com.gismo.PWCBHandler</passwordCallbackClass>
</action>
</parameter>
</service>
I right click on testUpdate -> RUN AS _> Run on Server (and my web service is deployed successfully)
File -> New -> Other -> Web Service Client
and in Service Definition I paste the url of the wsdl file of SimpleService
( http://localhost:9091/testUpdate/services/SimpleService?wsdl)
I add testcl.java class to my web-service client. Here is the code
public class testCL {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println(args.length);
System.out
.println("Usage: $java Client endpoint_address client_repo_path");
}
ConfigurationContext ctx = ConfigurationContextFactory
.createConfigurationContextFromFileSystem(args[1], args[1]
+ "/conf/axis2.xml");
ServiceClient client = new ServiceClient(ctx, null);
Options options = new Options();
options.setAction("urn:echo");
options.setTo(new EndpointReference(args[0]));
client.setOptions(options);
OMElement response = client.sendReceive(getPayload("Hello world"));
System.out.println(response);
}
private static OMElement getPayload(String value) {
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace ns = factory.createOMNamespace("com.gismo/xsd", "ns1");
OMElement elem = factory.createOMElement("echo", ns);
OMElement childElem = factory.createOMElement("param0", null);
childElem.setText(value);
elem.addChild(childElem);
return elem;
}
}
I don't forget to change webSercice_client/WebContent/axis2-web/conf/axis2.xml and add
<module ref="rampart"/>
<parameter name="OutflowSecurity">
<action>
<items>UsernameToken</items>
<user>bob</user>
<passwordCallbackClass>com.gismo.PWCBHandler</passwordCallbackClass>
</action>
</parameter>
But when I run testCl as Java Application it gives me an exception
Usage: $java Client endpoint_address client_repo_path
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at com.gismo.testcl.main(testcl.java:24)

My psychic debugging powers tell me that you ran it without providing two command-line arguments. You can see the error message "Usage: $java Client endpoint_address client_repo_path" is present in your program output, meaning that you didn't supply two command-line arguments, so args[1] may not be valid. Your program doesn't exit after checking the number of command-line arguments, so it tries to access args[1] after complaining that the program was run incorrectly.
if (args.length != 2) {
System.out.println(args.length);
System.out
.println("Usage: $java Client endpoint_address client_repo_path");
}
ConfigurationContext ctx = ConfigurationContextFactory
.createConfigurationContextFromFileSystem(args[1], args[1]
+ "/conf/axis2.xml");

Related

Aws-java-sdk from xagent

I'm developing an application in which much of the work interacts with aws S3.
Initial situation:
Domino: Release 9.0.1FP6.
Application on xpages with aws utilities working perfectly with the typical functionalities of readBucket, downloadFile, createBucket etc.
For application needs, due to its weight, I need to separate the logic of the same and try three methods for their separation.
In another database, an agent receives a docID from the main application and executes the order of the requested operations for S3. The mechanism works perfectly, but the memory consumption is unacceptable so it is discarded.
In another new database with the same libraries and classes needed to focus with XAgent based on How to schedule an Xagent from a Domino Java agent? Agent but with the access not ssl that points Per Henrik Lausten. It works fine, but if we load s3 it gives errors.
Console Java:
Starting http://localhost/proves\s3.nsf/demo.xsp
java.lang.NullPointerException --> at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:727)
Console Domino
HTTP JVM: demo.xsp --> beforePageLoad ---> Hello Word
HTTP JVM: CLFAD0211E: Exception thrown. please consult error-log-0.xml
Error-log-0.xml
Exception occurred servicing request for: /proves/s3.nsf/demo.xsp - HTTP Code: 500
IBM_TECHNICAL_SUPPORT\ xpages_exc.log
java.lang.NoClassDefFoundError: com.amazonaws.auth.AWSCredentials
I think the problem may be in using this mechanism because it is not secure, if it is accessed from the browser to demo.xsp it will be running the entire load of aws xon the default credentials.
I test with another SSL-based xagent according to Devin Olson's blog post, Scheduled Xagents, but throw error:
Console Java:
Exception:javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.j: No trusted certificate found
Is the separation approach of the logic of the application correct?
Any suggestions as to why the third procedure for SSL is failing?
Thanks in advance
Edit: Hello, the code XAgent (Agent properties security tab=3)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.net.ssl.SSLSocketFactory;
import lotus.domino.AgentBase;
public class JavaAgent extends AgentBase {
// Change these settings below to your setup as required.
static final String hostName = "localhost";
static final String urlFilepath = "/proves/s3.nsf/demo.xsp";
static final int sslPort = 443;
public void NotesMain() {
try {
final SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
final Socket socket = factory.createSocket(JavaAgent.hostName, JavaAgent.sslPort);
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final StringBuilder sb = new StringBuilder();
sb.append("GET ");
sb.append(JavaAgent.urlFilepath);
sb.append(" HTTP/1.1\n");
final String command = sb.toString();
sb.setLength(0);
sb.append("Host: ");
sb.append(JavaAgent.hostName);
sb.append("\n\n");
final String hostinfo = sb.toString();
out.write(command);
out.write(hostinfo);
out.flush();
in.close();
out.close();
socket.close();
} catch (final Exception e) {
// YOUR_EXCEPTION_HANDLING_CODE
System.out.println("Exception:" + e);
}
}
}
Code demo.xsp
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.beforePageLoad><![CDATA[#{javascript:
print("demo.xsp --> beforePageLoad ---> Hello Word");
var a = new Array();
a[0] = "mybucket-proves";
a[1] = #UserName();
var s3 = new S3();
var vector:java.util.Vector = s3.mainReadBucket(a);
var i=0;
for ( i = 0; i < vector.size(); i++) {
print("Value:" + vector.get(i));
}
}]]></xp:this.beforePageLoad>
<xp:label value="Demo" id="label1"></xp:label>
</xp:view>
New test:
Although the two bd's reside on the same server, I have an SSL Certificate Authority in the JVM in case this is the fault, but it still gives the same error. SSLHandshakeException: com.ibm.jsse2.util.j: No trusted certificate.
Note: I have tested in the main application, where the aws libraries work properly, this agent and demo.xsp page and follow the same error.
Thank you

AbstractMethodError with jTDS JDBC Driver on Tomcat 8

I am deploying a web app (WAR) to a Tomcat 8 web container.
The WAR includes in the '/WEB-INF/lib' directory the following jTDS JDBC driver:
<dependency org="net.sourceforge.jtds" name="jtds" rev="1.3.1" />
(file is: jtds-1.3.1.jar).
This is how the resource is defined in META-INF/context.xml:
<Resource name="jdbc/jtds/sybase/somedb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="net.sourceforge.jtds.jdbc.Driver"
url="jdbc:jtds:sybase://localhost:2501/somedb"
username="someuser" password="somepassword"
/>
In my code I obtain the javax.sql.DataSource the normal way:
InitialContext cxt = new InitialContext();
if ( cxt == null ) {
throw new RuntimeException("Uh oh -- no context!");
}
DataSource ds = (DataSource) cxt.lookup( lookupName );
I further verify (by printing) that the DataSource object ds is of the expected type:
org.apache.tomcat.dbcp.dbcp2.BasicDataSource
… but when I try to get a connection out of it:
Connection conn = ds.getConnection();
… I get the following trace:
java.lang.AbstractMethodError
net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:924)
org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:359)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2316)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
What gives?
Turns out I had to add:
validationQuery="select 1"
in the Resource declaration in context.xml.
This is mentioned here (although mispelled as validateQuery).
Digging into the implementation of JtdsConnection one sees:
/* (non-Javadoc)
* #see java.sql.Connection#isValid(int)
*/
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
This is really weird, I think AbstractMethodError is supposedly thrown by the compiler only, unimplemented methods ought to throw UnsupportedOperationException. At any rate, the following code from PoolableConnection shows why the presence or not of validationQuery in context.xml can change things. Your validationQuery is passed as the value of the sql String parameter in the below method (or null if you don't define a validationQuery):
public void More ...validate(String sql, int timeout) throws SQLException {
...
if (sql == null || sql.length() == 0) {
...
if (!isValid(timeout)) {
throw new SQLException("isValid() returned false");
}
return;
}
...
}
So basically if no validationQuery is present, then the connection's own implementation of isValid is consulted which in the case of JtdsConnection weirdly throws AbstractMethodError.
The answer mentioned above by Marcus worked for me when I encountered this problem. To give a specific example of how the validationQuery setting looks in the context.xml file:
<Resource name="jdbc/myDB" auth="Container" type="javax.sql.DataSource"
driverClassName="net.sourceforge.jtds.jdbc.Driver"
url="jdbc:jtds:sqlserver://SQLSERVER01:1433/mydbname;instance=MYDBINSTANCE"
username="dbuserid" password="dbpassword"
validationQuery="select 1"
/>
The validationQuery setting goes in with each driver setting for your db connections. So each time you add another db entry to your context.xml file, you will need to include this setting with the driver settings.
The above answer works. If you are setting it up for standalone Java application, set the validation query in the datasource.
BasicDataSource ds = new BasicDataSource();
ds.setUsername(user);
ds.setPassword(getPassword());
ds.setUrl(jdbcUrl);
ds.setDriverClassName(driver);
ds.setMaxTotal(10);
ds.setValidationQuery("select 1"); //DBCP throws error without this query

Spring boot JNDI datasource lookup failure - Name comp/env/jdbc not found in context "java:"

I have setup a spring boot (v 1.1.9) application to deploy as a WAR file. And I'm trying to integrate this web application with an existing data service module (added as a maven dependency).
Environment trying to deploy: WebSphere Application Server 8.5.5.4
The issue I'm facing is an application start-up failure when try to look-up a JNDI dataSource (jdbc/fileUploadDS) as below within the dependent data service module.
#Configuration
#Profile("prod")
public class JndiDataConfig implements DataConfig {
#Bean
public DataSource dataSource() throws NamingException {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/fileUploadDS");
}
}
My Spring Boot configuration:
#Configuration
#ComponentScan(basePackages = { "au.com.aiaa.fileupload.data.*", "demo" })
#EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class })
public class SampleApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<SampleApplication> applicationClass = SampleApplication.class;
#Bean
public static Properties fileUploadJndiProperties() throws NamingException {
JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
jndiFactoryBean.setJndiName("props/FileUploadProperties");
jndiFactoryBean.setExpectedType(Properties.class);
jndiFactoryBean.setLookupOnStartup(true);
jndiFactoryBean.afterPropertiesSet();
return (Properties) jndiFactoryBean.getObject();
}
}
Note that I'm able to lookup props/FileUploadProperties successfully. But failing to do the same for a datasource.
My doubt is it is trying to load a EmbeddedWebApplicationContext which is not what I want.
The stack trace is:
Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at **org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)**
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:89)
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:51)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
..................
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 132 common frames omitted
Caused by: javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".
at com.ibm.ws.naming.ipbase.NameSpace.getParentCtxInternal(NameSpace.java:1970)
at com.ibm.ws.naming.ipbase.NameSpace.retrieveBinding(NameSpace.java:1377)
at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1220)
at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1142)
at com.ibm.ws.naming.urlbase.UrlContextImpl.lookupExt(UrlContextImpl.java:1436)
at com.ibm.ws.naming.java.javaURLContextImpl.lookupExt(javaURLContextImpl.java:477)
at com.ibm.ws.naming.java.javaURLContextRoot.lookupExt(javaURLContextRoot.java:485)
at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:370)
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
at javax.naming.InitialContext.lookup(InitialContext.java:436)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource(JndiDataConfig.java:41)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.CGLIB$dataSource$0(<generated>)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe$$FastClassBySpringCGLIB$$3c9e0518.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.dataSource(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
What am I missing here? Even when I try to explicitly define the dataSource bean method in SampleApplication.java like below it fails with the same error.
#Bean
public static DataSource dataSource() throws NamingException {
JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
jndiFactoryBean.setJndiName("java:comp/env/jdbc/fileUploadDS");
jndiFactoryBean.setExpectedType(DataSource.class);
jndiFactoryBean.setLookupOnStartup(true);
jndiFactoryBean.setResourceRef(true);
jndiFactoryBean.afterPropertiesSet();
return (DataSource) jndiFactoryBean.getObject();
}
I referred this and it says we need to set enableNaming() on servlet container? Can I do something similar for non-embedded web application context? Or is it purely a WAS 8.5 issue??
You need to have resource reference with jdbc/fileUploadDS name in your web.xml. And make sure it is bound to actual datasource name during installation or via ibm-web-bnd.xml file.
Definition in web.xml:
<resource-ref>
<description />
<res-ref-name>jdbc/fileUploadDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
If you dont want to use web.xml, then in normal Java EE app you could just add in web component (servlet, filter) the following class annotation:
#Resource(name="jdbc/fileUploadDS", type=javax.sql.DataSource.class, lookup="jdbc/fileUploadDS")
but I'm not Spring-boot expert, so don't know, if it will work or is possible there.
I am able to connect my Spring-Boot application (deployed in Websphere Application Server 9) to WAS datasource.
The following code worked for me, for connecting to DataSource:
#Bean(name = "WASDataSource")
public DataSource WASDataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("DSNAME");
}
#Bean(name = "WASDataSourceJdbcTemplate")
public JdbcTemplate jdbcTemplate_WASDS(#Qualifier("WASDataSource")
DataSource dsDB2) {
return new JdbcTemplate(dsDB2);
}
Note: The name of Datasource "DSNAME" is the name which appears on the UI of Websphere console.
You can see that via -> Select Resources > JDBC > Data Sources.
Then I created jdbc template:
#Autowired
#Qualifier("WASDataSourceJdbcTemplate")
private JdbcTemplate db2WASTemplate;`
And running query using the query method works fine :
db2WASTemplate.query()
I did not create any Web.xml or ibm-web-bnd.xml files
I just configured spring boot with my custom datasource as follows:
#Bean
#ConfigurationProperties("spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
and inside the application.properties file I defined all datasource settings as usual
spring.datasource.driver-class-name= ***
spring.datasource.url= ***
spring.datasource.username= ***
spring.datasource.password= ***
spring.datasource.jndi-name=jdbc/myDB
It works nicely with #SpringBootApplication with all other default settings
I am facing the same problem. I don't know how to define tag in spring boot since there is no web.xml file in the spring boot.
So far what I came to know that we have to define it in the application file from where we start our spring application. I think we need to use this method to set the Datasource:
#Bean(destroyMethod="")
#ConfigurationProperties(prefix="datasource.mine")
public DataSource dataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("java:jdbc/configurationFile");
}

NLog to WCF. Closing client throws SocketException on Server

I've been struggling with this problem for a whole day and do not know how to fix it. I have tried various things to resolve the issue but I am at a loss.
I have a project where I am attempting to use the LogReceiverServer from NLog to send and receive messages between 2 PCs. I followed this example here. Everything actually works fine, my WCF service starts up correctly, my client starts up correctly, even the sending of the message to log from client to server works. But, when I shut the client down, I get SocketExceptions thrown by the server for each message that was transmitted. I know this is due to the channel not being closed properly by the client. I cannot find where I must close the channel to prevent the exceptions being thrown by my server. I have read that to manually close the channel I must use
Channel.Close();
would that be correct and where would I put that?
I want to prevent these SocketExceptions. I have found this, but it does not seem to be the correct thing to do. Correct me if I am wrong, but would the solution not use the same principles?
Unless of course I am understanding this completely wrong...
Everything is done using the config files (App.Config and NLog.Config).
Here is my LogReceiverService Target from NLog.config:
<target xsi:type="LogReceiverService"
name="logreceiver"
endpointConfigurationName="LogReceiverClient"
endpointAddress="net.tcp://server:8888/NLogServices/LogReceiverServer/logreceiverserver" />
Here is my endpoint from my app.config:
<endpoint address="net.tcp://server:8888/NLogServices/LogReceiverServer/logreceiverserver"
binding="netTcpBinding"
bindingConfiguration="LogReceiverClient"
contract="NLog.LogReceiverService.ILogReceiverClient"
name="LogReceiverClient" />
Any help or advise would greatly be appreciated.
EDIT: Extended on problem description
OK, So first, here is the Service on my host pretty much as I got it from here:
/// <summary>
/// Log service server object that logs messages.
/// </summary>
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
public class LogReceiverServer : ILogReceiverServer
{
public void ProcessLogMessages(NLogEvents nevents)
{
var events = nevents.ToEventInfo("Client.");
foreach (var ev in events)
{
var logger = LogManager.GetLogger(ev.LoggerName);
logger.Log(ev);
}
}
}
I then created this class, where I inherit from LogReceiverWebServiceTarget and override protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient(); method. It is exactly the same as is found on GitHub here, except that I registered on the ProcessLogMessagesCompleted event where I close the 'client':
[Target("wcftarget")]
public class WcfTarget : LogReceiverWebServiceTarget
{
protected override WcfLogReceiverClient CreateWcfLogReceiverClient()
{
WcfLogReceiverClient client;
if (string.IsNullOrEmpty(EndpointConfigurationName))
{
// endpoint not specified - use BasicHttpBinding
Binding binding;
if (UseBinaryEncoding)
{
binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
}
else
{
binding = new BasicHttpBinding();
}
client = new WcfLogReceiverClient(binding, new EndpointAddress(EndpointAddress));
}
else
{
client = new WcfLogReceiverClient(EndpointConfigurationName, new EndpointAddress(EndpointAddress));
/*commenting this out causes multiple socket exceptions on host*/
client.ProcessLogMessagesCompleted += client_ProcessLogMessagesCompleted;
}
return client;
}
private void client_ProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs e)
{
WcfLogReceiverClient client = sender as WcfLogReceiverClient;
if (client.State == CommunicationState.Opened)
{
(sender as WcfLogReceiverClient).Close();
}
}
}
The Logger in NLog.config is:
<logger name="*" writeTo="logreceiver" minlevel="Info" />
So then if I try to log like this:
class Program
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private static void Main(string[] args)
{
logger.Info("foo");
}
}
my host gives prints this to Debug:
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.ServiceModel.CommunicationException' occurred in System.ServiceModel.dll
Will this have any impact on performance of the host over a long period of time?
The problem has been resolved: https://github.com/NLog/NLog/commit/138fd2ec5d94072a50037a42bc2b84b6910df641

S#arp Lite - NHibernate Initializer not finding named connection string

I am attempting to use S#arp Lite. I have followed the instructions here - https://github.com/codai/Sharp-Lite/blob/master/README.txt
When I first attempt to run the MappingIntegrationTests in NUnit, I receive the following errors:
MySolution.Tests.NHibernateProvider.MappingIntegrationTests.CanConfirmDatabaseMatchesMappings:
SetUp : NHibernate.HibernateException : Could not find named connection string MySolutionConnectionString
MySolution.Tests.NHibernateProvider.MappingIntegrationTests.CanConfirmDatabaseMatchesMappings:
SetUp : NHibernate.HibernateException : Could not find named connection string MySolutionConnectionString
NUnit indicates that the above errors are coming from the second line of the SetUp method in MappingIntegrationTests.
[SetUp]
public virtual void SetUp() {
_configuration = NHibernateInitializer.Initialize();
_sessionFactory = _configuration.BuildSessionFactory();
}
The Initialize method of my NHibernateInitializer class,
public static Configuration Initialize() {
Configuration configuration = new Configuration();
configuration.Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
.DataBaseIntegration(db => {
db.ConnectionStringName = "MySolutionConnectionString";
db.Dialect<MsSql2008Dialect>();
})
.AddAssembly(typeof(ActionConfirmation<>).Assembly)
.CurrentSessionContext<LazySessionContext>();
ConventionModelMapper mapper = new ConventionModelMapper();
mapper.WithConventions(configuration);
return configuration;
}
And the App.Config file from MySolution.Tests project,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MySolutionConnectionString" connectionString="data source=.\SQLEXPRESS;Initial Catalog=MySolutionDB-DEV;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</ connectionStrings>
</configuration>
I don't understand why the NUnit test runner is failing with the message Could not find named connection string MySolutionConnectionString. According to James Kovacs' blog post on Loquacious Configuration, this seems like this should work no problem -
"Setting db.ConnectionStringName causes NHibernate to read the connection string from the config section of the [App|Web].config."
MySolution.Tests is a dll but App.configs are only read for the starting .exe file which is the NUnit testrunner.