namespace TinyChat
{
class Program
{
NetConnection Client;
static void Main(string[] args)
{
Program TinyChat_Function = new Program();
TinyChat_Function.connectTinyChat();
}
void connectTinyChat()
{
Client = new NetConnection();
Client.OnConnect += new ConnectHandler(Client_OnConnect);
Client.NetStatus += new NetStatusHandler(Client_NetStatus);
Client.Connect("rtmp://209.212.144.77:443/tinyconf", new string[] { "SomeRoom", "none", "show", "tinychat" });
}
}
Errors:
1 The name 'Client_OnConnect' does not exist in the current context
2 The name 'Client_netStatus' does not exist in the current context
Using latest version of FluorineFx.
The documentation shows that this is the right way to do this, but this does not work. Any ideas on how i can solve this problem?
The documentation can be found here.
Where is the code for the Client_OnConnectevent handler and the Client_NetStatusevent handlers? You are adding the events here in your lines , but you didn't implement the code. Unless you forgot to paste it in the question.
Client.OnConnect += new ConnectHandler(Client_OnConnect);
Client.NetStatus += new NetStatusHandler(Client_NetStatus);
You if you look at the documentation link this is the code
void netConnection_OnConnect(object sender, EventArgs e)
{
//The NetConnection object is connected now
netConnection.Call("serverHelloMsg", new ServerHelloMsgHandler(), "some text");
}
You should replace netConnection_OnConnect to Client_OnConnect and write the code in the method, maybe like this
void Client_OnConnect(object sender, EventArgs e)
{
//handle connection below and do whatever needs to be done
}
Related
I'm trying to implement Websockets in c# and i tried many ways but nothing works fine.
i) working fine with ClientwebSocket class but this class don't have events(i need events)
ii) tried with WebSocketSharp.WebSocket class but closing immediately after opening connection
iii) WebSocket4Net.WebSocket same problem closing connection immediately
can anyone please help me in solving this issue.A big thanks in advance.
class SocketConnection
{
public static WebSocketSharp.WebSocket client;
public void connectionEstablish()
{
//---------------------------WebSocketSharp ----------------------------
using (client = new WebSocketSharp.WebSocket("ws://localhost:8182"))
{
client.OnClose += new EventHandler<CloseEventArgs>(onClosed);
client.OnMessage += new EventHandler<MessageEventArgs>(onReceived);
client.OnOpen += new EventHandler(OnConnectionOpen);
client.Connect();
}
}
public static void onClosed(object sender, EventArgs e)
{
Console.WriteLine("Inclose");
}
public static void onReceived(object sender, MessageEventArgs e)
{
Console.WriteLine("received");
}
public void OnConnectionOpen(object sender, EventArgs e)
{
Console.WriteLine("opened connection");
}
}
I hope that your issue is with the using in the code. The variable client is an using variable so It will get disposed when using block ends(That is what the purpose of using, calling dispose automatically).
That means after executing the client.Connect(); using block ends and hence the object get disposed. To verify this, try remove the using block and change the code like the following:
var client = new WebSocketSharp.WebSocket("ws://localhost:8182");
Don't forget to dispose the object after use.
New to IIS and Mongo, and I'm trying to find a way to clear the keys from my server to avoid an "item with the same key has already been added" exception.
IMongoDatabase _db;
IMongoCollection<BoardStorageItem> _boardsCollection;
public MongoDb()
{
var client = new MongoClient("mongodb://localhost");
_db = client.GetDatabase("KanbanDemonstration");
BsonClassMap.RegisterClassMap<CardStorageItem>();
BsonClassMap.RegisterClassMap<ColumnStorageItem>();
BsonClassMap.RegisterClassMap<BoardStorageItem>();
BsonClassMap.RegisterClassMap<EmployeeStorageItem>();
_boardsCollection = _db.GetCollection<BoardStorageItem>("Board");
}
public BoardStorageItem GetBoardByName(string name)
{
var board = _boardsCollection.AsQueryable().FirstOrDefault(b => b.Name == name);
return board;
}
public class MongoConverter
{
MongoDb _mongoDb;
public MongoConverter()
{
_mongoDb = new MongoDb();
}
public BoardStorageItem GetBoardByName(string name)
{
return _mongoDb.GetBoardByName(name);
}
}
and then for the code on the web page itself
protected void Button1_Click(object sender, EventArgs e)
{
_mongoConverter = new MongoConverter();
var board = _mongoConverter.GetBoardByName(TextBox1.Text);
BoardName = board.Name;
BoardId = board.Id;
Label3.Text = BoardName;
Label4.Text = BoardId;
Session.Clear();
}
This works perfectly this first time I use the button to get a board, but if I try a second time, I get an exception "item with the same key has already been added" when attempting to new up MongoConverter. I had thought that clearing the session after would clear out the keys as well, but the only thing that seems to work is resetting the server itself.
Calling BsonClassMap.RegisterClassMap<T>() should only be done once per type. And it should be done at application startup, before opening any database connections according to the documentation.
Since you're in ASP.NET, put this in your Application_Start event in your global application class (global.asax)
void Application_Start(object sender, EventArgs e)
{
BsonClassMap.RegisterClassMap<CardStorageItem>();
BsonClassMap.RegisterClassMap<ColumnStorageItem>();
BsonClassMap.RegisterClassMap<BoardStorageItem>();
BsonClassMap.RegisterClassMap<EmployeeStorageItem>();
}
You can make another method that calls it so you don't pollute your global application class if you want. And of course, remove the registrations from your constructor.
After making the project simpler, I believe I identified the problem is actually a result the async marshalling.
UPDATE: I made the code simpler to try to figure out what was going on. So here is an update... The Observable collection is being populated on a new thread (async method). I tried moving the assigning of the ItemsSource to after the ObservableCollection is loaded as seen below
async void LoadAllData(object sender, EventArgs e)
{
if (sender != null)
{
App.GeoLocationComplete -= LoadAllData;
}
await ViewModelObjects.NearbyLocations.LoadLocationData();
lvPlaces.ItemsSource = ViewModelObjects.NearbyLocations.GBSLocationDetails;
}
The definition for the data load method is a follows:
public async Task LoadLocationData()
{....}
When I run this code I get the following error:
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
I know what is causing the error (the data was loaded on a thread other than the UI thread) but I don't know how to fix it. Suggestions?
UPDATE UPDATE: So I believe I have identified the root cause of the problem but have not figured out how to fix it. I started by simplifying my code as follows and it worked.
public nearbyplaces()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
LoadAllData(null, null);
}
void LoadAllData(object sender, EventArgs e)
{
lobj_Places = new ObservableCollection<GBSLocationDetail>()
{
new GBSLocationDetail()
{
Title = "Location 1",
Distance = "20 Miles",
AddInfo = "Something Else",
AttributesTexts="Gay, Bar, Dance"
}
};
lvPlaces.ItemsSource = lobj_Places;
}
HOWEVER, what I need is for the LoadAllData method to be called once I have the GPS location from the device. So in my App.XAML.cs I have the following delegate event declared:
public static Plugin.Geolocator.Abstractions.IGeolocator gobj_RealGeoCoordinator;
public static event GeoLocationCompleteEventHandler GeoLocationComplete;
public static bool gb_WaitingForLocation = true;
Then I have the following code call the event once I get the location back from the device:
private async void ProcessStartupandResume()
{
if (gobj_RealGeoCoordinator == null)
{
gobj_RealGeoCoordinator = CrossGeolocator.Current;
ViewModelObjects.AppSettings.CanAccessLocation = App.gobj_RealGeoCoordinator.IsGeolocationEnabled;
if (!ViewModelObjects.AppSettings.CanAccessLocation)
{
await MainPage.DisplayAlert(ResourceStrings.GetValue("NoLocationServicesTitle"), ResourceStrings.GetValue("NoLocationServicesMessage"), ResourceStrings.GetValue("OKButtonText"));
}
//Only add the events if the object has to be created.
gobj_RealGeoCoordinator.PositionChanged += gobj_RealGeoCoordinator_PositionChanged;
gobj_RealGeoCoordinator.PositionError += (sender, e) =>
{
ProcessException(new Exception(e.Error.ToString()));
};
}
//Set this to null to trigger the first check
ib_GPSReenabled = null;
if (gobj_RealGeoCoordinator.IsListening)
await gobj_RealGeoCoordinator.StopListeningAsync();
gobj_RealGeoCoordinator.DesiredAccuracy = 50;
await gobj_RealGeoCoordinator.StartListeningAsync(10000, 20);
}
private static void gobj_RealGeoCoordinator_PositionChanged(object sender, PositionEventArgs e)
{
var pos = e.Position;
ViewModelObjects.AppSettings.Latitude = pos.Latitude;
ViewModelObjects.AppSettings.Longitude = pos.Longitude;
if (gb_WaitingForLocation)
{
gb_WaitingForLocation = false;
GeoLocationComplete?.Invoke(new object() , null);
}
}
Then in my page I subscribe to the GeoLocationComplete event using the LoadAllData method as seen below. Even when I use a local object and try to set the ItemsSource for the ListView in the code when executed as a result of the event being raised, I receive the error. See code below which subscribed to the event:
public nearbyplaces()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
if (App.gb_WaitingForLocation)
App.GeoLocationComplete += LoadAllData;
else
LoadAllData(null, null);
}
Any suggestions on how to fix this?
OK so I figured it out. I needed to invoke the event on the main thread and I did that with the following code:
Device.BeginInvokeOnMainThread(() =>
{
GeoLocationComplete?.Invoke(new object(), null);
});
After inserting this code, the error was gone. Changing the code back to simply
GeoLocationComplete?.Invoke(new object(), null);
cause the error to occur again. Thus I believe this resolved my problem. Hope this helps someone else. :)
I'm using Kellerman .NET SFTP Library and I'm having some issues using event handlers
According to the documentation it has the following events:
I'm interested in two of them:
TransferCompleteEvent
FailureEvent
I would like to display a message when the transfer is complete and restart the upload if connection failed.
In my class I have the following:
public static void uploadToSFTP()
{
try
{
SFTP myConnection = new SFTP();
myConnection.EnableLogging();
myConnection.HostAddress = "servername";
myConnection.UserName = "username";
myConnection.Password = "password";
myConnection.CurrentDirectory = "directory";
myConnection.Connect();
//UPLOADING FILE TO SFTP SERVER
myConnection.UploadFileAsync(yesterdaysZipFile, localZipFileName);
while (myConnection.IsBusy == true)
{
//PRINT HOW LONG REMAINING FROM UPLOAD
Console.WriteLine(myConnection.EstimatedTimeRemaining);
}
//declaring an eventhandler
myConnection.TransferCompleteEvent += SFTPCompleted;
myConnection.Disconnect();
myConnection.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
And then I have
public static void SFTPCompleted(Object sender, TransferCompletedEventArgs e)
{
Console.WriteLine("Completed");
}
My problem is in this line:
myConnection.TransferCompleteEvent += SFTPCompleted;
When I use the debugger and get to this line it skips and goes to the next line it never goes to
public static void SFTPCompleted(Object sender, TransferCompletedEventArgs e)
{
Console.WriteLine("Completed");
}
What am I doing wrong here?
And in regards the FailureEvent I can't even get it to compile:
myConnection.FailureEvent += TransferFailed;
Here's the event:
public static void TransferFailed(Object sender, SFTP.FailureEventHandler e)
{
Console.WriteLine("failed");
}
I get this compiler error:
Error 1 No overload for 'TransferFailed' matches delegate 'KellermanSoftware.NetSFtpLibrary.SFTP.FailureEventHandler'
This is my first time using this library. Any suggestion would be helpful.
This line:
myConnection.TransferCompleteEvent += SFTPCompleted;
is attaching an event handler.
You are attaching the event handler after calling UploadFileAsync and waiting for it to stop being busy. At this point, the event would have already fired, so you're missing out on hearing about it.
You should attach the event handler as soon as you create the myConnection object.
SFTP myConnection = new SFTP();
myConnection.TransferCompleteEvent += SFTPCompleted;
Your second problem is that you cannot attach the TransferFailed event. That's because you have the wrong parameters in your handler function. My guess is that it should be:
public static void TransferFailed(Object sender, SFTP.FailurEventArgs e)
Have a look at the SFTP.FailureEventHandler declaration. It will tell you what the parameters need to be.
I am a starter who is stuck very badly on this initially my main aim is to control robots using speech. Initially I started with making grammar for my speech with this code I was even successful my code is this I made this in windows form application:
using System.Speech.Recognition;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a new SpeechRecognizer instance.
sr = new SpeechRecognizer();
// Create a simple grammar that recognizes "red", "green", or "blue".
Choices colors = new Choices();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
colors.Add("white");
GrammarBuilder gb = new GrammarBuilder();
gb.Append(colors);
// Create the actual Grammar instance, and then load it into the speech recognizer.
Grammar g = new Grammar(gb);
sr.LoadGrammar(g);
// Register a handler for the SpeechRecognized event.
sr.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sr_SpeechRecognized);
}
// Simple handler for the SpeechRecognized event.
private void sr_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
MessageBox.Show(e.Result.Text);
}
private SpeechRecognizer sr;
}
Now from this code when I speak red , I get red in message box now I want to control motors therefore i need to communicate with my robots therefore i MADE ONE CONSOLE APPLICATION from help from internet FOR SENDING DATA TO MY SERVO CONTROLLER -SSC 32 THE CODE FOR ABOVE IS:
using System.IO.Ports;
using System.Threading;
namespace cConsoleAppMonitorServoCompletion
{
class Program
{
static SerialPort _serialPort;
static void Main(string[] args)
{
try
{
_serialPort = new SerialPort();
_serialPort.PortName = "COM3";
_serialPort.Open();
_serialPort.Write("#27 P1600 S750\r");
Console.WriteLine("#27 P1500 S750\r");
string output;
output = "";
//Example: "Q <cr>"
//This will return a "." if the previous move is complete, or a "+" if it is still in progress.
while (!(output == ".")) //loop until you get back a period
{
_serialPort.Write("Q \r");
output = _serialPort.ReadExisting();
Console.WriteLine(output);
Thread.Sleep(10);
}
_serialPort.Close();
}
catch (TimeoutException) { }
}
}
}
Now I want like when I speak red instead of giving a text box I want get serial command like _serialPort.Write("#27 P1600 S750\r");
Please help I have tried but I was not successful , it is my humble request please answer in more detailed manner , I am a just starter so it will be easy for me thanks in advance.
Controlling a robot using voice recognition... an ambitious project for a starter! There could be a million things going wrong here.
Just as important as the ability to write code is the ability to debug it. What can you tell us further - which parts work, which parts don't? Have you single-stepped through the code to see what happens and when, to diagnose where things start to go wrong?
You could also try some debugging output - Console.WriteLine for example - so we you can see the state of variables and flow of the code as it's running.
It looks like you need to use System.Diagnostics.Process.Start
This page has an example - how to execute console application from windows form?
// Simple handler for the SpeechRecognized event.
private void sr_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
System.Diagnostics.Process.Start( #"cmd.exe", #"/k c:\path\my.exe" );
}
An ambitious starter project indeed!
Update
private bool LaunchApp(String sAppPath, String sArg)
{
bool bSuccess = false;
try
{
//create a new process
Process myApp = new Process();
myApp.StartInfo.FileName = sAppPath;
myApp.StartInfo.Arguments = sArg;
bSuccess = myApp.Start();
}
catch (Win32Exception e)
{
MessageBox.Show("Error Details: {0}", e.Message);
}
return bSuccess;
}
if Now I want like when I speak red instead of giving a text box I want get serial command means - just to _serialPort.Write("#27 P1600 S750\r"); instead of showing messagebox (i.e. MessageBox.Show(e.Result.Text);) then task is really simple. just copy-paste that code. and add using System.IO.Ports; so that u can work with ports.
so prolly ur code will look like this:
private void sr_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
//MessageBox.Show(e.Result.Text);
try
{
_serialPort = new SerialPort();
_serialPort.PortName = "COM3";
_serialPort.Open();
_serialPort.Write("#27 P1600 S750\r");
Console.WriteLine("#27 P1500 S750\r");
string output;
output = "";
//Example: "Q <cr>"
//This will return a "." if the previous move is complete, or a "+" if it is still in progress.
while (!(output == ".")) //loop until you get back a period
{
_serialPort.Write("Q \r");
output = _serialPort.ReadExisting();
Console.WriteLine(output);
Thread.Sleep(10);
}
_serialPort.Close();
}
catch (TimeoutException) { }
}
p.s.
if you don't understand how SerialPort Class works go to MSDN