I'm having an issue with NoClassDefFoundError when running Java from the Windows Command Prompt. I put the main TestLogger.java file in C:\mywork and four other java files in C:\mywork\logging that were organized as a package.
There was no difficulty compiling these files (javac TestLogger.java), or even creating a jar file, but I failed when trying to run the compiled TestLogger, and got the "Exception in thread 'main' java.lang.NoClassDefFoundError".
I also did some searching on the web, and found that most folks who were getting this error were only trying to run a single simple HelloWorld program. So I tried my own HelloWorld.java in C:\mywork and weird enough, there was no problem compiling and running it. And none of the various solutions I found on the web such as checking the environment variable, and adding a period after -classpath parameter, could work a miracle in my case.
I'm using JDK 1.7 on Windows XP. I'm sure there's nothing wrong with the environment variables. Below are the full contents of my source files (an example from Jeff Friesen's 2nd Edition of Learn Java for Android Development, p. 175). Hopefully someone can shed some light on this. Thanks in advance!
In C:\mywork I have one single file as the main entrance.
TestLogger.java:
package logging;
import logging.Logger;
import logging.LoggerFactory;
public class TestLogger {
public static void main(String[] args) {
Logger logger = LoggerFactory.newLogger(LoggerFactory.CONSOLE);
if (logger.connect()) {
logger.log("test message #1");
logger.disconnect();
}
else
System.out.println("cannot connect to console-based logger");
logger = LoggerFactory.newLogger(LoggerFactory.FILE, "x.txt");
if (logger.connect()) {
logger.log("test message #2");
logger.disconnect();
}
else
System.out.println("cannot connect to file-based logger");
logger = LoggerFactory.newLogger(LoggerFactory.FILE);
if (logger.connect()) {
logger.log("test message #3");
logger.disconnect();
}
else
System.out.println("cannot connect to file-based logger");
}
}
In the C:\mywork\logging folder I have four files:
1) Logger.java:
package logging;
public interface Logger {
boolean connect();
boolean disconnect();
boolean log(String msg);
}
2) Console.java:
package logging;
public class Console implements Logger {
private String dstName;
Console(String dstName) {
this.dstName = dstName;
}
#Override
public boolean connect() {
return true;
}
#Override
public boolean disconnect() {
return true;
}
#Override
public boolean log(String msg) {
System.out.println(msg);
return true;
}
}
3) File.java:
package logging;
public class File implements Logger {
private String dstName;
File(String dstName) {
this.dstName = dstName;
}
#Override
public boolean connect() {
if (dstName == null)
return false;
System.out.println("opening file " + dstName);
return true;
}
#Override
public boolean disconnect() {
if (dstName == null)
return false;
System.out.println("closing file " + dstName);
return true;
}
#Override
public boolean log(String msg) {
if (dstName == null)
return false;
System.out.println("writing "+msg+" to file " + dstName);
return true;
}
}
4) LoggingFactory.java:
package logging;
public abstract class LoggerFactory {
public final static int CONSOLE = 0;
public final static int FILE = 1;
public static Logger newLogger(int dstType, String... dstName) {
switch (dstType) {
case CONSOLE:
return new Console(dstName.length == 0 ? null : dstName[0]);
case FILE:
return new File(dstName.length == 0 ? null : dstName[0]);
default:
return null;
}
}
}
Related
I am building a Spring Batch Job that has 2 steps for downloading 2 files. The file names are job parameters.
Please find below the steps configuration class (FileDownloader and FileDownloadTasklet are custom classes for the download logic):
#Autowired
private FileDownloader fileDownloader;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean
public Step downloadFirstFileStep() {
return stepBuilderFactory.get("downloadFirstFileStep")
.tasklet(firstFileDownloadTasklet(null)).build();
}
#Bean
#StepScope
public FileDownloadTasklet firstFileDownloadTasklet(
#Value("#{jobParameters['firstFile']}") String fileName) {
return new FileDownloadTasklet(fileDownloader, fileName);
}
#Bean
public Step downloadSecondFileStep() {
return stepBuilderFactory.get("downloadSecondFileStep")
.tasklet(secondFileDownloadTasklet(null)).build();
}
#Bean
#StepScope
public FileDownloadTasklet secondFileDownloadTasklet(
#Value("#{jobParameters['secondFile']}") String fileName) {
return new FileDownloadTasklet(fileDownloader, fileName);
}
I'm feeling I'm not doing the right thing by duplicating the Step beans since the only difference is the actual name of the file to be downloaded.
Can you please give me a hint on how can I do it without duplicating the beans?
Yes we can do this in better way using a partitioner. Currently you are downloading 2 files and future you might want to download more number of files.
#Bean(name = "partitionerJob")
public Job partitionerJob() {
return jobs.get("partitioningJob")
.start(partitionStep())
.build();
}
#Bean
#StepScope
public Step partitionStep() {
return steps.get("partitionStep")
.partitioner("slaveStep", partitioner())
.step(downloadFirstFileStep())
.taskExecutor(taskExecutor())
.build();
}
#Bean
public Step downloadFirstFileStep() {
return stepBuilderFactory.get("downloadFirstFileStep")
.tasklet(firstFileDownloadTasklet(null)).build();
}
#Bean
#StepScope
public FileDownloadTasklet firstFileDownloadTasklet(
#Value("#{stepExecutionContext['fileName']}") String fileName) {
return new FileDownloadTasklet(fileDownloader, fileName);
}
#Bean
public YourPartitioner partitioner() {
return new YourPartitioner();
}
public class YourPartitioner implements Partitioner {
#Value("#{jobParameters['fileNames']}") //Pass Comma separated file names as argument
protected String fileNames;
#Override
public Map<String, ExecutionContext> partition(int gridSize) {
Map<String, ExecutionContext> map = new HashMap<>(gridSize);
int i = 0, k = 1;
for (String resource : fileNames.split(",") {
ExecutionContext context = new ExecutionContext();
context.putString("fileName", resource); //This will be fetched as argument to the step job from JobExecutionContext
map.put("PARTITION_KEY " + i, context);
i++;
}
return map;
}
}
Currently I am working designing my project in Specflow. I want to implement some reporting to my project. Currently I have created one separate .cs file and kept all my report setting. But these steps are getting unreachable. Can anyone please guide me how i can design my flow and how i can integrate with the feature file?
Please find the below BaseReport.cs file and my Step definition file.
namespace Verivox.CommonLib
{
public class BaseReport
{
public static ExtentReports extent;
public static ExtentTest test;
[BeforeFeature()]
public static void BasicSetUp()
{
//string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Reports\\" + FeatureContext.Current.FeatureInfo.Title + ".html";
extent = new ExtentReports(reportPath, true);
extent.LoadConfig(projectPath + "CommonLib\\Extent-config.xml");
}
[BeforeScenario()]
public static void BeforeScenarioSetUp()
{
test = extent.StartTest("Running Scenario -->" + ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario()]
public static void AfterScnario()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
//Add capture screen shot line here
extent.EndTest(test);
}
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
// extent.Close();
}
}
}
Steps
namespace Verivox.Steps
{
[Binding]
class CalculationVerificationSteps
{
[Given(#"I have navigate to Home Page")]
public void GivenIHaveNavigateToHomePage()
{
Browser.Current.Navigate().GoToUrl(ConfigurationManager.AppSettings["seleniumBaseUrl"]);
PropertyCollection.currentPage = new HomePage();
Browser.Current.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
[Given(#"Navigate to Mobile Calculator under All Comparison Section")]
public void GivenNavigateToMobileCalculatorUnderAllComparisonSection()
{
PropertyCollection.currentPage.As<HomePage>().MainCompItemClick("Telekommunikation");
PropertyCollection.currentPage.As<HomePage>().SubCompItemClick("Mobilfunk");
PropertyCollection.currentPage.As<HomePage>().CalculatorLinkClick("Mobiles Internet");
}
[Then(#"Mobile Calculator should appear")]
public void ThenMobileCalculatorShouldAppear()
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().IsMobileInternetCalcExistance());
}
[Then(#"(.*) option and (.*) option is selected by default\.")]
public void ThenMonatsflatrateOptionAndSIMOptionIsSelectedByDefault_(string defaultTarif, string hardware)
{
try
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().VerifyMobiIntSelectedItem(defaultTarif));
string colorCode = PropertyCollection.currentPage.As<HomePage>().VerifySelectedHardWare();
Assert.AreEqual(0, string.Compare("rgba(253, 138, 2, 1)", colorCode, StringComparison.OrdinalIgnoreCase));
}
catch (Exception)
{
BaseReport.test.Log(LogStatus.Fail, "Default selections are incorrect.");
}
}
You are missing the Binding- attribute on the BaseReport class. Without that, the hooks defined there are not called.
i use JSF and want to have file download in my page . i wrote some codes but i get ClientAbortException error when i use some download manager for download my file :
public class FileUtil {
public static FacesContext getContext() {
return FacesContext.getCurrentInstance();
}
public static void sendFile(File file, boolean attachment) throws IOException {
sendFile(getContext(), file, attachment);
}
public static void sendFile(FacesContext context, File file, boolean attachment) throws IOException {
sendFile(context, new FileInputStream(file), file.getName(), file.length(), attachment);
}
public static void sendFile(FacesContext context, byte[] content, String filename, boolean attachment) throws IOException {
sendFile(context, new ByteArrayInputStream(content), filename, (long) content.length, attachment);
}
public static void sendFile(FacesContext context, InputStream content, String filename, boolean attachment) throws IOException {
sendFile(context, content, filename, -1L, attachment);
}
private static void sendFile(FacesContext context, InputStream input, String filename, long contentLength, boolean attachment) throws IOException {
ExternalContext externalContext = context.getExternalContext();
externalContext.setResponseBufferSize(10240);
externalContext.setResponseContentType(getMimeType(context, filename));
externalContext.setResponseHeader("Content-Disposition", String.format("%s;filename=\"%2$s\"; filename*=UTF-8\'\'%2$s", new Object[]{attachment ? "attachment" : "inline", encodeURL(filename)}));
if (((HttpServletRequest) externalContext.getRequest()).isSecure()) {
externalContext.setResponseHeader("Cache-Control", "public");
externalContext.setResponseHeader("Pragma", "public");
}
if (contentLength != -1L) {
externalContext.setResponseHeader("Content-Length", String.valueOf(contentLength));
}
long size = stream(input, externalContext.getResponseOutputStream());
if (contentLength == -1L) {
externalContext.setResponseHeader("Content-Length", String.valueOf(size));
}
context.responseComplete();
}
public static String getMimeType(FacesContext context, String name) {
String mimeType = context.getExternalContext().getMimeType(name);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
return mimeType;
}
public static long stream(InputStream input, OutputStream output) throws IOException {
ReadableByteChannel inputChannel = Channels.newChannel(input);
Throwable var3 = null;
try {
WritableByteChannel outputChannel = Channels.newChannel(output);
Throwable var5 = null;
try {
ByteBuffer buffer = ByteBuffer.allocateDirect(10240);
long size = 0L;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += (long) outputChannel.write(buffer);
buffer.clear();
}
long var9 = size;
return var9;
} catch (Throwable var33) {
var5 = var33;
throw var33;
} finally {
if (outputChannel != null) {
if (var5 != null) {
try {
outputChannel.close();
} catch (Throwable var32) {
var5.addSuppressed(var32);
}
} else {
outputChannel.close();
}
}
}
} catch (Throwable var35) {
var3 = var35;
throw var35;
} finally {
if (inputChannel != null) {
if (var3 != null) {
try {
inputChannel.close();
} catch (Throwable var31) {
var3.addSuppressed(var31);
}
} else {
inputChannel.close();
}
}
}
}
public static String encodeURL(String string) {
if (string == null) {
return null;
} else {
try {
return URLEncoder.encode(string, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException var2) {
throw new UnsupportedOperationException("UTF-8 is apparently not supported on this platform.", var2);
}
}
}
}
something that i can not understand is when download is done by native chorome download without usage of any download manager like IDM or eagleget , I Do not get any ClientAbortException , but when i use these download manager software for (enable their AddOns) i get these error
what happens ? i know this error happens with some connection losing ... but i did not close my page or any thing that cause this error!
and this is my bean code:
#ManagedBean(name = "bean")
#RequestScoped
public class MB implements Serializable {
public void MBdowan() throws IOException {
File file = new File("E:\\Animation\\IA\\Learning movies\\webinar1\\01_Aug_webinar_08\\Aug08_edited_webinar_animation.mov");
FileUtil.sendFile(file,true);
}
and this is my xhtml page :
</h:head>
<h:body>
<h:form>
<p:commandButton value="Download file" ajax="false" actionListener="#{bean.MBdowan}"/>
</h:form>
</h:body>
Download accelerators (and media players!) expect files which are idempotently available via GET and HEAD requests (i.e. when just typing URL in browser's address bar) and preferably also support HTTP Range requests (so multiple HTTP connections could be opened to download parts simultaneously). The JSF backing bean method is only invoked on a POST request (i.e. when submitting a HTML form with method="post"). The ClientAbortException happens because the download accelerator didn't got the response it expected while sniffing for HEAD and Range support and aborted it.
If those files are static and thus not dynamic, then your best bet is to create a separate servlet which supports HEAD and preferably also HTTP Range requests.
Given that you clearly ripped off the source code from OmniFaces Faces#sendFile(), I'd suggest to rip off the source code of another OmniFaces artifact, the FileServlet. You can find snapshot showcase and source code link here: OmniFaces (2.2) FileServlet.
Here's how you could use it:
#WebServlet("/webinar_animation.mov")
public class YourFileServlet extends FileServlet {
#Override
protected File getFile(HttpServletRequest request) throws IllegalArgumentException {
return new File("E:\\Animation\\IA\\Learning movies\\webinar1\\01_Aug_webinar_08\\Aug08_edited_webinar_animation.mov");
}
}
Download file
See also:
How to stream audio/video files such as MP3, MP4, AVI, etc using a Servlet
In Python I can consume a web service so easily:
from suds.client import Client
client = Client('http://www.example.org/MyService/wsdl/myservice.wsdl') #create client
result = client.service.myWSMethod("Bubi", 15) #invoke method
print result #print the result returned by the WS method
I'd like to reach such a simple usage with Java.
With Axis or CXF you have to create a web service client, i.e. a package which reproduces all web service methods so that we can invoke them as if they where normal methods. Let's call it proxy classes; usually they are generated by wsdl2java tool.
Useful and user-friendly. But any time I add/modify a web service method and I want to use it in a client program I need to regenerate proxy classes.
So I found CXF DynamicClientFactory, this technique avoids the use of proxy classes:
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
//...
//create client
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("http://www.example.org/MyService/wsdl/myservice.wsdl");
//invoke method
Object[] res = client.invoke("myWSMethod", "Bubi");
//print the result
System.out.println("Response:\n" + res[0]);
But unfortunately it creates and compiles proxy classes runtime, hence requires JDK on the production machine. I have to avoid this, or at least I can't rely on it.
My question:
Is there another way to dinamically invoke any method of a web service in Java, without having a JDK at runtime and without generating "static" proxy classes? Maybe with a different library? Thanks!
I know this is a really old question but if you are still interested you could use soap-ws github project: https://github.com/reficio/soap-ws
Here you have a sample usage really simple:
Wsdl wsdl = Wsdl.parse("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL");
SoapBuilder builder = wsdl.binding()
.localPart("CurrencyConvertorSoap")
.find();
SoapOperation operation = builder.operation()
.soapAction("http://www.webserviceX.NET/ConversionRate")
.find();
Request request = builder.buildInputMessage(operation)
SoapClient client = SoapClient.builder()
.endpointUrl("http://www.webservicex.net/CurrencyConvertor.asmx")
.build();
String response = client.post(request);
As you can see it is really simple.
With CXF 3.x this could be possible with StaxDataBinding. Follow below steps to get the basics. Of course, this could be enhanced to your needs.
Create StaxDataBinding something like below. Note below code can be enhanced to your sophistication.
class StaxDataBinding extends AbstractInterceptorProvidingDataBinding {
private XMLStreamDataReader xsrReader;
private XMLStreamDataWriter xswWriter;
public StaxDataBinding() {
super();
this.xsrReader = new XMLStreamDataReader();
this.xswWriter = new XMLStreamDataWriter();
inInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inFaultInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
inFaultInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
}
static class RemoveStaxInEndingInterceptor
extends AbstractPhaseInterceptor<Message> {
static final RemoveStaxInEndingInterceptor INSTANCE = new RemoveStaxInEndingInterceptor();
public RemoveStaxInEndingInterceptor() {
super(Phase.PRE_INVOKE);
addBefore(StaxInEndingInterceptor.class.getName());
}
public void handleMessage(Message message) throws Fault {
message.getInterceptorChain().remove(StaxInEndingInterceptor.INSTANCE);
}
}
public void initialize(Service service) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
SchemaCollection schemaCollection = serviceInfo.getXmlSchemaCollection();
if (schemaCollection.getXmlSchemas().length > 1) {
// Schemas are already populated.
continue;
}
new ServiceModelVisitor(serviceInfo) {
public void begin(MessagePartInfo part) {
if (part.getTypeQName() != null
|| part.getElementQName() != null) {
return;
}
part.setTypeQName(Constants.XSD_ANYTYPE);
}
}.walk();
}
}
#SuppressWarnings("unchecked")
public <T> DataReader<T> createReader(Class<T> cls) {
if (cls == XMLStreamReader.class) {
return (DataReader<T>) xsrReader;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedReaderFormats() {
return new Class[] { XMLStreamReader.class };
}
#SuppressWarnings("unchecked")
public <T> DataWriter<T> createWriter(Class<T> cls) {
if (cls == XMLStreamWriter.class) {
return (DataWriter<T>) xswWriter;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedWriterFormats() {
return new Class[] { XMLStreamWriter.class, Node.class };
}
public static class XMLStreamDataReader implements DataReader<XMLStreamReader> {
public Object read(MessagePartInfo part, XMLStreamReader input) {
return read(null, input, part.getTypeClass());
}
public Object read(QName name, XMLStreamReader input, Class<?> type) {
return input;
}
public Object read(XMLStreamReader reader) {
return reader;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String prop, Object value) {
}
}
public static class XMLStreamDataWriter implements DataWriter<XMLStreamWriter> {
private static final Logger LOG = LogUtils
.getL7dLogger(XMLStreamDataWriter.class);
public void write(Object obj, MessagePartInfo part, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
// WRITE YOUR LOGIC HOW you WANT TO HANDLE THE INPUT DATA
//BELOW CODE JUST CALLS toString() METHOD
if (part.isElement()) {
QName element = part.getElementQName();
writer.writeStartElement(element.getNamespaceURI(),
element.getLocalPart());
if (obj != null) {
writer.writeCharacters(obj.toString());
}
writer.writeEndElement();
}
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
public void write(Object obj, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
throw new UnsupportedOperationException("Data types of "
+ obj.getClass() + " are not supported.");
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
private boolean doWrite(Object obj, XMLStreamWriter writer)
throws XMLStreamException {
if (obj instanceof XMLStreamReader) {
XMLStreamReader xmlStreamReader = (XMLStreamReader) obj;
StaxUtils.copy(xmlStreamReader, writer);
xmlStreamReader.close();
return true;
}
else if (obj instanceof XMLStreamWriterCallback) {
((XMLStreamWriterCallback) obj).write(writer);
return true;
}
return false;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String key, Object value) {
}
}
}
Prepare your input to match the expected input, something like below
private Object[] prepareInput(BindingOperationInfo operInfo, String[] paramNames,
String[] paramValues) {
List<Object> inputs = new ArrayList<Object>();
List<MessagePartInfo> parts = operInfo.getInput().getMessageParts();
if (parts != null && parts.size() > 0) {
for (MessagePartInfo partInfo : parts) {
QName element = partInfo.getElementQName();
String localPart = element.getLocalPart();
// whatever your input data you need to match data value for given element
// below code assumes names are paramNames variable and value in paramValues
for (int i = 0; i < paramNames.length; i++) {
if (paramNames[i].equals(localPart)) {
inputs.add(findParamValue(paramNames, paramValues, localPart));
}
}
}
}
return inputs.toArray();
}
Now set the proper data binding and pass the data
Bus bus = CXFBusFactory.getThreadDefaultBus();
WSDLServiceFactory sf = new WSDLServiceFactory(bus, wsdl);
sf.setAllowElementRefs(false);
Service svc = sf.create();
Client client = new ClientImpl(bus, svc, null,
SimpleEndpointImplFactory.getSingleton());
StaxDataBinding databinding = new StaxDataBinding();
svc.setDataBinding(databinding);
bus.getFeatures().add(new StaxDataBindingFeature());
BindingOperationInfo operInfo = ...//find the operation you need (see below)
Object[] inputs = prepareInput(operInfo, paramNames, paramValues);
client.invoke("operationname", inputs);
If needed you can match operation name something like below
private BindingOperationInfo findBindingOperation(Service service,
String operationName) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
Collection<BindingInfo> bindingInfos = serviceInfo.getBindings();
for (BindingInfo bindingInfo : bindingInfos) {
Collection<BindingOperationInfo> operInfos = bindingInfo.getOperations();
for (BindingOperationInfo operInfo : operInfos) {
if (operInfo.getName().getLocalPart().equals(operationName)) {
if (operInfo.isUnwrappedCapable()) {
return operInfo.getUnwrappedOperation();
}
return operInfo;
}
}
}
}
return null;
}
I am developing an application which uses WindowsFormsApplicationBase to enforce Single Instance. I get the following error when calling a method on a Remote object. It works fine if I don't use Single Instance approach.
System.Runtime.Remoting.RemotingException: Authentication failure ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.Runtime.Remoting.Channels.Tcp.TcpClientTransportSink.CreateAuthenticatedStream(Stream netStream, String machinePortAndSid)
Here is my Code:
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager sim = new SingleInstanceManager();
sim.Run(args);
}
}
public class SingleInstanceManager : WindowsFormsApplicationBase
{
private App app;
public SingleInstanceManager()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
app = new App();
app.InitializeComponent();
app.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
app.Activate();
}
}
This is how I am invoking the Remoting object:
public Hashtable GetData(string[] arg1, string[] arg2)
{
IDataProvider dataProvider = (IDataProvider )Activator.GetObject(typeof(IDataProvider ), "tcp://.....");
Hashtable data = dataProvider.GetData(arg1, arg2);
return data;
}
Thanks in advance.
I found the solution myself.
I used the following to implement single instance(http://www.ai.uga.edu/mc/SingleInstance.html).
[STAThread]
static void Main() // args are OK here, of course
{
bool ok;
m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was there
GC.KeepAlive(m); // important!
}