Sending SMS using Twilio from my website in asp.net - asp.net

I am trying to send SMS from twilio account. Here is my code.
try
{
string ACCOUNT_SID = ConfigurationManager.AppSettings["XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"];
string AUTH_TOKEN = ConfigurationManager.AppSettings["XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"];
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
client.SendSmsMessage("+1XXXXXXXXXX", "+1XXXXXXXXXXX", "Hi");
Label1.Text = "Sent Successfully";
}
catch (Exception ex)
{
Label1.Text = "Error:"+ex.Message;
}
Running on my server, I am receiving message "Sent Successfully" but not receiving message on my phone.
I have changed the original numbers with "XXXXX".Also I have added packages for Twilio.
Please let me know if can.

Twilio evangelist here.
You might be getting an error back from the Twilio REST API when you make the call to SendSmsMessage. You can check if this is happening by grabbing the value returned from the method and seeing if the RestException property is null or not:
var result = client.SendSmsMessage("+1xxxxxxxxxx", "+1xxxxxxxxxx", "Hi");
if (result.RestException!=null)
{
//An error occured
Console.Writeline(result.RestException.Message);
}
Another option would be to use a tool like Fiddler to watch the actual HTTP request/response as it happens and see if any errors are happening.
Hope that helps.

Related

Widevine DRM Content on Exoplayer 2.0

I am trying to play Widevine encrypted content on an Android TV application using Exoplayer. I have my video URL which is served from a CDN and acquired with a ticket. I have my widevine license URL, a ticket and a auth token for the license server.
I am creating a drmSessionManager, putting the necessary headers needed by the license server as follows:
UUID drmSchemeUuid = C.WIDEVINE_UUID;
mediaDrm = FrameworkMediaDrm.newInstance(drmSchemeUuid);
static final String USER_AGENT = "user-agent";
HttpMediaDrmCallback drmCallback = new HttpMediaDrmCallback("my-license-server", new DefaultHttpDataSourceFactory(USER_AGENT));
keyRequestProperties.put("ticket-header", ticket);
keyRequestProperties.put("token-header", token);
drmCallback.setKeyRequestProperty("ticket-header", ticket);
drmCallback.setKeyRequestProperty("token-header", token);
new DefaultDrmSessionManager(drmSchemeUuid, mediaDrm, drmCallback, keyRequestProperties)
After this Exoplayer handles most of the stuff, the following breakpoints are hit.
response = callback.executeKeyRequest(uuid, (KeyRequest) request);
in class DefaultDrmSession
return executePost(dataSourceFactory, url, request.getData(), requestProperties) in HttpMediaDrmCallback
I can observe that everything is fine till this point, the URL is correct, the headers are set fine.
in the following piece of code, I can observe that the dataSpec is fine, trying to POST a request to the license server with the correct data, but when making the connection the response code returns 405.
in class : DefaultHttpDataSource
in method : public long open(DataSpec dataSpec)
this.dataSpec = dataSpec;
this.bytesRead = 0;
this.bytesSkipped = 0;
transferInitializing(dataSpec);
try {
connection = makeConnection(dataSpec);
} catch (IOException e) {
throw new HttpDataSourceException("Unable to connect to " + dataSpec.uri.toString(), e,
dataSpec, HttpDataSourceException.TYPE_OPEN);
}
try {
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
} catch (IOException e) {
closeConnectionQuietly();
throw new HttpDataSourceException("Unable to connect to " + dataSpec.uri.toString(), e,
dataSpec, HttpDataSourceException.TYPE_OPEN);
}
When using postman to make a request to the URL, a GET request returns the following body with a response code of 405.
{
"Message": "The requested resource does not support http method 'GET'." }
a POST request also returns response code 405 but returns an empty body.
In both cases the following header is also returned, which I suppose the request must be accepting GET and POST requests.
Access-Control-Allow-Methods →GET, POST
I have no access to the configuration of the DRM server, and my contacts which are responsible of the DRM server tells me that POST requests must be working fine since there are clients which have managed to get the content to play from the same DRM server.
I am quite confused at the moment and think maybe I am missing some sort of configuration in exoplayer since I am quite new to the concept of DRMs.
Any help would be greatly appreciated.
We figured out the solution. The ticket supplied for the DRM license server was wrong. This works as it is supposed to now and the content is getting played. Just in case anyone somehow gets the same problem or is in need of a basic Widevine content playing code, this works fine at the moment.
Best regards.

Sending a mail or invite through asp

I'm trying to send email or invite dynamically using asp page.
I used,
Oapp = new Outlook.Application();
But the problem is when executed, the page tries to open a new outlook application and sends a mail. I want the page to use the existing or open outlook application and send a mail.
Can anyone help me???
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
As a workaround you may consider using EWS or Outlook API, see EWS Managed API, EWS, and web services in Exchange for more information.
For sending emails use System.Net.* classes for sending emails from the server-side.
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString() );
}
// Display the values in the ContentDisposition for the attachment.
ContentDisposition cd = data.ContentDisposition;
Console.WriteLine("Content disposition");
Console.WriteLine(cd.ToString());
Console.WriteLine("File {0}", cd.FileName);
Console.WriteLine("Size {0}", cd.Size);
Console.WriteLine("Creation {0}", cd.CreationDate);
Console.WriteLine("Modification {0}", cd.ModificationDate);
Console.WriteLine("Read {0}", cd.ReadDate);
Console.WriteLine("Inline {0}", cd.Inline);
Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
foreach (DictionaryEntry d in cd.Parameters)
{
Console.WriteLine("{0} = {1}", d.Key, d.Value);
}
data.Dispose();
}

Timeout error for AWS SNSClient Publish request

Here is the piece of code :
//Publishing the topic
snsClient.Publish(new PublishRequest
{
Subject = Constants.SNSTopicMessage,
Message = snsMessageObj.ToString(),
TopicArn = Settings.TopicArn
});
I am getting the below error :
The underlying connection was closed: A connection that was expected
to be kept alive was closed by the server.
And here is the screenshot of detailed error:
But not able to get an idea how to solve this. Any hint or link will helpful.
We had the exact same issue happen to us. We got this error about 40 times a day, which was less than 0.1% of the successful push notifications we sent out.
Our solution? Update the AWSSDK NuGet package from 1.5.30.1 to 2.3.52.0 (the latest v2 release for ease-of-upgrade). As soon as we updated, the errors stopped happening. I looked through lots of release notes and couldn't find anything specifically mentioning this issue. We have no idea why the update worked, but it did.
I hope this helps you and anyone else fix this issue.
This problem may occur when one or more of the following conditions are true:
• A network outage occurs.
• A proxy server blocks the HTTP request.
• A Domain Name System (DNS) problem occurs.
• A network authentication problem occurs.
[https://nilangshah.wordpress.com/2007/03/01/the-underlying-connection-was-closed-unable-to-connect-to-the-remote-server/]1
make sure your payloads size should not exceed more than 256 kb
make sure you had configured timeout property of the PutObjectRequest
Take a look sample aws sns request code (from https://stackoverflow.com/a/13016803/2318852)
// Create topic
string topicArn = client.CreateTopic(new CreateTopicRequest
{
Name = topicName
}).CreateTopicResult.TopicArn;
// Set display name to a friendly value
client.SetTopicAttributes(new SetTopicAttributesRequest
{
TopicArn = topicArn,
AttributeName = "DisplayName",
AttributeValue = "StackOverflow Sample Notifications"
});
// Subscribe an endpoint - in this case, an email address
client.Subscribe(new SubscribeRequest
{
TopicArn = topicArn,
Protocol = "email",
Endpoint = "sample#example.com"
});
// When using email, recipient must confirm subscription
Console.WriteLine("Please check your email and press enter when you are subscribed...");
Console.ReadLine();
// Publish message
client.Publish(new PublishRequest
{
Subject = "Test",
Message = "Testing testing 1 2 3",
TopicArn = topicArn
});
// Verify email receieved
Console.WriteLine("Please check your email and press enter when you receive the message...");
Console.ReadLine();
// Delete topic
client.DeleteTopic(new DeleteTopicRequest
{
TopicArn = topicArn
});

Worklight 6.2 - Broadcast notification not being sent

We are trying to run the sample app for push notifications with some modification to get it to send out a broadcast notification, but it is not getting sent.
We have modified the PushBackendEmulator code as well. The emulator invokes the submitBroadCastNotification procedure successfully and the following result is returned:
Server response :: /-secure-{"result":"Notification sent to all
users","isSuccessful":true}/
However, it appears the WL.Server.sendMessage method is not sending the message and returns. I am not able to see the server side logs either after a thorough search on the liberty server except for the messages.log on the liberty server which shows the following when WL.Server.sendMessage is called.
ht.integration.js.JavaScriptIntegrationLibraryImplementation E
FWLSE0227E: Failed to send notification. Reason: FPWSE0009E: Internal
server error. No devices found [project worklight]
Here is the adapter code:
function submitBroadcastNotification( notificationText) {
var notification = {};
notification.message = {};
notification.message.alert = notificationText;
//notification.target = {};
//notification.target.tagNames = ['test'];
WL.Logger.debug("broadcast: " + notification.message.alert );
var delayTimeOut = **WL.Server.sendMessage**("PushNotificationsApp", notification);
WL.Logger.debug("Return value from WL.Server.sendMessage :"+ delayTimeOut);
return {
result : "Notification sent to all users"
};
}
Here is the PushBackendEmulator code:
public static void main(String [] args){
String serverUrl =
"http://208.124.245.78:9080/worklight";
String notificationText = "Hellofrombroadcastingnotifications";
String userId = "admin";
notificationText = notificationText.replace(" ", "%20");
Logger.debug("sending broadcast notification: " + notificationText);
URL url = new URL(serverUrl
+ "/invoke?
adapter=PushAdapter&procedure=submitBroadcastNotification&parameters=['" + userId + "','" + notificationText + "']");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.setDoOutput(true);
Logger.debug("Connected to server");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = "";
String inputLine;
while ((inputLine = in.readLine()) != null)
response+= inputLine;
Logger.debug("response is:"+ response);
in.close();
Logger.debug("Server response :: " + response);
connection.disconnect();
Looking at your application from the PMR, it seems to me like you have mixed both event source-based notifications and broadcast notifications.
If you want to use Broadcast notifications, this means you cannot try imposing sending the notification to any specific userId, etc as it is not needed nor based on userIds.
By default, all devices are auto-subscribed to a tag called "push.ALL".
You can read more about broadcast notifications API methods in the IBM Worklight Knowledge Center.
This is a modified version of your application, tested in iOS and Android: https://www.dropbox.com/s/l2yk2pbvykrzfoh/broadcastNotificationsTest.zip?dl=0
Basically, I stripped away from it anything not related to broadcast notifications:
I removed the push securitytest from application-descriptor.xml
I removed any function from the adapter XML and JS files and main.js file that is related to event source-based notifications.
The end result is that after the app is loaded, you are right inside the application (no login).
I then right-clicked the adapter folder in Studio > invoke procedure, and selected the submitBroadcastNotification option to send the notification ("aaa").
In the device, a notification was received. Tapping it (if the app is closed) launches the application, which then triggers the WL.Client.Push.onMessage API in common\js\main.js to display alerts containing the payload and props of the received notification.
This was tested in both iOS and Android.
As the application was loading, I could see in LogCat and Xcode console the token registration.
To test this in iOS, you will need to update application-descriptor.xml with your own pushSender password and add your own apns-certificatae-sandbox.p12 file.
To test in Android, make sure you are have generated a browser key in the GCM console and are using it in application-descriptor.xml
For both, make sure that all requires ports and addresses and accessible in your network

Difficulty confirming Instant Payment Notification (IPN) from Paypal within an MVC3 Application

I am trying to get Paypal's IPN service working within my app.
When I use the Paypal Sandbox IPN Simulator set to the transaction type of, "Web Accept," Paypal says the message went through just fine (and if I mess up the code in my Action that handles the IPN, Paypal says there was a server error, so this seems to be communicating correctly).
However, it doesn't appear to actually be doing anything. If I navigate to my IPN action in a browser myapp.com/Paypal/IPN, I receive a response from paypal that says INVALID (as expected) and this is written to my output via Debug.Write. When I click "Send IPN" in Paypal's simulator, I get no debug messages at all, although my IPN action is full of Debug.Write lines. (Do calls made from outside your local environment simply not allow Debug.Write output?)
For reference, here is the majority of my IPN Action (I've removed various logic for clarity's sake):
public ActionResult IPN()
{
Debug.Write("entering ipn action ");
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
Debug.Write("IPN Response received: " + response + " <-- That was response. . . ");
if (response == "VALID")
{
Debug.Write("Response Was Verified");
}
else
{
Debug.Write("RESPONSE WAS NOT VERIFIED");
}
return this.View();
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox
? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}
Am I correct in understanding that if Paypal is actually submitting a request to my IPN action, I should receive the Debug.Write messages the same as when I visit the IPN action within my browser?
It does not appear to me that anything actually happens when Paypal sends the IPN simulated message to my web application, but Paypal says things are ok and Paypal somehow knows if I intentionally make the IPN action have an error when it is caused (so it appears to actually be calling the action somehow).
Can anyone help me understand what I am not understanding here?
I just want my user's to be able to pay using Paypal's standard payment method with a 'buy now' button and be able to change a database value from false to 'true' when the payment is confirmed to have been received.
Thank you for your time.
Note: Another way I tested this was to have the action change something in my database if it was called (I simply did something like MyEntity.Value = new value then db.SaveAll();. This change to my database was made if I navigated directly to the action within my browser, but no change occurs when I had the paypal IPN simulator 'ping' the action.
Update:
Ok, running trace using trace.axd:
<trace enabled="true" requestLimit="100" pageOutput="false" traceMode="SortByTime" localOnly="false" />
It behaves as if nothing happens when I run the Paypal IPN Simulator or if I browse to my web page using a device that is off my local network.
Note that I do see details change when I visit the pages on my local computer:
8 7/8/2012 6:25:01 PM paypal/ipn 200 GET View Details
9 7/8/2012 6:25:02 PM paypal/themes/ui-lightness/jquery-ui-1.8.19.custom.css 404 GET View Details
10 7/8/2012 6:25:02 PM favicon.ico 404 GET View Details
11 7/8/2012 6:25:52 PM favicon.ico 404 GET View Details
12 7/8/2012 6:26:09 PM home/paypaltest 200 GET View Details
Update 2:
I got the debugger to start debugging by attaching the debugger to : w3wp.exe
It appears that Paypal is indeed making it to my page and responding with VERIFIED at this point when I use the IPN simulator. Not sure what this means for me. Will update.
Update 3:
With debugging working I was able to properly test everything and the IPN verification was actually working as intended - I just couldn't tell without proper debugging messages.
Thank you for your time.
With debugging working I was able to properly test everything and the IPN verification was actually working as intended - I just couldn't tell without proper debugging messages.
Thank you for your time.

Resources