SMStextmesage background service async - windows-8

The following code will work for CLICK event handler but i cant let it send automatically
async void Button_Click_1(object sender, RoutedEventArgs e)
{
SmsDevice smsDevice2 = (SmsDevice)await SmsDevice.GetDefaultAsync();
// Create a text message - Set destination number and message text
SmsTextMessage msg = new SmsTextMessage();
msg.To = "12345678";
msg.Body = "xxxx";
// Send the message asynchronously
await smsDevice2.SendMessageAsync(msg);
}
This wont work (background service)
async void DisplayToastAsync(IBackgroundTaskInstance taskInstance, ManualResetEvent manualEventWaiter)
{
SmsDevice smsDevice2 = (SmsDevice)await SmsDevice.GetDefaultAsync();
// Create a text message - Set destination number and message text
SmsTextMessage msg = new SmsTextMessage();
msg.To = "12345678";
msg.Body = "xxx";
// Send the message asynchronously
await smsDevice2.SendMessageAsync(msg);
}
Anyone know why? and how can i fix it?

I was experimenting and I found that you do need to fill in the "From" field (a copy of SmsDevice.AccountPhoneNumber).
Having said that, I still get a so called 'generic error', but at least it isn't a 'parameter error'.
If you're interested, my generic error is 0x80548212.
Also - I'm guessing you already did this (or I think you'd get a null sms device )- but you need to make the app as being able to do text messaging in the manifest.
Further info - that Generic Error was that my SIM was enabled for Data only. Once swapped out for a SIM that included SMS, the code worked fine.

Related

Azure service bus Message deserialize broken in core conversion

So, I've created a new Azure Functions project v3 and am porting over a subset of functions from v1 that was running on 4.6.2, while retiring the rest as obsolete. Unfortunately in the change from BrokeredMessage to Message due to changing from Microsoft.ServiceBus.Messaging to Microsoft.Azure.ServiceBus the following deserialization method is now failing with:
There was an error deserializing the object of type stream. The input source is not correctly formatted.
The problem is right there in the error, but Im not sure what the correct new approach is, its a bit unclear.
Serialize
public static Message CreateBrokeredMessage(object messageObject)
{
var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageObject)))
{
ContentType = "application/json",
Label = messageObject.GetType().Name
};
return message;
}
Deserialize
public static T ParseBrokeredMessage<T>(Message msg)
{
var body = msg.GetBody<Stream>();
var jsonContent = new StreamReader(body, true).ReadToEnd();
T updateMessage = JsonConvert.DeserializeObject<T>(jsonContent);
return updateMessage;
}
Object
var fileuploadmessage = new PlanFileUploadMessage()
{
PlanId = file.Plan_Id.Value,
UploadedAt = uploadTimeStamp,
UploadedBy = uploadUser,
FileHash = uploadedFileName,
FileName = file.Name,
BusinessUnitName = businessUnitName,
UploadedFileId = uploadedFile.Id
};
```
Message.GetBody<T>() is an extension method for messages sent using the legacy Service Bus SDK (WindowsAzure.ServiceBus package) where BrokeredMessage was populated with anything other than Stream. If your sender sends an array of bytes as you've showed, you should access it using Message.Body property.
In case your message is sent as a BrokeredMessage, the receiving code will need to select either of the methods based on some information to indicate how the message was originally sent.

Bot api, how i can get last message or chat history?

I want implement some functional like user send me a message and I reply to him with my (bot) latest message from chat history.
As you can see in the Telegram Bot API Documentation you can use sendMessage to send a message to the user.
When you receive a message, look for the chat or the from parameter in the JSON (depends if you want to answer to the person when it's a group chat or not). You can use the id parameter of the chat or from to send the message.
So the first parameter for your sendMessage would be chat_id=message.chat.id
You don't need the parse_mode, disable_web_page_preview and reply_markup for this example.
As you want to reply to the message of the user you may want to set the reply_to_message_id to the id of the received message.
reply_to_message_id = message.message_id
Last but not least, you want to set the text parameter. If I understand it correctly, your program will send the last received message.text to the user.
So what you want to do is, as soon as you get a message, save it.
Message oldMessage = message
And when you send the Message to the user use the old messages text property as the text.
text = oldMessage.text
Alright to sum it up here is the pseudocode of the function that will happen as soon as you receive a message:
Message oldMessage = null;
public void NewMessage(Message message){
int chat_id = message.chat.id;
int reply_to_message_id = message.message_id;
String text = "There is no old Message"; //fallback value
if(oldMessage != null){
text = oldMessage.text;
}
//Send Message in this example only has 3 parameters, and ignores the
//not used ones
SendMessage(chat_id,text,reply_to_message_id);
oldMessage = message; //store the received message for future answering
}
As you store the whole message in oldMessage you could also set the text you will send to something like this:
String text = oldMessage.from.first_name+": "+oldMessage.text;
if you simply want to reply on users message you need this function:
public void sendMsg(Message message, String text){
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try{
setButtons(sendMessage);
sendMessage(sendMessage);
}catch (TelegramApiException e){
e.printStackTrace();
}
}

What is the merchant id?

I'm having issues getting paypal integrated into my windows 8 app. I'm not sure what the "merchantId" is suppose to be, I'm assuming the terminology doesn't line up with what is on the developer portal?
In this code sample, Execute() returns false without showing any prompt:
BuyNow buyNow = new BuyNow([I've tried several ids I found from the portal])
{
UseSandbox = true,
};
ItemBuilder itemBuilder = new ItemBuilder(this.product.Name);
itemBuilder.Description(this.product.Description);
itemBuilder.Name(this.product.Name);
itemBuilder.Price((product.SalePrice ?? product.Price).ToString());
itemBuilder.Quantity(1);
itemBuilder.ID (this.product.Id.ToString());
Item item = itemBuilder.Build();
buyNow.AddItem(item);
bool buyNowResult = await buyNow.Execute();
Alright, for the next person. The 'MerchantId' refers to 'Merchant account ID' which is found on the www.sandbox.paypal.com site under Profile -> My Business Info.
I was also having issues because the string I was entering for the description was too long. Be sure to hook up to the error event to get a meaningful error message. The BuyNow object isn't populated with the error message despite it having an Error property.
buyNow.Error += (sender, e) =>
{
// e has the error
};

How to cancel HttpClient GET Web request

Is it possible to cancel HttpClient GET web request in Windows 8. I am looking for a solution to cancel my web request if the user press back key from the page. In my app i am using a static class for creating web request.
Alos i am using MVVM Light, and static viewmodels inside the app.
In the current situation, even if the user press the back button,
the vm stay alive and the call back reaches and executes in the VM.
So i am looking for a solution to cancel the request on back press.
Try this
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
await HttpGetRequest();
}
public CancellationTokenSource cts = new CancellationTokenSource();
private async Task HttpGetRequest()
{
try
{
DateTime now = DateTime.Now;
var httpClient = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, "https://itunes.apple.com/us/rss/toppaidapplications/limit=400/genre=6000/json");
var response = await httpClient.SendAsync(message, cts.Token);
System.Diagnostics.Debug.WriteLine("HTTP Get request completed. Time taken : " + (DateTime.Now - now).TotalSeconds + " seconds.");
}
catch (TaskCanceledException)
{
System.Diagnostics.Debug.WriteLine("HTTP Get request canceled.");
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
cts.Cancel();
}
The answer by #Farhan Ghumra is correct. Since we have moved to .Net 6 just like to add the following to the answer.
After you’re completely done with the CancellationTokenSource, dispose it directly E.g use cts.Dispose() (because you’ll most likely be using this with UI code and needing to share it with click event handling code, which means you wouldn’t be able to dispose of it with a using block)
More information can be found here.

Trouble Attaching File Programmatically to Email in Windows Metro App C#/XAML using Share Charm

I'm simply trying to attach a file named Document.pdf in the DocumentsLibrary to an email using the Share Charm. My code below works perfectly on the Local Machine:
private async void OnDataRequestedFiles(DataTransferManager sender, DataRequestedEventArgs e)
{
List<IStorageItem> shares = new List<IStorageItem>();
StorageFile filetoShare = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync("Document.pdf");
if (filetoShare != null)
{
shares.Add(filetoShare);
filetoShare = null;
}
if (shares != null)
{
DataPackage requestData = e.Request.Data;
requestData.Properties.Title = "Title";
requestData.Properties.Description = "Description"; // The description is optional.
requestData.SetStorageItems(shares);
shares = null;
}
else
{
e.Request.FailWithDisplayText("File not Found.");
}
}
But when I run the exact same code on a Windows Surface Tablet, I get the dreaded "There's nothing to share right now." on the right in the Charms flyout area.
Here's a little more background to help:
I'm not looking to use a File Picker...I know the exact file I'm looking for
I've enabled the Documents Library Capability in the manifest
I've added a File Type Association for pdf in the manifest
and yes, the file does exist and is in the Documents Library
an email account is properly setup in the Mail App on the surface
I can successfully send text emails from the Tablet...just not emails with attachments
Like I said, this works on my Win 8 Development Machine as expected...just not on the Surface. I'm wondering if the Surface has different file or folder permissions?
Thanks for the help...this is driving me CRAZY
I finally figured it out - the problem was that my Event Handler was async (so that I could use await to set the StorageFile variable).
I solved it by setting the StorageFile variable earlier in my code so that it was already available when the Event Handler was called.
I still have no idea why it worked on my development machine, but no on the WinRT surface...
The handler can be an async method. In this case, it is critical to use DataTransferManager. Please refer to the MSDN page specifically for this scenario. For your convenience, the code from the page is copied to here:
private void RegisterForShare()
{
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
DataRequestedEventArgs>(this.ShareStorageItemsHandler);
}
private async void ShareStorageItemsHandler(DataTransferManager sender,
DataRequestedEventArgs e)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Share StorageItems Example";
request.Data.Properties.Description = "Demonstrates how to share files.";
// Because we are making async calls in the DataRequested event handler,
// we need to get the deferral first.
DataRequestDeferral deferral = request.GetDeferral();
// Make sure we always call Complete on the deferral.
try
{
StorageFile logoFile =
await Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");
List<IStorageItem> storageItems = new List<IStorageItem>();
storageItems.Add(logoFile);
request.Data.SetStorageItems(storageItems);
}
finally
{
deferral.Complete();
}
}
It is critical to place the following statement before any async method is called:
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
You only have half a second to get the whole job done (getting the file, attaching...etc.). If the half-second deadline occurs you'll get this "driving crazy" message. Consider implementing some resumable logic and replace the message with "the attachment is being prepared please try again in a few seconds" (or else).
Your WinRT device might be just slower than your development machine. The latter just does the job before the deadline...