How to implement chat functionality in windows phone 7 - c#

I want to implement a simple online chat application in WP7.
I am using Matrix SDK to implement chat on my WP7
This is how I am trying to connect but I am not able to connect and send any messages.
Neither the events are getting fired..I am not getting any exception also..
what have I done wrong????
Please guide me
Thanks in advance
XmppClient xmppConn;
xmppConn = new XmppClient();
Jid jidUser = new Jid("username");
xmppConn.Username = jidUser.User;
xmppConn.Password = "password";
xmppConn.SetXmppDomain(jidUser.Server);
xmppConn.Uri = new System.Uri("http://server.com:7070/http-bind/",UriKind.RelativeOrAbsolute);
xmppConn.Status = "Testing on Windows Phone 7";
xmppConn.Show = Matrix.Xmpp.Show.Chat;
try
{
xmppConn.Open();
xmppConn.OnLogin += new EventHandler<Matrix.EventArgs>(xmppConn_OnLogin);
//xmppConn.OnPresence += new EventHandler<PresenceEventArgs>(xmppConn_OnPresence);
// xmpp.OnLogin += new EventHandler<Matrix.EventArgs>(xmpp_OnLogin);
}
catch
{
Console.WriteLine("Wrong login data!");
}
}
private void SendButton_Click(object sender, System.EventArgs e)
{
// loose focus to hide keyboard
this.Focus();
messages.Add(new ChatMessage()
{
Side = MessageSide.Me,
Text = TextInput.Text
});
var pm = new PresenceManager(xmppConn);
string sub_id = "xxxxxxxxx";
Jid jid = sub_id;
pm.Subscribe(jid);
xmppConn.Send(new Message(new Jid(jid), MessageType.chat, TextInput.Text));
xmppConn.OnMessage += new EventHandler<MessageEventArgs>(xmppConn_OnMessage);
TextInput.Text = "";
}

Take a look at SignalR for real time web based communications (including chat).
There is an official sample for Windows Phone 8 and also a 3rd party helper for WP7.

Before doing anything on xmpp you first need to set OnBind Event of xmmp class.
Reason: Most of the xmpp works asynchronously.When you call something like client.Open it returns immediately so you first need to wait for OnBind event.

Related

How Can Get CallbackData in current when InlineKeyboardCallbackButton clicked in telegram Bot in C#

How can I get InlineKeyboardCallbackButton clicked in telegram bot?
Here is my code : I Edited The Code
public async System.Threading.Tasks.Task<ActionResult> GetMsgAsync()
{
var req = Request.InputStream;
var responsString = new StreamReader(req).ReadToEnd();
var update = JsonConvert.DeserializeObject<Update>(responsString);
var message = update.Message;
var chat = message.Chat;
InlineKeyboardMarkup categoryInlineMarkup = new
InlineKeyboardMarkup(
new InlineKeyboardButton[][]
{
new InlineKeyboardButton[]
{
new InlineKeyboardCallbackButton("button1","callbackData")
}
}
);
await api.SendTextMessageAsync(update.Message.Chat.Id, "Please click the button", replyMarkup: categoryInlineMarkup);
if (update.Type == Telegram.Bot.Types.Enums.UpdateType.MessageUpdate)
{
// all codes just run in this block
}
if (update.Type == Telegram.Bot.Types.Enums.UpdateType.CallbackQueryUpdate)
{
// I can't get clicked button here
if (update.CallbackQuery.Data.Contains("callbackData"))
{
await api.AnswerCallbackQueryAsync(update.CallbackQuery.Id, update.CallbackQuery.Data);
}
}
}
How can I get this button clicked also in webhook method, not in console program?
Finally i find out the answer, the problem is this line of code :
var message = update.Message;
this line of code is the main problem because this line is not in try
catch block and i can't understand which line is the problem .
After this Problem, i have a suggestion for you
You can debugging your telegram bot in your personal computer without uploading any code on any host, for this purpose You can run 3 below steps ::
1- Accessing an IIS Express site from a remote computer
2- Download NGROK
3- after download ngrok you can forward telegram webhook requests to your personal computer .

How to send SMS programatically in Windows Phone 8.1(C#)

I want to send SMS programatically for that i am using below code but seems that it dontwork in 8.1
SmsComposeTask SMSCompose = new SmsComposeTask();
SMSCompose.To = "<Number to which the SMS needs to be sent";
SMSCompose.Body = "Message that needs to be sent";
SMSCompose.Show();
Is there any othey way to achive it?
public async static Task SendMessage (string phoneNumber)
{
ChatMessage msg = new ChatMessage();
msg.MessageKind = Windows.ApplicationModel.Chat.ChatMessageKind.Standard;
msg.Body = "...";
msg.Recipients.Add(phoneNumber);
ChatMessageStore cms = await ChatMessageManager.RequestStoreAsync();
cms.SendMessageAsync(msg);
}
This should send the message on Windows Phone 8.1. You may want to check if cms is not null, just in case...
You should do some searching before make a new thread. Your question is already a part in this thread. The universal app is also called windows runtime, so same solution in that threat if you want to send message or event call or send email.
You can use this for send message:
Windows.ApplicationModel.Chat.ChatMessage msg = new Windows.ApplicationModel.Chat.ChatMessage();
msg.Body = "This is body of demo message.";
msg.Recipients.Add("10086");
msg.Recipients.Add("10010");
await Windows.ApplicationModel.Chat.ChatMessageManager.ShowComposeSmsMessageAsync(msg);
Enjoy coding!
P/s: update from #Sinaesthetic , this just compose the message, it'll not send it, all user has to do is to hit the send button :)

Issues authenticating with Facebook sdk .net - blank white screen in browser

I am having issues with Authentication in my Windows Phone 7 app using Facebook SDK .net
here is the authentication part
var facebookClient = new FacebookClient();
facebookClient.AppId = FacebookAppId;
facebookClient.AppSecret = FacebookSecret;
var authUrl = facebookClient.GetLoginUrl(new
{
client_id = FacebookAppId,
client_secret = FacebookSecret,
scope = "publish_stream",
response_type = "token",
display = "touch",
redirect_uri = "https://www.facebook.com/connect/login_success.html"
});
browser.Navigate(authUrl);
So the browser screens seem to work fine, login screen shows and then the permissions screens show. When I press OK on the last permission screen I just get a white screen. In fact I have been staring at this white screen for 10mins now.
Any ideas?
Here is the Browser.Navigated event handler. I have commented where I have put breakpoints
async void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
var facebookClient = new FacebookClient(); // Put break point here to make sure the event is handled
if(facebookClient.TryParseOAuthCallbackUrl(e.Uri, out result))
{
if (result.IsSuccess) // Put break point here to check result but its never reached
{
Logging.WriteLine("Authentication was a success!");
Classes.Facebook.Instance.AccessToken = result.AccessToken;
CreateFacebookPost();
}
else
{
MessageBox.Show(string.Format("Error: {0}\nReason:{1}", result.ErrorDescription, result.ErrorReason), "Authentication Error", MessageBoxButton.OK);
Logging.WriteLine("Authentication Failed");
Logging.WriteLine(string.Format("Error: {0}\nReason:{1}", result.ErrorDescription, result.ErrorReason));
}
browser.Visibility = System.Windows.Visibility.Collapsed;
browser.Navigated -= browser_Navigated;
}
}
EDIT 1:
Just some more info. I know the authentication (from Facebooks view) is a success as I can now see the app on my Facebook. Also, if I push back on the phone to go to previous screen of the app and then go back into the facebook section it shows everything is ok and I can make posts.
EDIT 2:
Using very similar code, this works fine in a Windows Phone 8 app. I have compared the 2 and can't seen any difference.
Looks like I have found the solution. You have to set IsScriptedEnabled=True on the WebBrowser control. By default it is false.

Cancel webclient Async request

Hopefully an easy question for you all but I'm really struggling.
I've only recently started programming and have just had an app certified to the WP7 app store but noticed a bug myself that i would like to fix before making the app public.
Basically I have a search box where the user enters a chemical name and a webservice returns an image and its molecular weight. What i would like to do is cancel the webclient if the user navigates away from the page before the download is completed or if a new search is made before the previous is completed (this currently crashes the app as I believe you can only have one request at a time??)
private void searchCactus()
{
WebClient imgClient = new WebClient();
imgClient.OpenReadCompleted += new OpenReadCompletedEventHandler(imgClient_OpenReadCompleted);
WebClient mwClient = new WebClient();
mwClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mwClient_DownloadStringCompleted);
if (DeviceNetworkInformation.IsNetworkAvailable == false)
{
MessageBox.Show("No network found, please check network availability and try again");
}
else if (compoundSearchBox.Text.Contains("?"))
{
MessageBox.Show("\"?\" Not Permitted");
return;
}
else if (compoundSearchBox.Text != "")
{
progBar1.IsIndeterminate = true;
string imageuri = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/image?format=png&width=300&height=300";
string mwURI = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/mw";
imgClient.OpenReadAsync(new Uri(#imageuri), imgClient);
mwClient.DownloadStringAsync(new Uri(#mwURI), mwClient);
// //lower keyboard
this.Focus();
}
else MessageBox.Show("Enter Search Query");
}
I tried implementing the following button but it does not work
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
imgClient.CancelAsync();
mwClient.CancelAsync();
}
as "the name 'mwClient' does not exist in the current context"
I would be very grateful if anybody could provide some guidance
Just put the two clients into fields in your class.

How can I use google text to speech api in windows form?

I want to use google text to speech in my windows form application, it will read a label. I added System.Speech reference. How can it read a label with a button click event?
http://translate.google.com/translate_tts?q=testing+google+speech This is the google text to speech api, or how can I use microsoft's native text to speech?
UPDATE Google's TTS API is no longer publically available. The notes at the bottom about Microsoft's TTS are still relevant and provide equivalent functionality.
You can use Google's TTS API from your WinForm application by playing the response using a variation of this question's answer (it took me a while but I have a real solution):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += (sender, e) =>
{
if (waiting)
stop.Set();
};
}
private void ButtonClick(object sender, EventArgs e)
{
var clicked = sender as Button;
var relatedLabel = this.Controls.Find(clicked.Tag.ToString(), true).FirstOrDefault() as Label;
if (relatedLabel == null)
return;
var playThread = new Thread(() => PlayMp3FromUrl("http://translate.google.com/translate_tts?q=" + HttpUtility.UrlEncode(relatedLabel.Text)));
playThread.IsBackground = true;
playThread.Start();
}
bool waiting = false;
AutoResetEvent stop = new AutoResetEvent(false);
public void PlayMp3FromUrl(string url)
{
using (Stream ms = new MemoryStream())
{
using (Stream stream = WebRequest.Create(url)
.GetResponse().GetResponseStream())
{
byte[] buffer = new byte[32768];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
ms.Position = 0;
using (WaveStream blockAlignedStream =
new BlockAlignReductionStream(
WaveFormatConversionStream.CreatePcmStream(
new Mp3FileReader(ms))))
{
using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
waveOut.Init(blockAlignedStream);
waveOut.PlaybackStopped += (sender, e) =>
{
waveOut.Stop();
};
waveOut.Play();
waiting = true;
stop.WaitOne(10000);
waiting = false;
}
}
}
}
}
NOTE: The above code requires NAudio to work (free/open source) and using statements for System.Web, System.Threading, and NAudio.Wave.
My Form1 has 2 controls on it:
A Label named label1
A Button named button1 with a Tag of label1 (used to bind the button to its label)
The above code can be simplified slightly if a you have different events for each button/label combination using something like (untested):
private void ButtonClick(object sender, EventArgs e)
{
var clicked = sender as Button;
var playThread = new Thread(() => PlayMp3FromUrl("http://translate.google.com/translate_tts?q=" + HttpUtility.UrlEncode(label1.Text)));
playThread.IsBackground = true;
playThread.Start();
}
There are problems with this solution though (this list is probably not complete; I'm sure comments and real world usage will find others):
Notice the stop.WaitOne(10000); in the first code snippet. The 10000 represents a maximum of 10 seconds of audio to be played so it will need to be tweaked if your label takes longer than that to read. This is necessary because the current version of NAudio (v1.5.4.0) seems to have a problem determining when the stream is done playing. It may be fixed in a later version or perhaps there is a workaround that I didn't take the time to find. One temporary workaround is to use a ParameterizedThreadStart that would take the timeout as a parameter to the thread. This would allow variable timeouts but would not technically fix the problem.
More importantly, the Google TTS API is unofficial (meaning not to be consumed by non-Google applications) it is subject to change without notification at any time. If you need something that will work in a commercial environment I'd suggest either the MS TTS solution (as your question suggests) or one of the many commercial alternatives. None of which tend to be even this simple though.
To answer the other side of your question:
The System.Speech.Synthesis.SpeechSynthesizer class is much easier to use and you can count on it being available reliably (where with the Google API, it could be gone tomorrow).
It is really as easy as including a reference to the System.Speech reference and:
public void SaySomething(string somethingToSay)
{
var synth = new System.Speech.Synthesis.SpeechSynthesizer();
synth.SpeakAsync(somethingToSay);
}
This just works.
Trying to use the Google TTS API was a fun experiment but I'd be hard pressed to suggest it for production use, and if you don't want to pay for a commercial alternative, Microsoft's solution is about as good as it gets.
I know this question is a bit out of date but recently Google published Google Cloud Text To Speech API.
.NET Client version of Google.Cloud.TextToSpeech can be found here:
https://github.com/jhabjan/Google.Cloud.TextToSpeech.V1
Here is short example how to use the client:
GoogleCredential credentials =
GoogleCredential.FromFile(Path.Combine(Program.AppPath, "jhabjan-test-47a56894d458.json"));
TextToSpeechClient client = TextToSpeechClient.Create(credentials);
SynthesizeSpeechResponse response = client.SynthesizeSpeech(
new SynthesisInput()
{
Text = "Google Cloud Text-to-Speech enables developers to synthesize natural-sounding speech with 32 voices"
},
new VoiceSelectionParams()
{
LanguageCode = "en-US",
Name = "en-US-Wavenet-C"
},
new AudioConfig()
{
AudioEncoding = AudioEncoding.Mp3
}
);
string speechFile = Path.Combine(Directory.GetCurrentDirectory(), "sample.mp3");
File.WriteAllBytes(speechFile, response.AudioContent);

Categories