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.
Related
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
I have a problem with the code scanner, I use this lib https://github.com/codenameone/cn1-codescan in my application to scan the barcode. I work on an android application and I try to scan code_128 code format.
public class ScanQr extends Form {
final Container cnt = this;
public ScanQr(Form parent){
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
final RadioButton qr = new RadioButton("QR Code");
final RadioButton bar = new RadioButton("Bar Code");
bg.add(qr);
bg.add(bar);
this.addComponent(new Label("Code Type"));
this.addComponent(qr);
this.addComponent(bar);
Button scanBtn = new Button("Scan Code");
scanBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(qr.isSelected()){
CodeScanner.getInstance().scanQRCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
//barCode.setText("Bar: " + contents);
cnt.addComponent(new Label(contents));
cnt.revalidate();
}
public void scanCanceled() {
cnt.addComponent(new Label("cancelled"));
}
public void scanError(int errorCode, String message) {
cnt.addComponent(new Label("err " + message));
}
});
}else{
CodeScanner.getInstance().scanBarCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
//barCode.setText("Bar: " + contents);
cnt.addComponent(new Label(contents));
cnt.revalidate();
}
public void scanCanceled() {
cnt.addComponent(new Label("cancelled"));
}
public void scanError(int errorCode, String message) {
cnt.addComponent(new Label("err " + message));
}
});
}
}
});
if (CodeScanner.isSupported()) {
this.addComponent(scanBtn);
} else {
this.addComponent(new SpanLabel("Sorry. Codescanner not supported on this platform"));
}
}
}
First it installs Barcode Scanner+ Simple if it's not installed then when this app is used with my application, it takes a lot of time to find and display the information scanned on the barcode or it doesn't find anything but when I just use Barcode Scanner+ Simple alone, it works very well, I don't have any problem with it.
I don't understand where's the problem since I use the same codescanner application but in 2 differents contexts, when it's launched alone and when it's launched with my application.
You need to try narrowing the types that are scanned to get a better result e.g. do this some time before invoking the scan:
Display.getInstance().setProperty("android.scanTypes", "CODE_128");
I'm trying to use Netflix Hystrix open source API in an existing project to handle fault tolerance and Circuit Breaker implementation. I have referred some websites, but I couldn't get complete information about the implementation.
How can i invoke the below Hystrix program from my service class and what object it returns i'm unable to understand.
Below is the sample program about Hystrix.
Can anybody please help me to do this.
public class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
#Override
protected String run() {
return "Hello " + name + "!";
}
public static class UnitTest {
#Test
public void testSynchronous() {
assertEquals("Hello World!", new CommandHelloWorld("World").execute());
assertEquals("Hello Bob!", new CommandHelloWorld("Bob").execute());
}
#Test
public void testAsynchronous1() throws Exception {
assertEquals("Hello World!", new CommandHelloWorld("World").queue().get());
assertEquals("Hello Bob!", new CommandHelloWorld("Bob").queue().get());
}
#Test
public void testAsynchronous2() throws Exception {
Future<String> fWorld = new CommandHelloWorld("World").queue();
Future<String> fBob = new CommandHelloWorld("Bob").queue();
assertEquals("Hello World!", fWorld.get());
assertEquals("Hello Bob!", fBob.get());
}
}
}
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();
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!
}