"Authentication Failure" when calling a method on Remote Object in wpf - wpf

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!
}

Related

How to get Android Context using Robolectric 4.3.1

Trying to use Robolectric 4.3.1 to do the most basic of Android actions, get the Context.
I get a non-null context by doing this (tried many other attempts but all end up getting context = null):
Context context = RuntimeEnvironment.systemContext;
I can pass the object into some methods but I can never use it.
If I try
File dir = context.getFilesDir();
I get
java.lang.RuntimeException: No data directory found for package android
What am I doing wrong?
Here is my code:
#RunWith(RobolectricTestRunner.class)
#Config(sdk = Build.VERSION_CODES.O)
public class BtScannerTests
{
private BluetoothAdapter bluetoothAdapter;
#Before
public void setUp() throws Exception
{
bluetoothAdapter = Shadow.newInstanceOf(BluetoothAdapter.class);
}
private static boolean done = false;
#Test
public void testBtScannerCycle() throws InterruptedException
{
IntermediaryCallback intermediaryCallback = new IntermediaryCallback()
{
#Override
public void onReceiveMdsIntermediary(MdsIntermediary mds, int connectionHandle)
{
}
#Override
public void onReceiveMetricIntermediaries(List<MetricIntermediary> metricList, MdsIntermediary mds, int connectionHandle)
{
}
};
StatusEventCallback statusEventCallback = new StatusEventCallback()
{
#Override
public void onStatusEvent(StatusEvent statusEvent, int connectionHandle, String btAddress)
{
System.out.println("Status event " + statusEvent.name());
if(statusEvent == StatusEvent.SCANNING_PAUSED);
{
done = true;
}
}
};
Context context = RuntimeEnvironment.systemContext;
File dir = context.getFilesDir(); // This is the code that fails; put here to test attempts
AndroidBtManager.setStatusEventCallback(statusEventCallback);
AndroidBtManager androidBtManager =
new AndroidBtManager(context, intermediaryCallback, false, false, true);
BtScanner btScanner = androidBtManager.getBtScanner();
while(!done)
{
Thread.sleep(1000);
}
}
}
Use this one.
Context context = ApplicationProvider.getApplicationContext();
instead of
Context context = RuntimeEnvironment.systemContext;

Windows Service can not open Windows Form

I am trying to create a Windows Service using TopShelf and within this service i want to launch a Windows Form.After i created the service and i debugged it calling ShowDialog the form does not show up:
Service
class SimpleServ {
private Task task;
private const string PATH = #"D:/out.txt";
private Logger logger;
private CancellationTokenSource src = new CancellationTokenSource();
public SimpleServ() {
logger = new Logger();
}
public void Start() {
logger.Log("Started");
this.task = Task.Run(async () => {
var fm = new Fm(logger);
while (true) {
fm.ShowDialog();
logger.Log("Just closed the dialog");
await Task.Delay(3000);
}
});
}
public void Stop() {
logger.Log("Stopped service");
}
}
Form
public partial class Fm : Form {
private Logger log;
public Fm(Logger log) {
this.log = log;
this.log.Log("From Form constructor");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
this.log.Log("Button clicked");
this.Close();
}
}
Main
class Program {
static void Main(string[] args) {
var exitCode = HostFactory.Run(x => {
x.Service<SimpleServ>(s => {
s.ConstructUsing(h => new SimpleServ());
s.WhenStarted(h => h.Start());
s.WhenStopped(h => h.Stop());
});
x.RunAsLocalSystem();
x.SetServiceName("SimpleService");
x.SetDisplayName("Simple Service");
x.SetDescription("Simple serv description");
});
int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
Environment.ExitCode = exitCodeValue;
}
}
I have attached myself to the service and after it reaches the line of ShowDialog nothing happens.
Update
I have also added a Logger to log all important events and so far , it seems the form opens but i can not see it:
Logger
public class Logger {
private string path;
public Logger(string logPath=Constants.PATH) {
this.path = logPath;
}
private object #lock = new object();
public void Log(string message) {
string formattedMessage = "Date:" + DateTime.Now.ToString() + "\tMessage:" + message;
File.AppendAllLines(this.path, new string[] { formattedMessage });
}
}
The output of the file is :
Date:6/12/2019 11:19:13 AM Message:Started
Date:6/12/2019 11:19:13 AM Message:From Form constructor
In a world where Session 0 Isolation -- an important security measure to prevent Shatter attacks -- is the law of the land, you should think very carefully about any design relying on service interaction.
A best practice is to restructure your solution to have:
A service that runs in the background, independently of the
user
A conventional GUI application that interacts with the service and
can be run by any user

CamelTestSupport read placeholders from yml file

I am trying to test my Camel Routes using CamelTestSupport. I have my routes defined in a class like this
public class ActiveMqConfig{
#Bean
public RoutesBuilder route() {
return new SpringRouteBuilder() {
#Override
public void configure() throws Exception {
from("activemq:{{push.queue.name}}").to("bean:PushEventHandler?method=handlePushEvent");
}
};
}
}
And my test class look like this
#RunWith(SpringRunner.class)
public class AmqTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new ActiveMqConfig().route();
}
#Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
Properties properties = new Properties();
properties.put("pim2.push.queue.name", "pushevent");
return properties;
}
protected Boolean ignoreMissingLocationWithPropertiesComponent() {
return true;
}
#Mock
private PushEventHandler pushEventHandler;
#BeforeClass
public static void setUpClass() throws Exception {
BrokerService brokerSvc = new BrokerService();
brokerSvc.setBrokerName("TestBroker");
brokerSvc.addConnector("tcp://localhost:61616");
brokerSvc.setPersistent(false);
brokerSvc.setUseJmx(false);
brokerSvc.start();
}
#Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
MockitoAnnotations.initMocks(this);
jndi.bind("pushEventHandler", pushEventHandler);
return jndi;
}
#Test
public void testConfigure() throws Exception {
template.sendBody("activemq:pushevent", "HelloWorld!");
Thread.sleep(2000);
verify(pushEventHandler, times(1)).handlePushEvent(any());
}}
This is working perfectly fine. But I have to set the placeholder {{push.queue.name}} using useOverridePropertiesWithPropertiesComponent function. But I want it to be read from my .yml file.
I am not able to do it. Can someone suggest.
Thanks
Properties are typically read from .properties files. But you can write some code that read the yaml file in the useOverridePropertiesWithPropertiesComponent method and put them into the Properties instance which is returned.
Thank Claus.
I got it working by doing this
#Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
PropertySource<?> applicationYamlPropertySource = loader.load(
"properties", new ClassPathResource("application.yml"),null);
Map source = ((MapPropertySource) applicationYamlPropertySource).getSource();
Properties properties = new Properties();
properties.putAll(source);
return properties;
} catch (IOException e) {
LOG.error("Config file cannot be found.");
}
return null;
}

Unable to display toast messages

I have download and use the code form the following URL
https://github.com/Pmovil/Toast to display toast message.
Initially I got NativeToastImpl Not implemented error. I have resolved by coping the native related code to my project. Now the System throws Runtime Exception "Toast is not supported in this platform."
Here is my code to display toast message.
public class MyApplication {
private Form current;
private static Object context;
public void init(Object context) {
MyApplication.context = context;
}
public static Object getContext() {
return context;
}
public void start() {
if (current != null) {
current.show();
return;
}
showLoginForm();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
private void showLoginForm() {
Form form = new Form("WelCome ...");
Button b = new Button(" Login ");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Log.p(" *** " + MyApplication.getContext());
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG);
}
});
form.addComponent(b);
form.show();
}}
I have used Net Beans IDE for development, OS : windows 8.1
Please let me know I am doing wrong in this code and
Is there any other way to display toast messages using codename one?.
Thanks in advance
please edit the following code and please test the toast in device . Toast is not available in emulator.
public void init(Object context) {
this.context = context;
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Toast.makeText(context, "HI", Toast.LENGTH_LONG);
}
});
You missed the show() method on Toast.
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG).show();

WCF host in Windows Form Application

hiii
I am new to WCF and I have written a code in Console application.
I have created a service like this
[ServiceContract]
public interface IHelloService
{
[OperationContract]
void SayHello(string msg);
}
and define the function
public class HelloService: IHelloService
{
public void SayHello(string msg)
{
Console.WriteLine("I rec message : " + msg);
}
}
and I am starting service from main program file
static void Main(string[] args)
{
Console.WriteLine("******* Service Console *******");
using(ServiceHost host = new ServiceHost(typeof(HelloWcfServiceLibrary.HelloService)))
{
host.AddServiceEndpoint(typeof(IHelloService), new NetTcpBinding(), "net.tcp://localhost:9000/HelloWcfService");
host.Open();
Console.Read();
}
}
and at client side the code is
static void Main(string[] args)
{
IHelloService proxy = ChannelFactory<IHelloService>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloWcfService"));
string msg;
while (true)
{
msg = Console.ReadLine();
msg = proxy.SayHello(msg);
Console.WriteLine("Server returned " + msg);
}
}
it is working properly but I want to do the same thing in Windows Form Application and show the received data i richtextbox but I dont know how to do that.
Please Someone help me
It's just the same as what you did in console application. You can start a ServiceHost in Load method, but one difference is that RichTextbox can only be access in GUI thread, so you may have to save the GUI SynchronizationContext somewhere and when you want to output something to that rich textbox, you need to call Post method or send on the SynchronizationContext, like:
public class HelloService: IHelloService {
private SynchronizationContext context;
private RichTextbox textbox;
public void SayHello(string msg)
{
context.Post((obj) => textbox.Add("I rec message : " + msg));
}
}
Note: this just shows a sample, it may not work.

Resources