How to get sms records by subaccount - c#

I know about using the class MessageListRequest to ask for a list of SMS messages from the Twilio server. There is no Subaccount filter as a parameter when defining the request. Does anyone know how to get the message list for only those messages associated with a specific subaccount? Thanks.
I have used the subaccount credentials to get the list of messages but the result of the Twilio request is a list object with zero entries . I know there are messages in the sub account because I can see them in the Twilio dashboard for the subaccount. Can you please tell me what I am doing wrong in this code?
var aRequest = new MessageListRequest();
aRequest.From = null;
aRequest.To = null;
aRequest.DateSent = null;
GetSubAccounts();
if (mySubAccountSid != null)
{
TwilioRestClient aTwilio = new TwilioRestClient(mySubAccountSid,
mySubAccountToken);
var aResult = aTwilio.ListMessages(aRequest);
if (aResult != null)
{
foreach (var aMessage in aResult.Messages)
{
mySQLManager.UpdateSMSLogTable(aMessage, myVesselID);
Methods.WriteLog(aMessage.Sid + " " + aMessage.To + " " + aMessage.Body);
}
}
return aList;
}

The simple way, which is likely what you mean, is even if you use
your master credentials for auth, but a subaccount SID in the URL
provided for Message List Resource,
/2010-04-01/Accounts/{AccountSid}/Messages, you get the resources
for that subaccount.
The C# library has a GetAccount method that takes an account
SID and returns the Account object (representing the subaccount) for
which you should then be able to make API calls as normal.
var account = twilio.GetAccount("SUBACCOUNT_SID");
Eventually if you want to track things in a more sophisticated
manner, you may decide to use UsageRecords.
Using UsageRecords combined with Subaccounts will allow you
to build usage reports and set triggers based upon some behavior.
The two links provided above will show you how to work with each in
more detail but an example of grabbing a list of all-time usage for
sms would like this in C#:
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "ACCOUNT_SID";
string AuthToken = "AUTH_TOKEN";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var records = twilio.ListUsage("sms", null, null, null, null, null);
foreach (var record in records.UsageRecords)
{
Console.WriteLine(record.Count);
}
}
}

Related

How can I identify a user logged into DiallogFlow via webhook request?

I am using Dialogflow and would like to know if through the questions of a user to a bot it is possible to identify which user is asking this question.
Attached is a section of the code for reading the data already received.
I tried using the google documentation ('' https://developers.google.com/assistant/identity/google-sign-in#java "), but was unsuccessful.
WebhookRequest request;
using (var reader = new StreamReader(Request.Body))
{
request = jsonParser.Parse<WebhookRequest>(reader);
}
var pas = request.QueryResult.Parameters;
var queryText = request.QueryResult.QueryText;
var response = new WebhookResponse();
StringBuilder sb = new StringBuilder();
//interactionDAO.SaveInteration(new Interaction(Guid.NewGuid(), "google", queryText));
var intent = request.QueryResult.Intent.DisplayName;
var listaObjetos = await _service.DetectIntentAsync(new[] { queryText }, intent);
foreach (var item in listaObjetos)
{
var convertItem = JsonConvert.DeserializeObject<Fulfillment>(item.ToString());
if (!String.IsNullOrWhiteSpace(convertItem.FulfillmentText))
{
sb.Append(convertItem.FulfillmentText);
}
if (convertItem.Parameters != null && convertItem.Parameters.ContainsKey("date-time"))
{
sb.Append(convertItem.Parameters["date-time"]);
}
//sb.Append(item);
}
response.FulfillmentText = sb.ToString();
return Json(response);
Look for "session" in the JSON you receive in your webhook from DialogFlow, it is a unique identifier for the conversation.
Usually it has a format like this:
"session": "projects/${PROJECTID}/agent/sessions/${SESSIONID}"
Just extract the SESSIONID from the last part.
You can find more about DialogFlow Webhook JSON format here:
https://developers.google.com/assistant/actions/build/json/dialogflow-webhook-json
DialogFlow generally only identifies the session. Providing data to uniquely identify the user is part of the client and usually included in the payload.
For example, a signed in user from Google Assistant can be extracted like this (requires the System.IdentityModel.Tokens.Jwt package):
WebhookRequest request;
if (!request.OriginalDetectIntentRequest.Payload.Fields.ContainsKey("user"))
{
throw new ArgumentException("Payload does not contain user.");
}
string idToken = request.OriginalDetectIntentRequest.Payload.Fields["user"]
.StructValue.Fields["idToken"].StringValue;
var userInfo = new JwtSecurityTokenHandler().ReadJwtToken(idToken).Payload;
if (!userInfo["iss"].ToString().EndsWith("accounts.google.com")
|| !userInfo["aud"].ToString().Equals("((your_action_id))")
{
throw new SecurityException("Issuer or authentication token do not match expected value.");
}
string accountName = userInfo["email"].ToString();
if (string.IsNullOrEmpty(accountName))
{
throw new ArgumentException("Id token does not contain mail address.");
}
return accountName;
You need to configure the project as detailed in the article you already linked. It is then possible to mark any DialogFlow intent as "Sign-in required" via the Google Assistant integration settings or use the helper intent for optional sign-in (see this question for details on implementing the helper).

List of favorites using tweet sharp

I am having trouble implementing a function to get the list of favorite tweets for a given user using tweetsharp. Does anyone have suggestion on how i should go about doing this? Thanks!
[HttpGet]
public JsonResult GetTwitterFavoritesList(string oauth_token, string oauth_verifier, string screen_name)
{
try
{
var requestToken = new OAuthRequestToken { Token = oauth_token };
TwitterService service = new TwitterService(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
ListFavoriteTweetsOptions options = new ListFavoriteTweetsOptions();
options.ScreenName = screen_name;
options.MaxId = 100;
IEnumerable<TwitterStatus> favoritesList = service.ListFavoriteTweets(options);
return Json(favoritesList, JsonRequestBehavior.AllowGet);
}
catch(Exception)
{
return Json(false);
}
}
Your problem is probably the MaxId = 100. That property is used for "paging" and setting it to 100 means no tweet with an id of more than 100 will be returned. Given all current tweets are in the billions, the query won't return anything.
If you were trying to restrict the number of tweets returned, you want to use the Count property, if one exists for that method.
I resolved this issue by using the access token and access secret i got from the initial authorization. So to get favorites i did not need to do a second authorization. i saved the access token and secret and just used them again in this line
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);

Implementing 3D Secure with Sitefinity Ecommerce

I want to add 3D secure authentication to credit card payments taken through a website. I am using Sitefinity 8, the e-commerce plug-in and SagePay as the payment processor.
I have created a custom payment provider and can successfully redirect users to the 3D secure page. I am able to perform the second authentication call to SagePay using the SagePay integration kit (i.e. externally from the e-commerce plugin). However, I am struggling to find a way to complete the payment due the way the internal e-commerce classes function.
The difficulty is that the order processor treats the payment as declined if 3D secure authentication is required, but there does not seem to be a way to process the order correctly without using the inbuilt functionality. From my inspections of the ecommerce libraries, there seems to be no way to extend or modify these classes due to internal modifiers and concrete implementations.
How can I process the order once I have completed authentiation? Has anyone successfully implemented 3D secure with ecommerce? Or know if it is possible?
This is my custom payment provider at the moment.
public class CustomSagePayProvider : SagePayProvider
{
// Rest of code...
protected override IPaymentResponse ParseReponse(string uniqueTransactionCode, string responseXml)
{
var paymentResponse = base.ParseReponse(uniqueTransactionCode, responseXml);
if (Requires3DSecure(paymentResponse))
{
var responseFields = GetResponseAsDictionary(responseXml);
Set3DSecureFields(responseFields, paymentResponse);
}
return paymentResponse;
}
private bool Requires3DSecure(IPaymentResponse paymentResponse)
{
return paymentResponse.GatewayCSCResponse == "OK";
}
private void Set3DSecureFields(Dictionary<string, string> responseFields, IPaymentResponse paymentResponse)
{
var postValues = new NameValueCollection();
postValues.Add("MD", responseFields.ContainsKey("MD") ? responseFields["MD"] : string.Empty);
postValues.Add("PAReq", responseFields.ContainsKey("PAReq") ? responseFields["PAReq"] : string.Empty);
paymentResponse.GatewayRedirectUrlPostValues = postValues;
paymentResponse.GatewayRedirectUrl = responseFields.ContainsKey("ACSURL") ? responseFields["ACSURL"] : string.Empty;
}
}
And this is the 3D secure payment process using the .NET SagePay integration kit
using SagePay.IntegrationKit;
using SagePay.IntegrationKit.Messages;
// Rest of code
var sagePay = new SagePayIntegration();
IThreeDAuthRequest request = new DataObject();
request.Md = Request.Form["MD"];
request.PaRes = Request.Form["PaRes"];
sagePay.RequestQueryString = sagePay.BuildQueryString(request, ProtocolMessage.THREE_D_AUTH_REQUEST, ProtocolVersion.V_223);
sagePay.ResponseQueryString = sagePay.ProcessWebRequestToSagePay("https://test.sagepay.com/gateway/service/direct3dcallback.vsp", sagePay.RequestQueryString);
var result = sagePay.GetDirectPaymentResult(sagePay.ResponseQueryString);
if (result.Status == ResponseStatus.OK)
{
// Process order
}
I was able to add 3D secure authentication by treating the 2nd authentication call as an offsite payment and adding the IOffsitePaymentProcessorProvider interface to my payment provider class
public class CustomSagePayProvider : SagePayProvider, IOffsitePaymentProcessorProvider
{
// Triggered after payments that have been 3D Secure authenticated
public IPaymentResponse HandleOffsiteNotification(int orderNumber, HttpRequest request, PaymentMethod paymentMethod)
{
var paymentResponse = new PaymentResponse() { IsOffsitePayment = true };
var sagePay = new SagePayIntegration();
var result = sagePay.GetDirectPaymentResult(request.Params.ToString());
if (result.ThreeDSecureStatus == ThreeDSecureStatus.OK)
{
paymentResponse.IsSuccess = true;
paymentResponse.GatewayTransactionID = result.TxAuthNo.ToString();
}
return paymentResponse;
}
public IPaymentResponse HandleOffsiteReturn(int orderNumber, HttpRequest request, PaymentMethod paymentMethod)
{
throw new NotImplementedException();
}
I pass the notification url as a query string parameter in the termUrl value posted to SagePay when first requesting the authentication
(The url must be /Ecommerce/offsite-payment-notification/ to use the inbuilt offside payment notification handler).
var notificationUrl = request.Url.GetLeftPart(UriPartial.Authority) + "/Ecommerce/offsite-payment-notification/";
In the callback from SagePay after the user completes authentication, I use the SagePay integration kit to process the result of the authentication.
var sagePay = new SagePayIntegration();
IThreeDAuthRequest request = new DataObject();
request.Md = md;
request.PaRes = paRes;
sagePay.RequestQueryString = sagePay.BuildQueryString(request, ProtocolMessage.THREE_D_AUTH_REQUEST, ProtocolVersion.V_223);
sagePay.ResponseQueryString = sagePay.ProcessWebRequestToSagePay("https://test.sagepay.com/gateway/service/direct3dcallback.vsp", sagePay.RequestQueryString);
return sagePay.GetDirectPaymentResult(sagePay.ResponseQueryString);
Finally, I trigger the HandleOffsiteNotification event by posting to the url www.mysite.com/Ecommerce/offsite-payment-notification/. This marks the order as complete, updates stock levels and cleans up the user's basket. For simplicity in this example, I am using the SagePay integration kit object to build the query string and post to the url.
var sagePay = new SagePayIntegration();
var ordersManager = OrdersManager.GetManager();
var query = sagePay.ConvertSagePayMessageToNameValueCollection(ProtocolMessage.DIRECT_PAYMENT_RESULT, typeof(IDirectPaymentResult), result, ProtocolVersion.V_223);
// Required Sitefinity fields to trigger HandleOffsiteNotification in IOffsitePaymentProcessorProvider
query.Add("invoice", orderNumber.ToString());
query.Add("provider", ordersManager.Provider.Name);
var queryString = sagePay.BuildQueryString(query);
// Post 3d secure details to this site simulate an offsite payment processor response
sagePay.ProcessWebRequestToSagePay(notificationUrl, queryString);

How can I get the picture of a Facebook event using server side code?

I'm writing a web app that pulls events data from Facebook, and I can get a lot of the information using an app token, but not the picture, which requires a client token, as documented here: https://developers.facebook.com/docs/graph-api/reference/v2.2/event/picture
I want the code that grabs the event data to run automatically on a server at regular intervals, without requiring a user to log in to their Facebook account.
Is there a way I can get a client token without user intervention? If not, is there another way I can get the event picture?
This is the code I am using to get the event data, using C# and JSON.Net (This gets a list of events created by the specified user - ResortStudios):
var fb = new FacebookClient();
dynamic result = fb.Get( "oauth/access_token", new
{
client_id = "XXXXXXXXXXX",
client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXX",
grant_type = "client_credentials"
} );
var apptoken = result.access_token;
fb = new FacebookClient(apptoken);
result = fb.Get("ResortStudios/events");
JObject events = JObject.Parse(result.ToString());
JArray aEvents = (JArray)events["data"];
string s = aEvents.ToString();
List<fbEvent> lEvents = JsonConvert.DeserializeObject<List<fbEvent>>(s);
I've not tried this but something occurred to me that might work for you. Have you considered something like storing it a non-persistent data store like session state? Then, using the Facebook SDK for .NET, you create an ActionResult for UserInfo, like below. (I know this isn't directly applicable but I hoped it might get you thinking.)
//http://facebooksdk.net/docs/web/ajax-requests/
public ActionResult UserInfo()
{
var accessToken = Session["AccessToken"].ToString();
var client = new FacebookClient(accessToken);
dynamic result = client.Get("me", new { fields = "name,id" });
return Json(new
{
id = result.id,
name = result.name,
});
}

.NET C# aWeber API

Using .NET c# I need to programmatically manage / add subscribers to my lists in aWeber using the API. The process that I am tasked with will be a Windows Service that runs x # of times a day and updates the subscribers at aWeber and the lists that they are in.
So .. all of my research using the aWeber API with .NET has shown me that a signon page at aWeber must be completed in order to receive the oauth_verifier back in the callback URL.
So in summary here are my questions:
Any recommendations on how to accomplish this task using an unattended service?
Has anyone does this?
Any help is greatly appreciated.
Thanks
Emma
1) How to use Aweber .NET SDK to connect with Aweber account [Regular Account - (i.e.) Not the developer's one].
Download .NET SDK for Aweber from https://aweber.codeplex.com/
Ans :- 1) Create a developer account - Visit https://labs.aweber.com/
2) As you have successfully created the account you would see ConsumerKey, ConsumerSecret, & an AppId in your Application.
3) Then for the fist time add the following code.
string ConsumerKey = ConfigurationManager.AppSettings["AWeberConsumerKey"];
string ConsumerSecret= ConfigurationManager.AppSettings["AWeberConsumerSecret"];
Aweber.API api = new Aweber.API(ConsumerKey, ConsumerSecret);
api.CallbackUrl = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Authorize/Index";
api.get_request_token();
Response.Cookies["oauth_token"].Value = api.OAuthToken;
Response.Cookies["oauth_token_secret"].Value = api.OAuthTokenSecret;
api.authorize();
**Now create An Authorize controller in case of MVC or Authorize.aspx**
string ConsumerKey = ConfigurationManager.AppSettings["AWeberConsumerKey"];
string ConsumerSecret= ConfigurationManager.AppSettings["AWeberConsumerSecret"];
API api = new API(ConsumerKey, ConsumerSecret);
api.OAuthVerifier = Request["oauth_verifier"];
Response.Cookies["access_token"].Value = api.get_access_token();
Account account = api.getAccount();
**Now you can apply your code to create, delete... subscribers to/from the list**
When you run this code first the authorize page will appear where you need to add your Aweber regular account credentials.
Once it's verified then you'll get access to the aweber's(Customer) account.
**But you would not like the authorize page appear always whenever you run your application so you can omit it by doing the following steps.**
1. Use the PHP script provided in http://stackoverflow.com/questions/15378034/how-to-create-an-app-in-aweber
2. Run the above PHP script & you'll get the pair of accesskey & accesssecret.Copy them to your C# code (these are the permanent keys).
3. Initialize the API with this code:
string ConsumerKey = ConfigurationManager.AppSettings["AWeberConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["AWeberConsumerSecret"];
string accessKey = ConfigurationManager.AppSettings["accessKey"];
string accessSecret = ConfigurationManager.AppSettings["accessSecret"];
Aweber.API api = new Aweber.API(ConsumerKey, ConsumerSecret);
api.OAuthToken = accessKey;
api.OAuthTokenSecret = accessSecret;
Account account = api.getAccount();
**Now we'll code to create subscriber to a particular list**
int listid = int.Parse(ConfigurationManager.AppSettings["ListId"]);
foreach (List list in account.lists().entries)
{
if (list.id == listid) Your List's ID **(Mylist - xxxxxxx)**
{
foreach (Subscriber subscriber in list.subscribers().entries)
{
if (subscriber.email.Equals(objRegModel.EmailID))
{
flag = false;
break;
**Checks whether the similar subscriber exists on the list**
}
else
{
flag = true;
}
}
if (flag == true)
{
BaseCollection<Subscriber> target = list.subscribers();
SortedList<string, object> parameters = new SortedList<string, object>();
parameters.Add("email", objRegModel.EmailID);
parameters.Add("name", objRegModel.FirstName + " " + objRegModel.LastName);
Subscriber subscriber = target.create(parameters);
**This will add the subscriber to the specified list only if does not exist on that list.**
}
}
}
**To Delete a particluar subscriber from the list**
Apply the same logic till Account account = api.getAccount();
To get the EmailID,IP Address etc of the subscribers on the
list.Refer to this link https://labs.aweber.com/docs/permissions
int listid = int.Parse(ConfigurationManager.AppSettings["ListId"]);
foreach (List list in account.lists().entries)
{
if (list.id == listid)
{
foreach (Subscriber subscriber in list.subscribers().entries)
{
We Perform the check whether the email of the subscriber exists on the list or not & accordingly delete it from the list.
if (subscriber.email == eid && subscriber.status != "unconfirmed")
{
try
{
if (subscriber.delete())
{
//Response.Write("Subscriber Successfully Deleted");
}
}
catch (Exception ex)
{
}
}
}
}
}
}

Categories

Resources