im having a problem with catching an exception in proxy
private static async Task Check()
{
foreach (var cookieList in CookieList)
{
var user = JsonReader.readJSON("dataproxy.json", "proxyDetails", "proxyuser");
var pass = JsonReader.readJSON("dataproxy.json", "proxyDetails", "proxypass");
var proxyIp = JsonReader.readJSON("dataproxy.json", "proxyDetails", "proxyip");
var proxyPort = JsonReader.readJSON("dataproxy.json", "proxyDetails", "proxyport");
var container = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = container;
var client = new HttpClient(handler);
WebProxy proxy = new WebProxy(proxyIp,Convert.ToInt32(proxyPort));
if(user != null)
{
proxy.Credentials = new NetworkCredential(user, pass);
}
client.BaseAddress = BaseAddress; try
{
handler.Proxy = proxy;
}
catch
{
LogSystem.SendMessage("Proxy Error!", Log.Type.Message);
}
whenever a proxy is not working im getting this error:
any idea how to catch this error and let it retry if not then skip ?
The designers of .Net have considered these issues and provided us with an event called UnhandledExceptionEventHandler, through which we can intercept uncaught exceptions and process them.
The event parameter UnhandledExceptionEventArgs e of this event has two attributes, one is ExceptionObject, and this attribute returns the object instance that intercepted the exception. Another property is IsTerminating, which tells us whether this exception will cause the application to terminate.
Let's take a look at how Asp.net applications intercept uncaught exceptions.
First step:Create a class that implements the IHttpModule interface
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace WebMonitor
{
/// <summary>
/// Summary description for UnhandledExceptionModule
/// </summary>
public class UnhandledExceptionModule : IHttpModule
{
static object _initLock = new object();
static bool _initialized = false;
public UnhandledExceptionModule()
{
//
// TODO: Add constructor logic here
//
}
void OnUnhandledException(object o, UnhandledExceptionEventArgs e)
{
// Do some thing you wish to do when the Unhandled Exception raised.
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(#" c:/testme.log ",
System.IO.FileMode.Append, System.IO.FileAccess.Write))
{
using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs, System.
Text.Encoding.UTF8))
{
w.WriteLine(e.ExceptionObject);
}
}
}
catch
{
}
}
IHttpModule Members
}
}
Step two:Modify web.config
In the system.web section add
< httpModules >
< add name ="UnhandledExceptionModule" type="WebMonitor.UnhandledExceptionModule" />
</ httpModules >
After completing these two steps, your ASP.NET application can intercept uncaught exceptions.
Here is the test code:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TestMe(object state)
{
byte[] buf = new byte[2];
buf[2] = 0;
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TestMe),
null);
}
}
After pressing Button1, w3wp.exe is terminated, and the abnormal information is recorded in testme.log.
Related
I am attempting to design a windows service that contains a web server to do basic get request handling. Requests from the localhost work just find but I am unable to process requests from other machines. On python, setting the IP address to 0.0.0.0 allows the server to process requests from any IP on the network. I have found examples that use http://*:port/ or http://+:port/ to obtain this functionality in C# but these have not worked for me.
I am currently starting a HttpListener (WebServer.cs) when the windows service (UsherService.cs) receives its start command. If there is a better way to do this, I'd appreciate that answer as well.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace UsherService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new UsherService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
UsherService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace UsherService
{
public partial class UsherService : ServiceBase
{
WebServer ws;
public UsherService()
{
InitializeComponent();
}
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
}
protected override void OnStart(string[] args)
{
try
{
ws = new WebServer(SendResponse, "http://*:5000/");
ws.Run();
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", "Started Successfully");
}
catch(Exception e)
{
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", e.Message);
}
}
protected override void OnStop()
{
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", "Stopped Successfully");
}
}
}
WebServer.cs
using System;
using System.Net;
using System.Text;
using System.Threading;
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
{
_listener.Prefixes.Add(s);
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText2.txt", s);
}
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
The firewall was blocking the localhost from communicating to other devices on the network. I had to allow for communication over that port
I'm currently building an application for Windows Phone 8.1 using C#,
The aim of the app is to assess audio signals from the device's microphone, initially for frequency,
I was hoping to use the Accord library to help with this but have run into these errors:
XamlCompiler error WMC1006: Cannot resolve Assembly or Windows
Metadata file 'System.Windows.Forms.dll'
\Program Files
(x86)\MSBuild\Microsoft\WindowsXaml\v12.0\8.1\Microsoft.Windows.UI.Xaml.Common.targets(327,9):
Xaml Internal Error error WMC9999: Type universe cannot resolve
assembly: System.Windows.Forms, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089.
I'm fairly certain that this is arising due to the references included in the project but I'm not to sure,
Here is my current code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Accord.Audio;
using Accord.Controls;
using Accord.DirectSound;
using Accord.Imaging;
using Accord.MachineLearning;
using Accord.Math;
using Accord.Statistics;
using Accord;
using AForge;
using AForge.Controls;
using AForge.Imaging;
using AForge.Math;
using AForge.Video;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using System.Diagnostics;
using Windows.Media;
using Windows.Media.MediaProperties;
using Accord.Audio.Formats;
using Accord.Audio.Windows;
namespace Test2
{
public sealed partial class MainPage : Page
{
private MediaCapture _mediaCaptureManager;
private StorageFile _recordStorageFile;
private bool _recording;
private bool _userRequestedRaw;
private bool _rawAudioSupported;
private IRandomAccessStream _audioStream;
private FileSavePicker _fileSavePicker;
private DispatcherTimer _timer;
private TimeSpan _elapsedTime;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
InitializeAudioRecording();
}
private static void DecodeAudioFile()
{
String fileName = "record.wav";
WaveDecoder sourceDecoder = new WaveDecoder(fileName);
Signal sourceSignal = sourceDecoder.Decode();
RaisedCosineWindow window = RaisedCosineWindow.Hamming(1024);
Signal[] windows = sourceSignal.Split(window, 512);
ComplexSignal[] complex = windows.Apply(ComplexSignal.FromSignal);
complex.ForwardFourierTransform();
Debug.WriteLine(complex);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private async void InitializeAudioRecording()
{
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
settings.AudioProcessing = (_rawAudioSupported && _userRequestedRaw) ? AudioProcessing.Raw : AudioProcessing.Default;
await _mediaCaptureManager.InitializeAsync(settings);
Debug.WriteLine("Device initialised successfully");
_mediaCaptureManager.RecordLimitationExceeded += new RecordLimitationExceededEventHandler(RecordLimitationExceeded);
_mediaCaptureManager.Failed += new MediaCaptureFailedEventHandler(Failed);
}
private void Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
{
throw new NotImplementedException();
}
private void RecordLimitationExceeded(MediaCapture sender)
{
throw new NotImplementedException();
}
private async void CaptureAudio()
{
try
{
Debug.WriteLine("Starting record");
String fileName = "record.wav";
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Create record file successfully");
Debug.WriteLine(fileName);
MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
Debug.WriteLine("Start Record successful");
_recording = true;
}
catch (Exception e)
{
Debug.WriteLine("Failed to capture audio");
}
DecodeAudioFile();
}
private async void StopCapture()
{
if (_recording)
{
Debug.WriteLine("Stopping recording");
await _mediaCaptureManager.StopRecordAsync();
Debug.WriteLine("Stop recording successful");
_recording = false;
}
}
private async void PlayRecordedCapture()
{
if (!_recording)
{
var stream = await _recordStorageFile.OpenAsync(FileAccessMode.Read);
Debug.WriteLine("Recording file opened");
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, _recordStorageFile.FileType);
playbackElement1.Play();
}
}
private void Capture_Click(object sender, RoutedEventArgs e)
{
Capture.IsEnabled = false;
Stop.IsEnabled = true;
CaptureAudio();
}
private void Stop_Click(object sender, RoutedEventArgs e)
{
Capture.IsEnabled = true;
Stop.IsEnabled = false;
StopCapture();
}
private void Playback_Click(object sender, RoutedEventArgs e)
{
PlayRecordedCapture();
}
private void backBtn_Click(object sender, RoutedEventArgs e)
{
if (Frame.CanGoBack)
{
Frame.GoBack();
}
}
}
}
Any help or guidance in resolving these errors would be greatly appreciated,
Thanks
The original Accord.NET Framework is not accessible on other platforms than .NET.
There is an effort (of which I am responsible) for porting Accord.NET to mobile platforms via Portable Class Libraries. Several of these packages have been published on NuGet as well (prefix Portable Accord).
The Audio package is not published on NuGet, but you should be able to build it from source for Windows Phone 8.1. You can find the source for Portable Accord here.
Please note that only playback is supported, recording is not.
I have a problem changing text from another class in another namespace. I have the first Form1 class :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
static Form1 mainForm;
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
public static String LinkToApi = "http://google.com/api/";
public static Comunicator comunicator;
public static int debug = 5;
public Form1()
{
InitializeComponent();
AllocConsole(); // allow console
if(Form1.debug >= 3) Console.WriteLine("Application started");
comunicator = new Comunicator();
mainForm = this;
}
private void TestButton_Click(object sender, EventArgs e)
{
TestButton.Text = "Loading";
comunicator.TestConnection();
}
}
}
and this Comunicator class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Specialized;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
public class Comunicator
{
private String action = "idle";
public static Thread Start(Action action)
{
Thread thread = new Thread(() => { action(); });
thread.Start();
return thread;
}
public Comunicator()
{
}
public void TestConnection()
{
if (Form1.debug >= 3) Console.WriteLine("Testing connection");
// thread test
Start(new Action(ApiTest));
}
public void ApiTest()
{
if (Form1.debug >= 3) Console.WriteLine("API test begin");
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.bogotobogo.com/index.php");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
// Console.Read();
if (Form1.debug >= 3) Console.WriteLine("API test end");
// Form1.StaticTestButton.Text = "Loaded"; <---- CHANGE HERE
}
}
}
which is not even a form class (I want to keep everything nice and clean). I want to change the TestButton text into "LOADED" but i get an error when I try to do that as if Form1.TestButton does not exist in Comunicator class.
I have tried to instantiate the class, I made a couple of variables static ... nothing, still getting error.
What is the problem? How may I solve this?
The request must be asynchronous, that's why I am using threads.
You should separate concerns, and you shouldn't communicate with UI in class which is not related to UI.
You should rewrite your code.
But as quick fix you should do the following.
In class Comunicator, you can do such field.
private readonly Action<string> _notifySimpleMessageAction;
Then add to Communicator constructor parameter notifyFunction. Code in constructor:
_notifySimpleMessageAction = notifyFunction
After that you should create Communicator in following manner:
communicator = new Communicator((notification)=>
{
StaticTestButton.BeginInvoke((MethodInvoker)(() => StaticTestButton.AppendText(notification)));
});
Then at the end of your method you should do
_notifySimpleMessageAction("Loaded")
Controller class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControllerDemonstrator
{
public class Controller
{
public event EventHandler CommunicatorDataLoaded;
public event EventHandler FormTestConnection;
private Form1 _form;
private Communicator _communicator;
public Form1 MainForm
{
get { return _form; }
}
public Controller()
{
_form = new Form1(this);
_form.TestConnection += _form_TestConnection;
_form.FormClosed += _form_FormClosed;
_communicator = new Communicator(this);
_communicator.DataLoaded += _communicator_DataLoaded;
}
public void Start()
{
_form.Show();
}
void _form_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
{
// put any code to clean up the communicator resources (if needed) here
// --------------------------------------------------------------------
_communicator = null;
// Then exit
// ---------
Application.Exit();
}
private void _communicator_DataLoaded(object sender, EventArgs e)
{
if (null != CommunicatorDataLoaded)
{
CommunicatorDataLoaded(sender, e);
}
}
private void _form_TestConnection(object sender, EventArgs e)
{
if (null != FormTestConnection)
{
FormTestConnection(sender, e);
}
}
}
}
Basic form with one button (_testButton):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControllerDemonstrator
{
public partial class Form1 : Form
{
public event EventHandler TestConnection;
public Form1(Controller controller)
{
InitializeComponent();
controller.CommunicatorDataLoaded += controller_CommunicatorDataLoaded;
}
void controller_CommunicatorDataLoaded(object sender, EventArgs e)
{
_testButton.Text = "Loaded";
}
private void _testButton_Click(object sender, EventArgs e)
{
if (null != TestConnection)
{
TestConnection(this, new EventArgs());
}
}
}
}
Communicator class (everything has been stripped out, you will need to add in your logic):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ControllerDemonstrator
{
public class Communicator
{
public event EventHandler DataLoaded;
public Communicator(Controller controller)
{
controller.FormTestConnection += controller_FormTestConnection;
}
private void controller_FormTestConnection(object sender, EventArgs e)
{
// put your code that does the connection here
// -------------------------------------------
if (null != DataLoaded)
{
DataLoaded(this, new EventArgs());
}
}
}
}
And in your Program.cs (assuming that is how you are starting your application):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControllerDemonstrator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Controller c = new Controller();
Application.Run(c.MainForm);
}
}
}
With this kind of design, the communicator doesn't know about the form and vice verse. You can expand it out to have different kind's of communicators/forms/etc and have the controller keep track of everything. It is also much easier to test code like this as you can test each separate piece on it's own since they don't depend on each other. This is a quick and dirty implementation. Do some research on the Model View Controller design pattern (not Microsoft MVC for asp.Net, but the actual design pattern). It is more code up-front to code an application with the MVC design pattern but it makes it easier to test and more maintainable.
i'm struggling with simplest request handling in C# .NET, whenever i try to read something from request i usually get an Empty value.
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class server_save : System.Web.UI.Page
{
private string TXT_PATH = HttpContext.Current.Server.MapPath("files/saved.txt");
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
string DATA = Request["data"];
try
{
StreamWriter writer = new StreamWriter(TXT_PATH, true, Encoding.Default);
writer.WriteLine(DATA);
writer.Close();
Response.Write(DATA);
}
catch (Exception)
{
Response.Write(TXT_PATH);
}
}
}
http://pastebin.com/nJYBm4mX
hi i want to change label when i type in my browser one link. I create wcf service and i use one thread to change label in main form. Now when i click url in browser http://:5001/Connect i get this error for a reason. I dont understand the error here.
Invoke or BeginInvoke cannot be called on a control until the window
handle has been created.InvalidOperationException was unhandled
Must create object CashDesk_Form ? What must to do. Here is my codes:
MY FORM
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Threading;
namespace tameio
{
public partial class CashDesk_Form : Form
{
//Αντικείμενα
ServiceHost host;
public WCFService wcf;
//Μεταβλητές
string WCFPort = "5001";
//(ΔΗΜΙΟΥΡΓΟΣ) του Server
public CashDesk_Form()
{
InitializeComponent();
Thread startServerThread = new Thread(StartWCFServer);
startServerThread.IsBackground = true;
startServerThread.Start();
this.FormClosed += new FormClosedEventHandler(CashDesk_Form_FormClosed);
}
void CashDesk_Form_FormClosed(object sender, FormClosedEventArgs e)
{
if (host != null)
{
try { host.Close(); }
catch { }
host = null;
}
else MessageBox.Show("Ο Server είναι ήδη Απενεργοποιημένος");
}
public void AddNewConnection()
{
Thread clientThread = new Thread(new ThreadStart(_AddNewConnection));
clientThread.IsBackground = true;
clientThread.Start();
}
public void _AddNewConnection()
{
if (!IsHandleCreated)
this.CreateControl();
// ----> Exception here
this.Invoke((MethodInvoker)delegate
{
lbl_connectClients.Text = "ASDASDASD";
});
}
//(FUNCTION) - > Εκκίνηση του Server
private void StartWCFServer()
{
if (host == null)
{
Uri baseAddress = new Uri("http://localhost:" + WCFPort + "/");
host = new ServiceHost(typeof(WCFService), baseAddress);
host.AddServiceEndpoint(typeof(IWCFService), new WSHttpBinding(), "Services");
try
{
host.Open();
}
catch (Exception e)
{
if (e.GetType().FullName.ToString() == "System.InvalidOperationException") return;
else
{
MessageBox.Show("Βεβαιωθείτε ότι έχετε δικαιώματα διαχειριστή σε αυτόν τον υπολογιστή");
}
}
}
else
{
MessageBox.Show("Υπήρξε πρόβλημα κατά του άνοιγμα του WCF Server. Είτε ο WCF Server είναι Ενεργός, είτε το Port: " + WCFPort + " χρεισιμοποιείτε κάπου αλλού, είτε η IP του δικτύου δεν είναι σωστή");
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
WCFService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace tameio
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class WCFService : CashDesk_Form, IWCFService
{
public string connect()
{
AddNewConnection();
return "Έχετε συνδεθεί επιτυχώς με την εφαρμογή του ταμείου";
}
}
}
IWCFService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace tameio
{
[ServiceContract]
public interface IWCFService
{
[OperationContract(Name = "SendMessage")]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "Connect")]
//UriTemplate = "Send?Message={txt}")]
string connect();
}
}
Try and move the startup of the service to a later time:
public partial class CashDesk_Form : Form
{
public CashDesk_Form()
{
InitializeComponent();
this.FormClosed += new FormClosedEventHandler(CashDesk_Form_FormClosed);
}
protected override void OnShown(EventArgs e)
{
//at this point the handle *is* created
base.OnShown(e);
Thread startServerThread = new Thread(StartWCFServer);
startServerThread.IsBackground = true;
startServerThread.Start();
}
}
The exception you are getting i becuase you are starting up the WCF service in your forms constructor. At that point the handle for the Form has not yet been created - and therefore calling Connect could lead the the exception you are getting