c# Android access textview from another class - c#

I'm writing an android app in c#, which communicates with a server.
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.button1);
TextView txt = FindViewById<TextView>(Resource.Id.textView1);
Client client = new Client();
client.Setup("ws://192.168.0.14:8001", "basic", WebSocketVersion.Rfc6455);
client.Start();
...
On start up, it should display a message on the TextView.
class Client : Activity{
private WebSocket websocketClient;
...
public void Setup(string url, string protocol, WebSocketVersion version)
{
...
websocketClient.Opened += new EventHandler(websocketClient_Opened);
}
private void websocketClient_Opened(object sender, EventArgs e){
txt.Text = ("Client successfully connected."); // this line is wrong
websocketClient.Send("Hello World!");
}
}
The problem is, I have no idea, how to access the TextView. I found this, but I don't know how should I use it in my case.

I don't know what library WebSocket you a using. I using websocket-sharp. It is example use:
protected override void OnCreate(Bundle bundle)
{
TextView txt = FindViewById<TextView>(Resource.Id.My);
using (var ws = new WebSocket("ws://dragonsnest.far/Laputa"))
{
ws.OnError += (sender, e) =>
{
txt.Text = e.Message;
};
..........
}
It is work. I see error message in my TextView.
If you get error, try use RunOnUiThread.Example:
private void websocketClient_Opened(object sender, EventArgs e)
{
this.RunOnUiThread(() =>
{
txt.Text = "your message";
});
}
Hope this help.

Just make WebsocketClient a property it a instead of a class variable and then you can access it from you activity.
public class MainActivity : Activity
{
private TextView txt;
private Client client;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
txt = FindViewById<TextView>(Resource.Id.textView1);
client = new Client();
client.WebsocketClient.Opened += websocketClient_Opened;
client.Setup("ws://192.168.0.14:8001", "basic", WebSocketVersion.Rfc6455);
client.Start();
}
protected override void OnDestroy()
{
client.WebsocketClient.Opened -= websocketClient_Opened;
base.OnDestroy();
}
private void websocketClient_Opened(object sender, EventArgs e)
{
txt.Text = ("Client successfully connected.");
// maybe have to be wrapped in a RunOnUiThread(() =>{ ... });
}
}
class Client
{
public WebSocket WebsocketClient { get; set; }
public void Setup(string url, string protocol, WebSocketVersion version)
{
// WebsocketClient = new ...
WebsocketClient.Opened += websocketClient_Opened;
}
private void websocketClient_Opened(object sender, EventArgs e)
{
WebsocketClient.Send("Hello World!");
}
}

Related

Show message after a successful record saving

I am new to XAF Blazor so I trying to display a message to end users after a successful record saving, so I wrote the following code:
public partial class MessageSavedSuccessfullyViewController : ViewController
{
public MessageSavedSuccessfullyViewController()
{
InitializeComponent();
}
protected override void OnActivated()
{
base.OnActivated();
View.ObjectSpace.Committing += ObjectSpace_Committing;
}
protected override void OnViewControlsCreated()
{
base.OnViewControlsCreated();
}
protected override void OnDeactivated()
{
View.ObjectSpace.Committing -= ObjectSpace_Committing;
base.OnDeactivated();
}
private void ObjectSpace_Committing(object sender, CancelEventArgs e)
{
if (View.ObjectSpace.IsCommitting)
{
MessageOptions options = new();
options.Duration = 2000;
options.Message = string.Format("Record Saved Successfully");
options.Type = InformationType.Success;
options.Web.Position = InformationPosition.Right;
options.Win.Caption = "Success";
options.Win.Type = WinMessageType.Toast;
Application.ShowViewStrategy.ShowMessage(options);
}
}
}
but when I run the code, nothing happens.
Is there something I am missing?
This code should be used across my entire application, not just in a specific view.
public partial class MessageSavedSuccessfullyViewController : ViewController<DetailView>
{
private string message;
public MessageSavedSuccessfullyViewController()
{
InitializeComponent();
}
protected override void OnActivated()
{
base.OnActivated();
View.ObjectSpace.ObjectChanged += ObjectSpace_ObjectChanged;
View.ObjectSpace.Committed += ObjectSpace_Committed;
}
protected override void OnViewControlsCreated()
{
base.OnViewControlsCreated();
}
protected override void OnDeactivated()
{
View.ObjectSpace.ObjectChanged -= ObjectSpace_ObjectChanged;
View.ObjectSpace.Committed -= ObjectSpace_Committed;
base.OnDeactivated();
}
void ObjectSpace_Committed(object sender, EventArgs e)
{
MessageOptions options = new();
options.Duration = 2000;
options.Message = message;
options.Type = InformationType.Success;
options.Web.Position = InformationPosition.Right;
options.Win.Caption = "Success";
options.Win.Type = WinMessageType.Toast;
Application.ShowViewStrategy.ShowMessage(options);
message = string.Empty;
}
void ObjectSpace_ObjectChanged(object sender, ObjectChangedEventArgs e)
{
if (ObjectSpace.IsNewObject(e.Object))
{
message=string.Format("Record Saved Successfully");
}
else if (ObjectSpace.IsDeleting)
{
message = string.Format("Record Deleted Successfully");
}
else if (ObjectSpace.IsModified && e.OldValue != e.NewValue)
{
message = string.Format("Record Updated Successfully");
}
}
}

Unable to start New Activity from old fragment?? Button click is doing nothing

On Fragment :
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
buttonRedirect = View.FindViewById<Button>(Resource.Id.send);
buttonRedirect.Click += BtnOption_Click;
}
private void BtnOption_Click(object sender, EventArgs e)
{
string imageString = "Some Data I am sending"
StartNewActivity();
}
private void StartNewActivity()
{
Intent intent = new Intent(this.Activity,
typeof(New Activity Page));
intent.PutExtra("ImageString", imageString);
StartActivity(intent);
}
I am a beginner in Xamarin android but unable to decode this.Debugger is going to StartNewActivity() when pressing button , but doing nothing ..

Receiving back server response towards clients request

Currently I am using WebSocket-Sharp. I am able to connect to the server through my application and I am able to send a Client.Send(Move.HeadNod); to the server on button click. However even though I declared
private WebSocket client;
const string host="ws://localhost:80";
public Form1()
{
InitializeComponent();
client=new WebSocket(host);
client.connect();
Client.OnMessage+=client_OnMessage
}
where:
client_OnMessage(object sender,MessageEventArgs e)
{
textbox1.text=convert.tostring(e);
client.send(move.headleft);
}
I am still unable to get a response from the server and continue sending command afterwards.
Edit
void Client_OnMessage(object sender,MessageEventArgs e)
{
if(e.IsText)
{
edata=e.data;
return;
}
else if(e.IsBinary)
{
Textbox1.Text=Convert.Tostring(e.RawData);
return;
}
}
This is the complete code that works on my machine. Put a break-point in both event handlers to see what happens. Maybe your web socket server throws an exception and you just don't know it:
public partial class Form1 : Form
{
private readonly WebSocket _client;
public Form1()
{
InitializeComponent();
_client = new WebSocket("ws://echo.websocket.org");
_client.OnMessage += Ws_OnMessage;
_client.OnError += Ws_OnError;
_client.Connect();
}
private void Ws_OnError(object sender, ErrorEventArgs e)
{
}
private void Ws_OnMessage(object sender, MessageEventArgs e)
{
if (e.IsText)
{
Invoke(new MethodInvoker(delegate () {
textBox1.Text = e.Data;
}));
}
else if (e.IsBinary)
{
Invoke(new MethodInvoker(delegate () {
textBox1.Text = Convert.ToString(e.RawData);
}));
}
}
private void button1_Click(object sender, System.EventArgs e)
{
_client.Send("Hi");
}
}

Windows store app error during print operation

I am running my windows store app and i got error like this.
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code
WinRT information: Only one handler for the PrintTaskRequested event may be registered at a time.
Additional information: A method was called at an unexpected time.
My code is here.help me to get understand the problem and resolve this issue.Kindly tell me know the exact problem.
//print sample
protected PrintDocument printDocument = null;
protected IPrintDocumentSource printDocumentSource = null;
internal List<UIElement> printPreviewElements = new List<UIElement>();
protected event EventHandler pagesCreated;
Error came in print task requested handler
protected virtual void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequested =>
{
printTask.Completed += async (s, args) =>
{
if (args.Completion == PrintTaskCompletion.Failed)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
MessageDialog dialog = new MessageDialog("Something went wrong while trying to print. Please try again.");
await dialog.ShowAsync();
});
}
};
sourceRequested.SetSource(printDocumentSource);
});
}
protected virtual void RegisterForPrinting()
{
printDocument = new PrintDocument();
printDocumentSource = printDocument.DocumentSource;
printDocument.Paginate += CreatePrintPreviewPages;
printDocument.GetPreviewPage += GetPrintPreviewPage;
printDocument.AddPages += AddPrintPages;
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested += PrintTaskRequested;
}
protected virtual void UnregisterForPrinting()
{
if (printDocument != null)
{
printDocument.Paginate -= CreatePrintPreviewPages;
printDocument.GetPreviewPage -= GetPrintPreviewPage;
printDocument.AddPages -= AddPrintPages;
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested -= PrintTaskRequested;
}
}
protected virtual void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
{
printPreviewElements.Clear();
PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
AddOnePrintPreviewPage(pageDescription);
if (pagesCreated != null)
{
pagesCreated.Invoke(printPreviewElements, null);
}
((PrintDocument)sender).SetPreviewPageCount(printPreviewElements.Count, PreviewPageCountType.Intermediate);
}
protected virtual void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
{
((PrintDocument)sender).SetPreviewPage(e.PageNumber, printPreviewElements[e.PageNumber - 1]);
}
protected virtual void AddPrintPages(object sender, AddPagesEventArgs e)
{
foreach (UIElement element in printPreviewElements)
{
printDocument.AddPage(element);
}
((PrintDocument)sender).AddPagesComplete();
}
protected virtual void AddOnePrintPreviewPage(PrintPageDescription printPageDescription)
{
TextBlock block = new TextBlock();
block.Text = "This is an example.";
block.Width = printPageDescription.PageSize.Width;
block.Height = printPageDescription.PageSize.Height;
printPreviewElements.Add(block);
}
//protected override void OnNavigatedTo(NavigationEventArgs e)
//{
// RegisterForPrinting();
//}
//protected override void OnNavigatedFrom(NavigationEventArgs e)
//{
// UnregisterForPrinting();
//}
private void printBirth_Click(object sender, RoutedEventArgs e)
{
RegisterForPrinting();
}
you can use it
private async void printBirth_Click(object sender, RoutedEventArgs e)
{
await Windows.Graphics.Printing.PrintManager.showPrintUIAsync()
}

WPF: How to write stream which owned by main process in thread?

I want to implement this function: when receive a http request, then create a new window form, and waiting for user inputing response text and write to the http response stream. The quesition is, I can not write response text to the stream in thread even I useing the Action<> delegate. Some code like this:
public partial class MainWindow : Window
{
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//startup web server
Dispatcher.BeginInvoke(new Action(Start));
}
private void Start()
{
var server = new HttpServer();
try
{
server.EndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
server.RequestReceived += DataProcess;
}
catch (Exception ex)
{
return;
}
}
private void DataProcess(object sender, HttpRequestEventArgs e)
{
//create a new window in which user can input the response for the http request e.
var pw = (PrivateWindow)Dispatcher.Invoke(new Func<HttpRequestEventArgs, PrivateWindow>(CreatePrivateWindow), e);
}
public PrivateWindow CreatePrivateWindow(string windowKey, HttpRequestEventArgs e)
{
var pw = new PrivateWindow();
pw.httpRequest = e;//pass the stream to thread here.
windows.Add(pw);
return pw;
}
}
public partial class PrivateWindow : Window
{
private void btnSendMessage_Click(object sender, RoutedEventArgs e)
{
string messageText = new TextRange(txtWriteMessage.Document.ContentStart, txtWriteMessage.Document.ContentEnd).Text.Trim();
//write the response in thread
Dispatcher.BeginInvoke(new Action<HttpRequestEventArgs, string>(WriteToStream), httpRequest, messageText);
}
private void WriteToStream(HttpRequestEventArgs e, string str)
{
//**here occurs "stream can not be written" error.**
using (var writer = new StreamWriter(e.Response.OutputStream))
{
writer.Write(str);
}
}
}

Categories