Hi I am developing a chatbot on amazon lex and I want to send a response card using the lambda function but on using response card function inside the close response format it gives the error of null exception. Can anyone tell the solution to it?
PS I am using FlowerOrder blueprint created by Nikki.
if (slots[greet] != null)
{
var validateGreet = ValidateUserGreeting(slots[greet]);
if (validateGreet.IsValid)
{
return Close(sessionAttributes,
"Fulfilled",
new LexResponse.LexMessage
{
ContentType = "PlainText",
Content = String.Format("Hello Kindly choose one option")
},
new LexResponse.LexResponseCard
{
Version = 1,
ContentType = "application/vnd.amazonaws.card.generic",
GenericAttachments =
{
new LexResponse.LexGenericAttachments
{
Buttons =
{
new LexResponse.LexButton
{
Text = "Shop Now",
Value = "Shop Now"
}
},
AttachmentLinkUrl = null,
Title = "Shopping",
SubTitle = "Sub Shopping",
ImageUrl = null
}
}
}
);
}
Exception:-
2020-06-09 17:31:20: Object reference not set to an instance of an object.: NullReferenceException at EVS_Test_Abbar_Lambda_Function.OrderWatchIntentProcessorTest.Process(LexEvent lexEvent, ILambdaContext context) in D:\AWS Project\Abbrar Projects\EVS_Test_Abbar_Lambda_Function\EVS_Test_Abbar_Lambda_Function\OrderWatchIntentProcessorTest.cs:line 52 at EVS_Test_Abbar_Lambda_Function.Function.FunctionHandler(LexEvent lexEvent, ILambdaContext context) in D:\AWS Project\Abbrar Projects\EVS_Test_Abbar_Lambda_Function\EVS_Test_Abbar_Lambda_Function\Function.cs:line 43
at lambda_method(Closure , Stream , Stream , LambdaContextInternal )
Here is the solution to it since if you look at the structure of JSON it contains many models and lists and each has to be handled separately.
LexResponse.LexResponseCard lexResponseCard = new LexResponse.LexResponseCard();
List<LexResponse.LexGenericAttachments> ListlexGenericAttachments = new List<LexResponse.LexGenericAttachments>();
LexResponse.LexGenericAttachments lexGenericAttachments = new LexResponse.LexGenericAttachments();
List<LexResponse.LexButton> ListlexButton = new List<LexResponse.LexButton>();
LexResponse.LexButton lexButton = new LexResponse.LexButton();
lexButton.Text = "Yes Now";
lexButton.Value = "Yes";
ListlexButton.Add(lexButton);
lexGenericAttachments.AttachmentLinkUrl = "Link";
//lexGenericAttachments.AttachmentLinkUrl = null;
lexGenericAttachments.Title = "Shopping";
lexGenericAttachments.SubTitle = "Sub Shopping";
lexGenericAttachments.ImageUrl = "Link";
//lexGenericAttachments.ImageUrl = null;
lexGenericAttachments.Buttons = ListlexButton;
ListlexGenericAttachments.Add(lexGenericAttachments);
lexResponseCard.Version = 0;
lexResponseCard.ContentType = "application/vnd.amazonaws.card.generic";
lexResponseCard.GenericAttachments = ListlexGenericAttachments;
return Close(sessionAttributes,
"Fulfilled",
new LexResponse.LexMessage
{
ContentType = "PlainText",
Content = String.Format("Hello Kindly choose one option")
},
lexResponseCard
);
It may be your capitalization of key names. For example you have ContentType but it should be contentType as camelcase beginning with lowercase letters.
return Close(sessionAttributes,
"Fulfilled",
new LexResponse.LexMessage
{
contentType = "PlainText",
content = String.Format("Hello Kindly choose one option")
},
new LexResponse.LexResponseCard
{
version = 1,
contentType = "application/vnd.amazonaws.card.generic",
GenericAttachments =
{
new LexResponse.LexGenericAttachments
{
Buttons =
{
new LexResponse.LexButton
{
text = "Shop Now",
value = "Shop Now"
}
},
attachmentLinkUrl = null,
title = "Shopping",
subTitle = "Sub Shopping",
imageUrl = null
}
}
}
);
try just one Lex Response Card .
return Close(sessionAttributes,
"Fulfilled"
new LexResponse.LexResponseCard
{
version = 1,
contentType = "application/vnd.amazonaws.card.generic",
GenericAttachments =
{
new LexResponse.LexGenericAttachments
{
Buttons =
{
new LexResponse.LexButton
{
text = "Shop Now",
value = "Shop Now"
}
},
attachmentLinkUrl = null,
title = "Shopping",
subTitle = "Sub Shopping",
imageUrl = null
}
}
}
);
Related
I have a code that reads my Xslt templates from Resources but I have to make it reads from seperated files in root directory of application. So this is my code:
docs[0] = new DocumentReferenceType
{
ID = new IDType { Value = new Guid().ToString() },
IssueDate = new IssueDateType { Value = DateTime.Now },
DocumentType = new DocumentTypeType { Value = "xslt" },
Attachment = new AttachmentType
{
EmbeddedDocumentBinaryObject = new EmbeddedDocumentBinaryObjectType
{
filename = "customxslt.xslt",
encodingCode = "Base64",
mimeCode = "applicationxml",
format = "",
characterSetCode = "UTF-8",
Value = Encoding.UTF8.GetBytes(Properties.Resource1.XSLTFile)
}
}
};
return docs;
What should I write to "Properties.Resource1.XSLTFile" read from XSLTFile.xslt in root directory? I tried to write this:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
_filePath += #"\XSLTFile.xslt";
And I changed "Properties.Resource1.XSLTFile" with "_filePath " there but it gave me this error: "HTML conversion failed: XSLT compilation error"
i got help and i am sharing maybe there will be someone who needs it
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
_filePath += #"\xslt\earsiv.xslt";
string xs = System.IO.File.ReadAllText(_filePath);
docs[0] = new DocumentReferenceType
{
ID = new IDType { Value = new Guid().ToString() },
IssueDate = new IssueDateType { Value = DateTime.Now },
DocumentType = new DocumentTypeType { Value = "xslt" },
Attachment = new AttachmentType
{
EmbeddedDocumentBinaryObject = new EmbeddedDocumentBinaryObjectType
{
filename = "customxslt.xslt",
encodingCode = "Base64",
mimeCode = "applicationxml",
format = "",
characterSetCode = "UTF-8",
Value = Encoding.UTF8.GetBytes(xs)
}
}
};
return docs;
I am trying to display list of item on Echo show. Am using Alexa.Net.APL C# and below is what i have done so far but is not displaying i will appreciate help.
This is my method that generate Directive
private RenderDocumentDirective BuildDirective(string bg = "")
{
if (string.IsNullOrEmpty(bg))
{
bg = "https://i.ibb.co/5cWztFH/brown-on-seashore-near-mountain-1007657.jpg";
}
var mainLayout = new Layout(
new AlexaTextList
{
BackgroundImageSource = bg,
HeaderTitle = "Alexa text list header title",
HeaderSubtitle = "sub",
HeaderDivider = true,
BackgroundScale = new APLValue<Scale>(Scale.BestFill),
BackgroundAlign = new APLValue<string>("center"),
BackgroundColor = new APLValue<string>("transparent"),
ListItems = new APLValue<List<AlexaTextListItem>>()
{
Value = new List<AlexaTextListItem>
{
new AlexaTextListItem
{
PrimaryText = "Hello world! 1"
},
new AlexaTextListItem
{
PrimaryText = "Hello world! 2"
},
new AlexaTextListItem
{
PrimaryText = "Hello world! 3"
}
}
}
}
);
var renderDocument = new RenderDocumentDirective
{
Token = "randomToken",
Document = new APLDocument
{
MainTemplate = mainLayout
},
};
return renderDocument;
}
Here is where am calling it
var response = ResponseBuilder.Ask(d, rp, session);
var dr = BuildDirective();
response.Response.Directives.Add(dr);
return response;
I am trying to use AWS SDK for .NET Core.
Create a table to count views on videos.
Add a view count for a day.
Increment existing count for a day.
Query for video counts between two dates for a video.
.NET Core AWS SDK uses Async methods which are not documented in AWS. There is a feature request on their github page for this to happen.... but it is dated from last year. (https://github.com/aws/aws-sdk-net/issues/787)
CREATE THE TABLE
This works and creates a table on the AWS Console.
var ctRequest = new CreateTableRequest
{
AttributeDefinitions = new List<AttributeDefinition>()
{
new AttributeDefinition
{
AttributeName = "ViewUid",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "ViewDate",
AttributeType = ScalarAttributeType.S
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "ViewUid",
KeyType = KeyType.HASH //Partition key
},
new KeySchemaElement
{
AttributeName = "ViewDate",
KeyType = KeyType.RANGE
}
},
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 6
},
TableName = _settings.AWSDynamoDBViewCountTable
};
var response = _client.CreateTableAsync(ctRequest).Result;
UPDATE AND ITEM WITH AUTO-INCREMENT A FIELD
This, sadly, is where i hit issues. The old docs are found here under the Atomic Counter section. (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html)
Invalid ConditionExpression: Syntax error; token: \"SET\", near: \"SET
VC\"
var viewData = new Document();
viewData["ViewUid"] = videoUid; //Table entry UID
viewData["VideoId"] = videoId; // Video ID
viewData["ViewDate"] = date;
viewData["ViewCount"] = 0;
//Document result = await _viewCountTable.PutItemAsync(viewData);
Expression expr = new Expression();
expr.ExpressionStatement = "SET #VC = #VC + :val";
expr.ExpressionAttributeValues[":val"] = 1;
expr.ExpressionAttributeNames["#VC"] = "ViewCount";
var updateConfig = new UpdateItemOperationConfig() {
ConditionalExpression = expr,
ReturnValues = ReturnValues.UpdatedNewAttributes
};
var result = await _viewCountTable.UpdateItemAsync(viewData, updateConfig);
return result;
QUERY FOR DATE RANGE
Get one video's view count for a date range.
string queryTimeSpanStartString = dateFrom.ToString(AWSSDKUtils.ISO8601DateFormat);
string queryTimeSpanEndString = dateTo.ToString(AWSSDKUtils.ISO8601DateFormat);
var request = new QueryRequest
{
TableName = _settings.AWSDynamoDBViewCountTable,
KeyConditions = new Dictionary<string, Condition>()
{
{
"VideoId", new Condition()
{
ComparisonOperator = "EQ",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = videoId }
}
}
},
{
"ViewDate",
new Condition
{
ComparisonOperator = "BETWEEN",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = queryTimeSpanStartString },
new AttributeValue { S = queryTimeSpanEndString }
}
}
}
}
};
var response = await _client.QueryAsync(request);
Any help would be appreciated.
I was able to update the ViewCount with the following code:
string tableName = "videos";
var request = new UpdateItemRequest
{
Key = new Dictionary<string, AttributeValue>() { { "ViewUid", new AttributeValue { S = "replaceVideoIdhere" } } },
ExpressionAttributeNames = new Dictionary<string, string>()
{
{"#Q", "ViewCount"}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{":incr", new AttributeValue {N = "1"}}
},
UpdateExpression = "SET #Q = #Q + :incr",
TableName = tableName
};
var response = await _dynamoDbClient.UpdateItemAsync(request);
I created a table called "videos" with a partition key named "ViewUid" as string. Let me know if this works for you.
I am trying to use filter with search query. Search requset works correctly without filter. But using filter I get 400 error as response.
This is type mapping:
var mapp = new
{
mappings = new
{
posts = new
{
properties = new
{
FullText = new
{
type = "string",
analyzer = "russian"
},
Title = new
{
type = "string",
analyzer = "russian"
},
PostPubDate = new
{
type = "date"
},
Link = new
{
type = "string",
index = "not_analyzed"
},
RubricsIds = new
{
type = "integer"
},
ObjectsIds = new
{
type = "integer"
},
SourceId = new
{
type = "integer"
}
}
}
}
};
This is a request to index with filtered query:
string url = "http://localhost:9200/neg_collector/posts/_search";
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var o = new
{
size = 20,
query = new
{
filtered = new
{
query = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
#bool = new
{
should = new
{
term = new
{
SourceId = sIds
}
}
}
}
}
}
};
request.Method = "POST";
var jsonObj = JsonConvert.SerializeObject(o);
var data = Encoding.UTF8.GetBytes(jsonObj);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
I want to use an array of integers to filter result with certain SourceId-s. But I got error 400.
What am I doing wrong? Thank you
So the problem was that this syntax was for elasticsearch 2 version (And it worked nice on another computer). Here I have ElasticSearch 5 and should use another was of filtering:
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
}
}
}
}
};
It is describerd HERE
I'm trying to send a mail chimp campaign using asp.net, actually i created successfully the campaign and i can see it through my profile but also i want to send it through my code here is my code so if any one can help!!
private static void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 0;
string campaignID = string.Empty;
// compaign Create Options
var campaignCreateOpt = new campaignCreateOptions
{
list_id = listID,
subject = "subject",
from_email = "cbx#abc.com",
from_name = "abc",
template_id = TemplateID
};
// Content
var content = new Dictionary<string, string>
{
{"html", "Lots of cool stuff here."}
};
// Conditions
var csCondition = new List<campaignSegmentCondition>();
var csC = new campaignSegmentCondition {field = "interests-" + 123, op = "all", value = ""};
csCondition.Add(csC);
// Options
var csOptions = new campaignSegmentOptions {match = "all"};
// Type Options
var typeOptions = new Dictionary<string, string>
{
{"offset-units", "days"},
{"offset-time", "0"},
{"offset-dir", "after"}
};
// Create Campaigns
var campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
campaignSendNow c=new campaignSendNow();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}