Twilio StatusCallback not working: - c#

So I'm building an app with twilio voice, and I've got all the phonecall stuff working. But I'm having a little trouble understanding which parameters my callback should have.
I've registered the URL as described in the docs:
options.From = formatPhoneNumber(callout.callback_number);
options.To = formatPhoneNumber(offer.employee_phone_number);
options.Url = TwilioCallBotController.TwilioCalloutScriptURL;
options.StatusCallback = TwilioCallBotController.StatusCallbackURL;
options.StatusCallbackEvents = new []{"initiated", "ringing", "answered", "completed" };
options.StatusCallbackMethod = "POST";
I've also made a callback method here, but I'm not having much luck finding out how the parameters are supposed to work with their API. I'm kindof at a loss as to what could be the reason behind this one not working:
[HttpPost]
public ActionResult TwilioStatusCallback()
{
var twiml = new Twilio.TwiML.TwilioResponse();
twiml.Say("This is a test");
string CallSid = Request.Form["CallSid"];
string CallStatus = Request.Form["CallStatus"];
Debug.WriteLine("Status Callback Delivered");
Shift_Offer shoffer = db.Shift_Offers.Where(s => s.twillio_sid == CallSid).ToList()[0];
shoffer.status = CallStatus.ToString();// + DateTime.Now.ToString();
return TwiML(twiml);
}
Edit:
So it turns out that the API is very sensitive about the method signature (the call was previously throwing a method not found exception in a number of microsoft DLLs, including System.Web and System.Web.Mvc.
So I've actually gotten the software to call the method by using an empty method signature (no parameters).
However I'm still having trouble getting the parameters from the HTTPPOST
Edit: So upon further investigation I've managed to inspect the Request. The values I'm after exist in Request.Form["foo"], but they don't seem to be getting put into the two strings I have declared. I've removed the ["HttpPost"] attribute to try to troubleshoot the issue, but I'm really at a loss as to why I can see the values in the debugger, but they're not translating into memory.
public ActionResult TwilioStatusCallback()
{
var twiml = new Twilio.TwiML.TwilioResponse();
string sid = Request.Form["CallSid"];
string status = Request.Form["CallStatus"];
Shift_Offer shoffer = db.Shift_Offers.Where(s => s.twillio_sid == sid).ToList()[0];
shoffer.status = status;// + DateTime.Now.ToString();
return TwiML(twiml);
}

Last issue was that the database wasn't being saved.
Just added a db.SaveChanges() and we're good.

Related

C# ASP.Net Errors on form submission

I was hoping to get some insight on the error that are produced by the system. I am using a already built message system that I got some time ago and it works but sometimes on the forms I will get errors that I do not understand. For instance on a Create I have a try / catch block that produces a message if it has successfully Executed. I have tried to search for these errors in my project and it does not come up with anything. Even if it was in meta data a search should find it.
I use System.Text.StringBuilder sb = new System.Text.StringBuilder(); for the message and the code looks like this:
public ActionResult Create(Vendors model)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
//var getdata = ExtendedViewModels.VendorToEntity(model);
model.VendorId = Guid.NewGuid();
model.CreatedDate = System.DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Status = true;
db.Vendors.Add(model);
db.SaveChanges();
sb.Append("Submitted");
return Content(sb.ToString());
}
else
{
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
}
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
When this returns or closes the Modal it produces a message or if there is an error it will produce that so you can fix it like a Required field. If everything is okay it will produce from this:
#Html.StarkAjaxFormSubmiter("frmVendors", "tbVendors", true, "Action Successfully Executed")
This is a green box that shows up as "Action Successfully Executed". If something is wrong a red box shows up and you get a message. In my case I am getting a red box that says Submitted Read Warnings Alerts This is how it is spelled. I doubt this is a error that comes from ASP.Net it looks more like a custom message, I dont know what it means and I cannot find it anywhere. Regardless, it does create the record in the db. The other error I have gotten shows Something is went wrong [object, object] Not only do I want to find out what these mean, I also want to clean them up and give a proper message that makes sense. Does anyone have any ideas as to how to correct this? Could they be encypted in the custom package that was written for this? That is why I cannot find them. I have also viewed the package and did not find anything for this.
This is from Meta data:
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage);
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
//
// AfterSuccessCode:
// Add other JQuery code if you want
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage, string AfterSuccessCode);
Thanks for our help
UPDATE:
I did some searching on the web and found a program called JetBrains dotPeek. I decompiled the dll and sure enough the messages are in there. So I should be able to change them and recompile it and add if I want, to it.
I was not able to edit the decompiled dll. So I decided to just create a class in the main project and copy the the code to that class. Changing what I needed. Where my trouble was, was with misspellings. The dll used Sumitted as the sb.Append("Sumitted") I changed that in the controller to be Submitted. So the dll did not find "Sumitted" in the action, and in the dll class there is an If statement that faults to error if not found - which was listed as Read Warnings Error. I changed that and fixed all the misspellings. I also got rid of the Something is went wrong and changed it to something more meaningful. I will continue to add to this to give more meaningful messages. It helps to know what the error is, instead of [object], [object]. I dont know if this will help others, maybe if they have downloaded the same code I have and have issues.

How to make a POST method for an image?

So I've been working on this API and I didn't have issues until now when I tried figuring out how to make a POST method that takes an image as a parameter. In theory, this is how it should work:
From a web page, you will upload an image and then using the route to the API, the image information will be sent to the database like this:
Now, I've been searching for an answer to this on different several pages but none of them actually helped. In fact, the only guides that I've found were about integrating that method into a Web Api (see https://www.c-sharpcorner.com/article/uploading-image-to-server-using-web-api-2-0/) but this doesn't really work for me as I can't inherit some of the methods in my solution. For example, using the link above, I had issues with HttpContext.Current, and I would guess that is because of the solution that I am currently using. However, that's another question to be asked.
So my methods look pretty much like this:
public class RecipeController : Controller
{
private readonly Func<SqlConnection> _connFactory;
public RecipeController(Func<SqlConnection> connFactory)
{
_connFactory = connFactory;
}
[Route("v1/recipe/{recipeBy}")]
[HttpGet()]
public List<Recipe> GetRecipes(string recipeBy)
{
using (var con = _connFactory())
{
con.Open();
return con.Query<Recipe>("SELECT * FROM dbo.Recipe WHERE RecipeBy = #recipeBy", new { recipeBy }).ToList();
}
}
....
I am using Dapper to pass the values to the database.
Therefore, my question is: How can I write a POST method that takes an uploaded image as a parameter and then passes it to the database? I do realize that this question is pretty vague, as I didn't even provide reproducible code. The thing is, until now I didn't even figure out a correct way to start working on, so I couldn't really provide any useful code that you can help me with. Any tips, hints, advice, tutorials... Anything is welcome!
You can accomplish this by using the Html5 FileReader class to read the image to a string on the client-side and then post this to the api end-point:
function UploadImage()
{
var file = input[0].files[0];
var reader = new FileReader();
reader.onloadend = function () {
var imageDataString = reader.result;
// post the fileString value to your api here
}
if (file) {
reader.readAsDataURL(file);
}
}
Then on your Controller you would convert the Base64String into a byte[] and store it in your db:
if (imageDataString != null && imageDataString != String.Empty)
{
string imageDataParsed = imageDataString.Substring(imageDataString.IndexOf(',') + 1);
byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
}

Making a security definition request to FIX adapter

I am trying to make a request (Security Definition Request) to FIX Adapter using the following method. This is an application level call and I manually invoke this method whenever there is a successful connection to FIX Adapter.
WHen i run this method i get a "Field not found for tag:49" exception message. However SecurityDefinitionRequest class doesnt allow me to set Tag 49 (SenderCompId) to it.
First of all is this the right way to make a SecurityDefinitionRequest? I tried looking at QuickFix/N docs but they dont explain how to make such request.
http://quickfixn.org/tutorial/sending-messages.html
Infact i havent seen any articles so far in the internet. Any suggestions?
public void ToApp(Message message, SessionID sessionId)
{
var request =
new SecurityDefinitionRequest()
{
SecurityReqID = new SecurityReqID("1"),
SecurityID = new SecurityID("5"),
SecurityRequestType = new SecurityRequestType(3),
SecurityType = new SecurityType("FUT")
};
request.SetField(new SenderCompID("217"));
Session.SendToTarget(request);
}
The constructed message looks like this
8=FIX.4.29=3735=c48=549=217167=FUT320=1321=310=003
I'm going to suggest:
SessionId currentSessionId = new QuickFix.SessionID("FIX4.2", "217","CBOE");
securityDefinitionRequest.SetSessionID(currentSessionId );

Posting a tweet C#

I am trying to post a tweet with TweetSharp library but a StackOverflowException is thrown. I couldn't solve this problem. What should I do? The error occurs in this line:
servis.SendTweet(new SendTweetOptions { Status = textBox1.Text });
Break it down and step through in the debugger (put a break-point on the string status = ... line):
// if you don't get this far, the problem is elsewhere
// if it fails here, the problem is accessing the textbox value
string status = textBox1.Text;
// if it fails here, the problem is inside the tweetsharp library,
// and should be referred to the library authors, but indicating which
// step fails (constructor vs Status property vs Send method)
var msg = new SendTweetOptions();
msg.Status = status;
servis.SendTweet(msg);

Webservice.asmx not receiving parameters with POST/SOAP requests

I am trying to send data to a C# (actually Mono) webservice from a PHP environment. Oddly, the webservice works correctly when I call it with a browser URL (i.e. with the GET method).
However, calling it from my PHP script shows that no parameter is received on Mono's side.
Here is my PHP call:
$domoWSHeader->setAuthenticatedToken($resultAuthentification->AuthentificationResult);
$inputHeaders = new SoapHeader("http://tempuri.org/domo", "DomoWSHeader", $domoWSHeader, false);
$result = $soapClient->__soapCall("MyWebServiceMethod", array("idLight"=>$uuid), NULL, $inputHeaders);
And the Webservices.asmx looks like:
namespace domo
{
public class DomoWSHeader : System.Web.Services.Protocols.SoapHeader
{
public string username;
public string password;
public string authenticatedToken;
}
[WebMethod]
public bool MyWebServiceMethod(int idLight)
{
bool success = false;
//Snip
return success;
}
}
What have I tried?
Trying to declare [System.Web.Services.Protocols.SoapHeader("DomoWSHeader")] before the method didn't change the behaviour.
I also tried to edit the web.config file to add protocols in it. I am totally new to the C# world, and I am not sure where to find answers to this problem. I hope one of you can help me understand what happens here.
Found the origin of the problem from PHP.NET : http://php.net/manual/fr/soapclient.soapcall.php#110390
In the PHP code, the parameters in the "__soapCall()" method were :
$parameters = array("idLight" => $uuid);
but it's correct when you use them to call the webservice method directly as :
$soapClient->NameOfTheMethod($parameters);
In my case, i'd need to call the webservice method with "__soapCall()" because i use headers for authentication, and the PHP.NET documentation says that we must encapsulate the array of parameters into another array like this :
$soapClient->__soapCall("NameOfTheMethod", array($parameters), NULL, $inputHeaders);
(Note that the 3rd and the 4th parameters in the "__soapCall()" method are optionals but i use them)
Hope this help :)

Categories

Resources