How to send sms using inetlab.smpp in c# web app - c#

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());
}
}

Related

Trying to get data from firebase but it shows Json error"Could not cast or convert" c#

I am trying to get data from firebase but it shows an error "Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2"
This is my code:
IFirebaseConfig config = new FirebaseConfig()
{
AuthSecret = "Auth",
BasePath = "Path"
};
IFirebaseClient client;
private void Form1_Load(object sender, EventArgs e)
{
try
{
client = new FirebaseClient(config);
if (client != null)
{
MessageBox.Show("OK");
}
}
catch
{
MessageBox.Show("No");
}
LiveCall();
}
async void LiveCall()
{
while (true)
{
await Task.Delay(1000);
FirebaseResponse res = await client.GetAsync(#"GPS/lat");
Dictionary<string, GPS> data = JsonConvert.DeserializeObject<Dictionary<string, GPS>>(res.Body.ToString());
UpdateRTB(data);
}
}
void UpdateRTB(Dictionary<string, GPS> record)
{
label1.Text += record.ElementAt(1).Key + record.ElementAt(1).Value;
}
Can Anybody help me to solve the problem? thanks!

TLSharp Telegram API. Check phone registrered

I've got a problem with TLSharp method IsPhoneRegisteredAsync(...).
It always returns true, no matter the number I'm trying to check. Even for an input like "asdhbqaihbqwieuashdq23934327940scj0" it returns true.
Thanks for your help.
My code:
private void button1_Click(object sender, EventArgs e)
{
connectClient(SETS.API_ID, SETS.API_HASH);
}
private async void connectClient(int api_id, string api_hash)
{
client = new TelegramClient(api_id, api_hash);
api_ID_tb.Text = api_id.ToString();
api_hash_tb.Text = api_hash;
await client.ConnectAsync();
if (client.IsConnected)
{
MessageBox.Show("Connect Succefull");
}
}
async void CheckNumber(string number)
{
bool q = await client.IsPhoneRegisteredAsync(number);
MessageBox.Show(q.ToString());
}
private void numberCheckBtn_Click(object sender, EventArgs e)
{
CheckNumber(number_tb.Text);
}
Got same problem.
That`s how i solved it:
var req = new Auth.TLRequestSendCode
{
PhoneNumber = myPhone,
ApiId = ApiID,
ApiHash = ApiHash
};
var resp = await client.SendRequestAsync<Auth.TLSentCode>(req);
var phoneCodeHash = resp.PhoneCodeHash;
var isRegistered = resp.PhoneRegistered;
This is the same code as SendCodeRequestAsync (witch return only hash) but now we have access to Auth.TLSentCode.PhoneRegistered

load contacts from telegram to C#

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

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"
After about 4 hours of searching I cannot figure out this error. I am using the Windows 10 IOT Core on a RPI 3. My program is pretty basic, however I can not convert the datatype within the code to resolve the error.
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WiFiConnect
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WiFiConnect_Scenario : Page
{
MainPage rootPage;
private WiFiAdapter firstAdapter;
public ObservableCollection<WiFiNetworkDisplay> ResultCollection
{
get;
private set;
}
public WiFiConnect_Scenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
rootPage = MainPage.Current;
// RequestAccessAsync must have been called at least once by the app before using the API
// Calling it multiple times is fine but not necessary
// RequestAccessAsync must be called from the UI thread
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
}
else
{
DataContext = this;
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDevice Selector());
if (result.Count >= 1)
{
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
var button = new Button();
button.Content = string.Format("Scan Available Wifi Networks");
button.Click += Button_Click;
Buttons.Children.Add(button);
}
else
{
rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await firstAdapter.ScanAsync();
ConnectionBar.Visibility = Visibility.Collapsed;
DisplayNetworkReport(firstAdapter.NetworkReport);
}
private void DisplayNetworkReport(WiFiNetworkReport report)
{
rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
ResultCollection.Clear();
foreach (var network in report.AvailableNetworks)
{
ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter));
}
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null)
{
return;
}
// Show the connection bar
ConnectionBar.Visibility = Visibility.Visible;
// Only show the password box if needed
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
NetworkKeyInfo.Visibility = Visibility.Collapsed;
}
else
{
NetworkKeyInfo.Visibility = Visibility.Visible;
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null || firstAdapter == null)
{
rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
return;
}
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
{
reconnectionKind = WiFiReconnectionKind.Automatic;
}
WiFiConnectionResult result;
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
}
else
{
FileStream file = new FileStream("final-wordlist.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("final-wordlist.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(' ');
foreach (var item in dataArray)
{
PasswordCredential credential = line;
//string credential = line.ToString();
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
}
}
// Only the password potion of the credential need to be supplied
}
if (result.ConnectionStatus == WiFiConnectionStatus.Success)
{
rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
// refresh the webpage
webViewGrid.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
refreshBrowserButton.Visibility = Visibility.Visible;
}
else
{
rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
}
// Since a connection attempt was made, update the connectivity level displayed for each
foreach (var network in ResultCollection)
{
network.UpdateConnectivityLevel();
}
}
private void Browser_Toggle_Click(object sender, RoutedEventArgs e)
{
if (webViewGrid.Visibility == Visibility.Visible)
{
webViewGrid.Visibility = Visibility.Collapsed;
refreshBrowserButton.Visibility = Visibility.Collapsed;
toggleBrowserButton.Content = "Show Browser Control";
}
else
{
webViewGrid.Visibility = Visibility.Visible;
refreshBrowserButton.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
}
}
private void Browser_Refresh(object sender, RoutedEventArgs e)
{
webView.Refresh();
}
}
}
This worked for me. The problem was it was it need more than one var to fill it.
var credential = new PasswordCredential("Module", "Username", "Password");
Try this:
PasswordCredential credential = null;
if (!string.IsNullOrEmpty(line))
{
credential = new PasswordCredential()
{
Password = line
};
}

Add a username to Server/Client Chat in C#

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.

Categories