how to get information from user on alexa skill launch - c#

I've got an Alexa app that on first launch looks for the user's id in a dynamoDB. If it isn't there I'd like it to ask the user for their ip address.
I have an intent that can collect the IP but I was wondering if I could trigger the intent from the launch request?
private SkillResponse LaunchRequestHandler(SkillRequest input, ILambdaContext context)
{
// Initialise response
var skillResponse = new SkillResponse
{
Version = "1.0",
Response = new ResponseBody()
};
// Output speech
SsmlOutputSpeech ssmlResponse = new SsmlOutputSpeech();
try
{
try
{
var strUserId = input.Session.User.UserId;
var request = new GetItemRequest
{
TableName = tableName,
Key = new Dictionary<string, AttributeValue>() { { "strUserId", new AttributeValue { S = strUserId } } },
};
var response = client.GetItemAsync(request);
// Check the response.
var result = response.Result;
var attributeMap = result.Item;
if (result.Item.Count() < 1)
{
ssmlResponse.Ssml = "<speak></speak>";
// Trigger intent to get IP address and port number.
}
else
{
ssmlResponse.Ssml = "<speak>Hi there. I'm not Cortana.</speak>";
// Give command guidance prompt.
}
}
catch (AmazonDynamoDBException e) { ssmlResponse.Ssml = "<speak>" + e.InnerException.Message + "</speak>"; }
catch (AmazonServiceException e) { ssmlResponse.Ssml = "<speak>" + e.Message + "</speak>"; }
catch (Exception e) { ssmlResponse.Ssml = "<speak>" + e.Message + "</speak>"; }
skillResponse.Response.OutputSpeech = ssmlResponse;
skillResponse.Response.ShouldEndSession = true;
}
catch
{
//ssmlResponse.Ssml = "<speak><audio src='/samples/ImSorryDave'/></speak>";
ssmlResponse.Ssml = "<speak>I'm sorry Dave. I'm afraid I can't do that.</speak>";
skillResponse.Response.OutputSpeech = ssmlResponse;
}
skillResponse.Response.ShouldEndSession = true;
return skillResponse;
}

Two options I can think of:
Have you tried just asking for the IP address? <speak> Hi there. What is your IP address?</speak> If you make sure your IP address intent has examples of how you might expect a user to respond to that question, that intent should be the triggered and sent to your skill to process.
Also look into how Alexa can handle some of the dialog management for you with intent chaining. The example there sounds very similar to your use case.

Related

Adwords Api How to Pause Ads on Ad level

I am trying to PAUSE the Ads with the AdId and AdGroupID. I have successfully paused an AdGroup but i want to pause Ads individually. Is this possible on Adwords API. I tried the code below but It seems it only works on AdGroup level. Also checked the AdService but seems that there is no option to edit the Status.
I am using Ads.AdWords.v201809
Thanks in advance
public void googleEnableDisableAds(AdWordsUser user, long adGroupId, long AdID, AdGroupAdStatus AdStatus)
{
using (AdGroupAdService adGroupAdService =
(AdGroupAdService)user.GetService(AdWordsService.v201809.AdGroupAdService))
{
List<AdGroupAdOperation> operations = new List<AdGroupAdOperation>();
// Create the expanded text ad.
ExpandedTextAd expandedTextAd = new ExpandedTextAd
{
//CR[i].
id = AdID
};
AdGroupAd expandedTextAdGroupAd = new AdGroupAd
{
adGroupId = adGroupId,
ad = expandedTextAd,
// Optional: Set the status.
status = AdStatus
};
// Create the operation.
AdGroupAdOperation operation = new AdGroupAdOperation
{
#operator = Operator.SET,
operand = expandedTextAdGroupAd
};
operations.Add(operation);
AdGroupAdReturnValue retVal = null;
try
{
if (operations.Count > 0)
{
// Create the ads.
retVal = adGroupAdService.mutate(operations.ToArray());
// Display the results.
if (retVal != null && retVal.value != null)
{
foreach (AdGroupAd adGroupAd in retVal.value)
{
ExpandedTextAd newAd = adGroupAd.ad as ExpandedTextAd;
Console.WriteLine(
"Expanded text ad with ID '{0}' and headline '{1} - {2}' " +
"was added.", newAd.id, newAd.headlinePart1, newAd.headlinePart2);
//adGroupId
}
}
else
{
Console.WriteLine("No expanded text ads were created.");
}
}
adGroupAdService.Close();
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to create expanded text ad.", e);
}
}
}
Here is an example from API docs https://developers.google.com/adwords/api/docs/samples/csharp/basic-operations#pause-an-ad
The key idea is to set status property to PAUSED
AdGroupAdStatus status = AdGroupAdStatus.PAUSED

How to stop and re-excute methods in C#/XamarinForms?

I have a Display alert that ask if the user wants to retry syncing the data. My problem is when the user chose "Yes" my method overlaps it causes my application to crash. I there a way to for example when the user chooses yes the method execution stops and re-execute the method?
Here is my full code:
public async void FirstTimeSyncTown(string host, string database, string contact, string ipaddress)
{
try
{
syncStatus.Text = "Checking internet connection";
string apifile = "first-time-sync-town-api.php";
if (CrossConnectivity.Current.IsConnected)
{
syncStatus.Text = "Initializing first-time town sync";
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getData = conn.QueryAsync<TownTable>("SELECT * FROM tblTown WHERE Deleted != '1'");
var resultCount = getData.Result.Count;
var current_datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
int count = 1;
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
if (resultCount == 0)
{
syncStatus.Text = "Getting data from the server";
var link = "http://" + ipaddress + ":" + Constants.port + "/" + Constants.apifolder + "/api/" + apifile;
string contentType = "application/json";
JObject json = new JObject
{
{ "Host", host },
{ "Database", database }
};
HttpClient client = new HttpClient();
var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
{
try
{
var dataresult = JsonConvert.DeserializeObject<List<TownData>>(content, settings);
var datacount = dataresult.Count;
for (int i = 0; i < datacount; i++)
{
syncStatus.Text = "Syncing town " + count + " out of " + datacount;
var item = dataresult[i];
var townID = item.TownID;
var provinceID = item.ProvinceID;
var town = item.Town;
var lastsync = DateTime.Parse(current_datetime);
var lastupdated = item.LastUpdated;
var deleted = item.Deleted;
var insertdata = new TownTable
{
TownID = townID,
ProvinceID = provinceID,
Town = town,
LastSync = lastsync,
LastUpdated = lastupdated,
Deleted = deleted
};
await conn.InsertOrReplaceAsync(insertdata);
count++;
}
synccount += "Total synced town: " + count + "\n";
var logType = "App Log";
var log = "Initialized first-time sync (<b>Town</b>) <br/>" + "App Version: <b>" + Constants.appversion + "</b><br/> Device ID: <b>" + Constants.deviceID + "</b>";
int logdeleted = 0;
Save_Logs(contact, logType, log, database, logdeleted);
}
catch
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Failed to send the data.\n\n Error:\n\n" + content + "\n\n Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncTown(host, database, contact, ipaddress);
}
else
{
First_Time_Sync_Failed();
}
}
}
Preferences.Set("townchangelastcheck", current_datetime, "private_prefs");
SyncUserLogsClientUpdate(host, database, contact, ipaddress);
}
else
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Please connect to the internet to sync your data. Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncTown(host, database, contact, ipaddress);
}
else
{
First_Time_Sync_Failed();
}
}
}
else
{
SyncTownServerUpdate(host, database, contact, ipaddress);
}
}
else
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Please connect to the internet to sync your data. Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncTown(host, database, contact, ipaddress);
}
else
{
First_Time_Sync_Failed();
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
var retry = await DisplayAlert("Application Error", "Syncing failed. Failed to send the data.\n\n Error:\n\n" + ex.Message.ToString() + "\n\n Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncTown(host, database, contact, ipaddress);
}
else
{
First_Time_Sync_Failed();
};
}
}
In my case, I've used Task.Factory for executing methods in background, and also CancellationToken for cancelling executing.
Firstly, you need to create a Token parameter like so:
public CancellationTokenSource Ts { get; set; } = new CancellationTokenSource();
(I did it as public global param of the class for accessing from outside).
And when I execute the background methods, I use this lines of code:
// Get Token for Task.Factory
var ct = Ts.Token;
try
{
Task.Factory.StartNew(() =>
{
// your code for background task
...
// This is for defining whether user cancelled
// and in that place your code stops
if (ct.IsCancellationRequested)
{
// do the staff and return
return;
}
}, ct);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
}
When user click on "Cancel", I handle this event and call this:
// Call it to stop thread
yourCustomClass.Ts.Cancel();
After that you can re-execute your method. Hope it helps!

ReliableCollections Service Fabric: Statemanager's GetOrAddAsync() returns invalid queue with different names

I have two reliable queues and they are being accessed by two guest executables and each of them access their own. Sometimes the function I use to access them doesn't update the reliable queue object in the function and the wrong request is sent to the wrong guest executable.
What happens is that the clientId is passed by the guest executable to this function in the Get request. Let us say that there are two clientId(s) called T1 and T2.
What happens is that the guest executable (client) T2 at times gets the request that was meant for T1. Even though I tried line by line debugging the parameters passed to this function are correct.
Here is my API's POST that is passed a json to be added to the queue for the clients to receive from the GET
[HttpPost("MarketInfo")]
public JObject GetMarketInfo([FromBody] JObject jObject)
{
List<JToken> clients = jObject.GetValue("clients").ToList();
string json;
JObject response = new JObject();
JArray jsonArray = new JArray();
try
{
foreach (JToken client in clients)
{
var id = Guid.NewGuid();
json = "{'name':'MarketInfo','id':'" + id.ToString() + "','mtClientId':'" + terminal["name"].ToString() + "','parameters':{'symbol':'" + terminal["symbol"].ToString() + "','property':24}}";
bool result = _requestsCollectionHandler.CreateRequestForClient(JObject.Parse(json));
JObject clientResponse = new JObject();
if (result==true)
{
clientResponse["name"] = client["name"].ToString();
clientResponse["guid"] = id.ToString();
jsonArray.Add(clientResponse);
}
else
{
clientResponse["name"] = terminal.Children()["name"].ToString();
clientResponse["guid"] = "ERROR";
jsonArray.Add(terminalResponse);
}
}
response["clients"] = jsonArray;
return response;
}
catch (Exception e)
{
Debug.Write(e.Message);
return null;
}
}
This is the json that we pass to this API
{"clients":[{"name":"T1","symbol":"SomeInfo"},{"name":"T2","symbol":"SomeInfo"}]}
The problem is always with the clients object that is passed first.
Before I explain further let me also share the code for the client's HttpGet
[HttpGet("{clientId}")]
public string Get([FromRoute] string clientId)
{
try
{
string request = _requestsCollectionHandler.GetRequestJsonFromQueue(clientId);
return request;
}
catch(Exception e)
{
return e.Message;
}
}
This is the function that creates an object that is to be added by another function in the reliable queue
public bool CreateRequestForClient(JObject jObject)
{
try
{
this._jObject = new JObject(jObject);
CreateKey();
AddToRequestToQueueAsync();
return true;
}
catch (Exception e)
{
Debug.Write(e.Message);
_exceptionMessage = e.Message;
return false;
}
}
private void CreateKey()
{
dynamic data = JObject.Parse(_jObject.ToString(Newtonsoft.Json.Formatting.None));
string name = data.name;
string id = data.id;
string clientId = data.clientId;
_key.id = id;
_key.name = name;
_key.clientId = clientId;
//key.timestamp = GetTimestamp();
_key.timestamp = GetTimestamp();
_key.requestJson = _jObject.ToString(Newtonsoft.Json.Formatting.None);
}
_key is a private variable in class a custom class
This is the function in my class of request handler that adds the requests to the queue
private void AddToRequestToQueueAsync()
{
var transaction = this._stateManager.CreateTransaction();
CancellationToken cancellationToken
= new CancellationToken(false);
try
{
string queue = _key.clientId;
IReliableConcurrentQueue<TerminalResponseKey> reliableQueue =
_stateManager.GetOrAddAsync<IReliableConcurrentQueue<TerminalResponseKey>>(queue).Result;
transaction = this._stateManager.CreateTransaction();
if (reliableQueue!=null)
{
long count = reliableQueue.Count;
reliableQueue.EnqueueAsync(transaction, _key);
count = reliableQueue.Count;
transaction.CommitAsync().Wait();
}
else
{
transaction.Abort();
}
}
catch
{
transaction.Abort();
throw;
}
}
This is function that is used by the client
public string GetRequestJsonFromQueue(string clientId)
{
string queue = clientId;
try
{
IReliableConcurrentQueue<TerminalResponseKey> reliableQueue =
this._stateManager.GetOrAddAsync<IReliableConcurrentQueue<TerminalResponseKey>>(queue).Result;
if(reliableQueue != null)
{
ConditionalValue<TerminalResponseKey> key =
reliableQueue.TryDequeueAsync(transaction).Result;
if(key.HasValue)
{
string request = key.Value.requestJson;
transaction.CommitAsync().Wait();
return request;
}
}
else
{
transaction.Abort();
}
return "NO QUEUE";
}
catch (Exception e)
{
Debug.WriteLine(e);
transaction.Abort();
return e.InnerException.Message;
}
}
As far as I have found out I think my problem is in this function above. Because I don't know how the client T2 or client T1 gets another client's queue because the parameters determining the queue are their IDs and are totally unique.
These Ids are also passed correctly to this:
IReliableConcurrentQueue<TerminalResponseKey> reliableQueue =
this._stateManager.GetOrAddAsync<IReliableConcurrentQueue<TerminalResponseKey>>(queue).Result;
As you can see that we have queue=clientId
I have tried adding proper timespans but it was of no use as there is no exception thrown for OperationTimedOut. Furthermore since I am new to ServiceFabric I maybe totally doing anything wrong.
PS: Sorry for maybe a lot of jumbled up and confused code and question AND SOME OF THE INFORMATION IS OBFUSCATED DUE TO CONFIDENTIALITY BUT NOTHING OBSTRUCTING THE UNDERSTANDING OF THIS IS HIDDEN (I Hope not an issue)
I hope this is not an issue maybe an error I am overlooking at my side
When you put the request in the queue, in AddToRequestToQueueAsync(), the name of the queue is set from _key.terminalId (and I don't see where you assign it), but when you read from it, in GetRequestJsonFromQueue(), the clientId
is used as the queue name.

MailChimp Integaration with MVC 5

I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}

Bloomberg BLPAPI how get DV01 of a bond?

I'm pretty new to the BBG API and its lack of documentation. I've been trying to figure out how to get the DV01 or PV01 of a bond, but I always get an error on the fields I try. Am I missing something? Sample code below that I modified from blapi C# samples.
private void run(string[] args)
{
string serverHost = "localhost";
int serverPort = 8194;
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.ServerHost = serverHost;
sessionOptions.ServerPort = serverPort;
System.Console.WriteLine("Connecting to " + serverHost + ":" + serverPort);
Session session = new Session(sessionOptions);
bool sessionStarted = session.Start();
if (!sessionStarted)
{
System.Console.WriteLine("Failed to start session.");
return;
}
if (!session.OpenService("//blp/refdata"))
{
System.Console.Error.WriteLine("Failed to open //blp/refdata");
return;
}
Service refDataService = session.GetService("//blp/refdata");
Request request = refDataService.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement("securities");
//IBM Bond BBG004J4QNM9
securities.AppendValue("BBG004J4QNM9");
Element fields = request.GetElement("fields");
fields.AppendValue("DS002");
fields.AppendValue("MARKET_SECTOR_DES");
fields.AppendValue("SECURITY_TYP2");
fields.AppendValue("SECURITY_TYP");
fields.AppendValue("ID_EXCH_SYMBOL");
fields.AppendValue("PX_LAST");
//None of these are returned
fields.AppendValue("PV01_BID_CURRENCY_1");
fields.AppendValue("PV01_MID_CURRENCY_1");
fields.AppendValue("DV01");
fields.AppendValue("HEDGE_RATIO_10Y_TSY");
Console.WriteLine("Sending Request: " + request);
session.SendRequest(request, null);
while (true)
{
Event eventObj = session.NextEvent();
foreach (Message msg in eventObj.GetMessages())
{
Console.WriteLine(msg.AsElement);
}
if (eventObj.Type == Event.EventType.RESPONSE)
{
break;
}
}
}

Categories

Resources