I am using language programming C# and I am making a program that is using Telegram API called TLSharp and I wanna know can I load My contacts from Telegram So I used these codes that I found in stackoverflow but something went wrong
private async void button2_Click(object sender, EventArgs e)
{
try
{
client = new TelegramClient(****, "****");
await client.ConnectAsync();
button2.BackColor = Color.Green;
button1.Enabled = true;
button2.Text = "Connected";
}
catch
{
button2.BackColor = Color.Red;
button1.Enabled = false;
button2.Text = "Disconnected";
}
}
string hash;
private async void button1_Click(object sender, EventArgs e)
{
try
{
hash = await client.SendCodeRequestAsync(textBox1.Text);
panel1.Hide();
panel2.Show();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error");
}
}
private async void button3_Click(object sender, EventArgs e)
{
try
{
var result = await client.GetContactsAsync();
//find recipient in contacts
var user = result.users.lists.Where(x=>x.GetType()==typeof(TLUser)).Cast<TLUser>();
foreach (var item in user.username)
{
listBox1.Items.Add(item);
}
}
catch
{
}
}
But the problem is here , the list-box shows something which isn't Username and I don't know what is it and the list-box shall show my username of my contacts; It shows only my username like this #username
Related
I am using inetlab.smpp in c# web app to send sms. A client is created and connected successfully and bound but the message is not delivered to the recipient
public partial class sendsmss : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected async void send_Click(object sender, EventArgs e)
{
SmppClient client = new SmppClient();
await client.Connect("xx.xx.xx.xx", 00000);
if (client.Status == Inetlab.SMPP.Common.ConnectionStatus.Open)
{
await client.Bind("user", "pass");
if (client.Status == Inetlab.SMPP.Common.ConnectionStatus.Open)
{
SubmitSm sm = new SubmitSm();
sm.UserData.ShortMessage = client.EncodingMapper.GetMessageBytes("Test Test Test Test Test Test Test Test Test Test", DataCodings.Default);
sm.SourceAddress = new SmeAddress("1111");
sm.DestinationAddress = new SmeAddress("12345678");
sm.DataCoding = DataCodings.UCS2;
sm.RegisteredDelivery = 1;
await client.Submit(sm);
SubmitSmResp response = await client.Submit(sm);
if (response.MessageId != "")
{
Response.Write("response.messageID is " + response.MessageId.ToString() + "</br> ");
}
else { Response.Write("response null </br> "); }
await client.UnBind();
}
}
}
}
I expect the sms is delivered to recipient
Runs for me perfectly
private async void button1_Click(object sender, EventArgs e)
{
Inetlab.SMPP.SmppClient client = new Inetlab.SMPP.SmppClient();
await client.Connect("x.x.x.x", y);
await client.Bind("systemid", "password", ConnectionMode.Transceiver);
var resp = await client.Submit(
SMS.ForSubmit()
.From("SOURCEADDR", AddressTON.Alphanumeric, AddressNPI.Unknown )
.To("mobilenumber", AddressTON.International, AddressNPI.ISDN)
.Coding(DataCodings.Default)
.Text("test text")
);
if (resp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
{
MessageBox.Show("Message has been sent.");
}
else
{
MessageBox.Show(resp.GetValue(0).ToString());
}
}
I'm working on a Chat Application on Windows Form using C# Socket Programming.
Currently, my App send messages as "ME" and receives messages as "FRIEND".
What I want is to add a textbox which asks Client for username and server receives messages as that username. Following is my code:
namespace ServerClientChat
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public string receive2;
public String text_to_send;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //getting own IP
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBox3.Text = address.ToString();
}
}
// textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
private void button3_Click(object sender, EventArgs e) //Connect to server
{
client = new TcpClient();
//set client side endpoint consisting of client's ip address and port
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text),int.Parse(textBox6.Text));
try
{
client.Connect(IP_End);
if(client.Connected)
{
textBox2.AppendText(">> Connected to Server"+ "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
TcpListener listener = new TcpListener(IPAddress.Any,int.Parse(textBox4.Text)); //Listens for connections from TCP network clients.
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream()); //Implements a TextReader that reads characters from a byte stream in a particular encoding.
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true; //Setting AutoFlush to true means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed.
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //to receive data
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText("Friend: " + receive + "\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //to send data
{
if(client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText("Me: " + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Send Failed");
}
backgroundWorker2.CancelAsync();
}
private void button1_Click(object sender, EventArgs e) //Send button
{
if(textBox1.Text!="")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
DialogResult f = MessageBox.Show("Welcome to My Chat App! Do you want to start your own Server? ", "Welcome!", MessageBoxButtons.YesNoCancel);
if (f == DialogResult.Yes)
{
button3.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
}
if (f == DialogResult.No)
{
button2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(this, new EventArgs());
}
}
}
}
You can create something like your own protocol and send it to a server.
<username>YourName</username>
<msg>Hello World</msg>
But in real-life applications you should use database with user authorization process.
I was programming a "Minecraft" server manager program, but i don't know why, System.Windows.Threading doesn't exist (Visual C# says that), and in here: http://msdn.microsoft.com/en-us/library/vstudio/system.windows.threading.dispatcher, it says it should exist. Please help! (Message boxes are in Polish, becouse im from Poland, later i will add multi language support)
My code:
using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Process server;
private Boolean runServer()
{
if (!File.Exists(textBox2.Text))
{
MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Process process = new Process
{
StartInfo =
{
FileName = textBox2.Text,
//Arguments = textBox3.Text,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
}
};
process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
server = process;
if (process.Start())
return true;
else
{
MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private String ReadFile(String filename, int line)
{
StreamReader reader = new StreamReader(filename);
for (int i = 0; i < line; i++)
{
reader.ReadLine();
}
return reader.ReadLine();
}
private void ReloadOPs()
{
if (!File.Exists(textBox1.Text))
{
MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
tabControl1.SelectedTab = tabPageOptions;
textBox1.SelectAll();
return;
}
String line = ReadFile(textBox1.Text, 0);
comboBox1.Items.Clear();
for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
{
if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
{
comboBox1.Items.Add(line);
line = ReadFile(textBox1.Text, i);
}
}
MessageBox.Show("Lista graczy z OP, została odświeżona.");
}
// OPs combobox (OPs)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
groupBox1.Text = comboBox1.SelectedItem.ToString();
groupBox1.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = Application.StartupPath.ToString() + #"\ops.txt";
ReloadOPs();
}
// Reload OPs button (OPs)
private void button1_Click(object sender, EventArgs e)
{
ReloadOPs();
}
// Save button (Options)
private void button4_Click(object sender, EventArgs e)
{
}
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
{
addConsoleMessage(e.Data.ToString(), true);
});
}
// Run server button (Menu)
private void button5_Click(object sender, EventArgs e)
{
if (!runServer())
return;
server.BeginOutputReadLine();
button6.Enabled = true;
}
// Stop server button (Menu)
private void button6_Click(object sender, EventArgs e)
{
if(!server.HasExited)
server.Kill();
button6.Enabled = false;
}
private void addConsoleMessage(String message, Boolean refresh)
{
listBox1.Items.Add(message);
if (refresh)
listBox1.Refresh();
}
}
}
My error code: Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type (server_outputDataReceived)
You are targeting WinForm application and you are trying to use threading from WPF.
System.Windows.Threading Namespace
Contains types to support the Windows Presentation Foundation (WPF)
threading system
You should use: System.Threading Namespace. You may also see Threading in Windows Forms by Jon Skeet
I have been working on a manager application for a Minecraft server, when I run my program, the console shows and disappears, if I run it manually, it runs without and problems.
Batch file code:
java -Xmx1024M -jar craftbukkit-1.7.2-R0.3.jar -o false
My full code (MessageBoxes are in Polish, becouse im from Poland, but later i will add support for other languages):
using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Process server;
private Boolean runServer()
{
if (!File.Exists(textBox2.Text))
{
MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Process process = new Process
{
StartInfo =
{
FileName = textBox2.Text,
//Arguments = textBox3.Text,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
}
};
process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
server = process;
if (process.Start())
return true;
else
{
MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private String ReadFile(String filename, int line)
{
StreamReader reader = new StreamReader(filename);
for (int i = 0; i < line; i++)
{
reader.ReadLine();
}
return reader.ReadLine();
}
private void ReloadOPs()
{
if (!File.Exists(textBox1.Text))
{
MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
tabControl1.SelectedTab = tabPageOptions;
textBox1.SelectAll();
return;
}
String line = ReadFile(textBox1.Text, 0);
comboBox1.Items.Clear();
for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
{
if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
{
comboBox1.Items.Add(line);
line = ReadFile(textBox1.Text, i);
}
}
MessageBox.Show("Lista graczy z OP, została odświeżona.");
}
// OPs combobox (OPs)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
groupBox1.Text = comboBox1.SelectedItem.ToString();
groupBox1.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = Application.StartupPath.ToString() + #"\ops.txt";
ReloadOPs();
}
// Reload OPs button (OPs)
private void button1_Click(object sender, EventArgs e)
{
ReloadOPs();
}
// Save button (Options)
private void button4_Click(object sender, EventArgs e)
{
}
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
addConsoleMessage(e.Data.ToString(), true);
}
// Run server button (Menu)
private void button5_Click(object sender, EventArgs e)
{
if (!runServer())
return;
server.BeginOutputReadLine();
button6.Enabled = true;
}
// Stop server button (Menu)
private void button6_Click(object sender, EventArgs e)
{
if(!server.HasExited)
server.Kill();
button6.Enabled = false;
}
private void addConsoleMessage(String message, Boolean refresh)
{
listBox1.Items.Add(message);
if (refresh)
listBox1.Refresh();
}
}
}
My problem is that program crashes becouse InvaildOperationException was unhandled (listBox1.Items.Add(message) in addConsoleMessage).
External error information: Invalid operation between threads: the control 'listBox1' is accessed from a thread other than the thread it was created.
You cannot update UI form background thread. Try this
WPF
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
{
addConsoleMessage(e.Data.ToString(), true);
});
}
Update
In WinForms the Invoke/BeginInvoke methods are directly on the control objects as you can see from the docs of System.Windows.Forms.Control. So you'd have listBox1.BeginInvoke(...) for example.
I would like to have a combo box on my form which allows the user to select the voice which they would like to use. How can I implement such a feature?
Currently, my form consists of four buttons and a combo box. The code behind the buttons and the synthesizer is as follows:
private void button1_Click(object sender, EventArgs e)
{
reader.Dispose();
if (Basic_Word_Processor.Instance.richTextBoxPrintCtrl1.Text != "")
{
reader = new SpeechSynthesizer();
reader.SpeakAsync(Basic_Word_Processor.Instance.richTextBoxPrintCtrl1.Text)
button2.Enabled = true;
button4.Enabled = true;
reader.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(reader_SpeakCompleted);
}
else
{
MessageBox.Show("Please insert text before launching Text to Speech.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void reader_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
if (reader != null)
{
if (reader.State == SynthesizerState.Speaking)
{
reader.Pause();
button3.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
if (reader != null)
{
if (reader.State == SynthesizerState.Paused)
{
reader.Resume();
}
button3.Enabled = false;
}
}
private void button4_Click(object sender, EventArgs e)
{
if (reader != null)
{
reader.Dispose();
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
}
I would like to populate a combo box with a list of currently installed voices, which, when the user clicks one, reads the text from richTextBoxPrintCtrl1 in the selected voice. Currently, the synthesizer works, but I would like to add this feature to my Text to Speech feature.
Thanks.
This code should do roughly what you are after (if you are still interested:). You will need to drag on a new comboxbox called 'comboBox1' onto your form
private SpeechSynthesizer reader = new SpeechSynthesizer();
private void PopulateInstalledVoices()
{
foreach (InstalledVoice voice in
reader.GetInstalledVoices(new CultureInfo("en-US")))
{
VoiceInfo info = voice.VoiceInfo;
comboBox1.Items.Add(info.Name);
}
}
private void Form1_Load(object sender, EventArgs e)
{
PopulateInstalledVoices();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var voice = comboBox1.SelectedItem as String;
if (voice != null)
{
reader.SelectVoice(voice);
}
}
private void button1_Click(object sender, EventArgs e)
{
reader.SpeakAsync("this is a test message");
}