Devbridge Autocomplete serviceUrl not showing results - c#

Devbridge Autocomplete works with "lookup" but when I switch to serviceUrl it doesn't show the results. There are no errors and the json validates.
HTML:
<input type="text" name="currency" class="biginput" id="autocomplete" autocomplete="off">
JS:
$('#autocomplete').autocomplete({
//lookup: currencies,
serviceUrl: "http://localhost/agfg1Member/handlers/ACKeyword.ashx",
onSelect: function (suggestion) {
var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value + ' <br> <strong>Symbol:</strong> ' + suggestion.data;
$('#outputcontent').html(thehtml);
},
dataType: 'jsonp',
minChars: 2 });
Example of json from c# ashx handler
({"suggestions":[{"value":"Tuggerah","data":{"category":"Suburb","id":"3371","parentCat":"3"}},{"value":"Tuggeranong","data":{"category":"Suburb","id":"3372","parentCat":"80"}},{"value":"Tugun","data":{"category":"Suburb","id":"3373","parentCat":"33"}}]})
The brackets make it jsonp. This is JSONLINT validated without the brackets:
{
"suggestions": [
{
"value": "Tuggerah",
"data": {
"category": "Suburb",
"id": "3371",
"parentCat": "3"
}
},
{
"value": "Tuggeranong",
"data": {
"category": "Suburb",
"id": "3372",
"parentCat": "80"
}
},
{
"value": "Tugun",
"data": {
"category": "Suburb",
"id": "3373",
"parentCat": "33"
}
}
]}
And the ashx file outputs context.Response.ContentType = "application/json";
I tried adding "jsonp: 'cb'" to the source code, still nothing.
Uses jquery.1.9.1
Also, when stepping through the javascript, the var response remains undefined. I don't know what this means, but it doesn't sound good, hey?

Related

Convert name strings with diacritics into e-mail compatible format (SQL, C# or PowerAutomate)

I have a bit of experience with SQL and Power Platform/Logic Apps and am at the very beginning of learning C#.
I have a large SQL table with names (first names and last names) that are supposed to be used to create email addresses in Azure.
I want the display names of the emails to stay original, but I have to remove the German special characters äöüß and replace them with ae, oe, ue and ss and some characters with diacritics é, à etc that I need to replace with e or a etc.
Now, I'm wondering if I should create a view in SQL with two new columns that will convert the characters, or if I should create a logic app that will do all the replacements (and wrap that in a custom api) or if that would be a good project for my first azure function in C-Sharp (to be wrapped in a custom api).
I'm curious as to where in the system to handle the issue, and if there are any standard procedures available to handle this. I cannot be the first one to have exactly that problem.
A Google search gave me 20 different ways to handle it, all of which seemed a bit awkward or didn't work for me.
Thank you guys.
One of the workarounds is that this can be done directly using SQL commands itself. Below is a sample of data that I'm working on.
I tried creating another Colum called "FullName" and use CONCAT() operation to concat the FirstName and LastName.
ALTER TABLE <TABLENAME>
ADD [FullName] varchar(50);
Update <TABLENAME>
SET FullName = CONCAT(FirstName,' ',LastName);
Now I have used REPLACE() Function to replace all the required German special Characters.
UPDATE <TableName>
SET FullName = Replace(Replace(Replace(Replace(Replace(Replace(FullName,'ä','ae'),'ö','oe'),'ü','ue'),'ß','ss'),'é','e'),'à','a')
WHERE 'FullName'!='';
Now you can use the Full Name to be the Display Name while maintaining the original values in our table i.e., Firstname and LastName.
Alternatively, You can do that same using the logic apps too using Execute a SQL query (V2) action.
RESULTS:
Below is the codeview of my Logic App
{
"definition": {
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
"actions": {
"Execute_a_SQL_query_(V2)": {
"inputs": {
"body": {
"query": "select * from Table1"
},
"host": {
"connection": {
"name": "#parameters('$connections')['sql']['connectionId']"
}
},
"method": "post",
"path": "/v2/datasets/#{encodeURIComponent(encodeURIComponent('default'))},#{encodeURIComponent(encodeURIComponent('default'))}/query/sql"
},
"runAfter": {
"Execute_a_SQL_query_(V2)_3": [
"Succeeded"
]
},
"type": "ApiConnection"
},
"Execute_a_SQL_query_(V2)_2": {
"inputs": {
"body": {
"query": "Update Table1\nSET FullName = CONCAT(FirstName,' ',LastName);"
},
"host": {
"connection": {
"name": "#parameters('$connections')['sql']['connectionId']"
}
},
"method": "post",
"path": "/v2/datasets/#{encodeURIComponent(encodeURIComponent('default'))},#{encodeURIComponent(encodeURIComponent('default'))}/query/sql"
},
"runAfter": {},
"type": "ApiConnection"
},
"Execute_a_SQL_query_(V2)_3": {
"inputs": {
"body": {
"query": "UPDATE Table1\nSET FullName = Replace(Replace(Replace(Replace(Replace(Replace(FullName,'ä','ae'),'ö','oe'),'ü','ue'),'ß','ss'),'é','e'),'à','a')\nWHERE 'FullName'!='';"
},
"host": {
"connection": {
"name": "#parameters('$connections')['sql']['connectionId']"
}
},
"method": "post",
"path": "/v2/datasets/#{encodeURIComponent(encodeURIComponent('default'))},#{encodeURIComponent(encodeURIComponent('default'))}/query/sql"
},
"runAfter": {
"Execute_a_SQL_query_(V2)_2": [
"Succeeded"
]
},
"type": "ApiConnection"
}
},
"contentVersion": "1.0.0.0",
"outputs": {},
"parameters": {
"$connections": {
"defaultValue": {},
"type": "Object"
}
},
"triggers": {
"manual": {
"inputs": {
"schema": {}
},
"kind": "Http",
"type": "Request"
}
}
},
"parameters": {
"$connections": {
"value": {
"sql": {
"connectionId": "/subscriptions/<SubId>/resourceGroups/<RG>/providers/Microsoft.Web/connections/sql-2",
"connectionName": "sql-2",
"id": "/subscriptions/<SubId>/providers/Microsoft.Web/locations/centralus/managedApis/sql"
}
}
}
}
}

C# How to get exact error message from Logic App triggered by HttpRequest instead of default error message?

I have a simple console application and it calls a Logic App by HttpRequest.
When the Logic App fails at any step I want to get exact the error message saying why it fails.
In the Logic App I can see the error.
Example: in the image, it fails at step 2 which it can't convert a string into an int. It's saying:
InvalidTemplate. Unable to process template language expressions in action 'Parse_JSON' inputs at line '0' and column '0': 'Required property 'content' expects a value but got null. Path ''.'.
which is what's I expect.
Here is my Logic App design:
But when I debug in a console application, it gives me a message "The server did not receive a response from an upstream server. Request tracking id 'some random Ids'." which is not very useful.
Here is my console application:
var obj = new
{
Age = "Twenty",
Name = "James"
};
using (var client = new HttpClient())
{
var content = new StringContent(JsonConvert.SerializeObject(obj));
content.Headers.ContentType.MediaType = "application/json";
var response = await client.PostAsync(url, content);
var errorMessage = await response.Content.ReadAsStringAsync();
//errorMessage: {"error":{"code":"NoResponse","message":"The server did not receive a response from an upstream server. Request tracking id 'some random Ids'."}}
}
So is there anyway to make the C# response return the error message in the step 2 of the Logic App?
What I expect is:
InvalidTemplate. Unable to process template language expressions in action 'Parse_JSON' inputs at line '0' and column '0': 'Required property 'content' expects a value but got null. Path ''.'.
Not:
{"error":{"code":"NoResponse","message":"The server did not receive a response from an upstream server. Request tracking id 'some random Ids'."}}
Thank you in advanced.
You can use actions('<Your_Previous_Step>')['error'] in your case actions('Parse_JSON')['error'] doing so you can able to retrieve the error message of that particular action.
Here is my logic app
I'm testing this through postman. Below is the response I received in postman.
Make sure you set Configure run after options to make the flow work even after it gets failed.
Updated Answer (General Solution)
In this case you can initialise a string variable and then add Append to string variable for each step so that it can catch the previous steps error. Below is the screenshot of my logic app.
Response in my postman
NOTE: Make sure you set Configure run after property for each action.
You can use the Scope action to encase the vast majority of other actions and then if something fails, you can catch the step for which it fails at.
You can load this JSON definition into your own tenant and see a working version.
{
"definition": {
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
"actions": {
"Filter_array": {
"inputs": {
"from": "#variables('Result')",
"where": "#equals(item()['status'], 'Failed')"
},
"runAfter": {
"Initialize_Result": [
"Succeeded"
]
},
"type": "Query"
},
"Initialize_Error_Message": {
"inputs": {
"variables": [
{
"name": "Error Message",
"type": "string",
"value": "#{body('Filter_array')[0]['error']['message']}"
}
]
},
"runAfter": {
"Filter_array": [
"Succeeded"
]
},
"type": "InitializeVariable"
},
"Initialize_Integer_Variable": {
"inputs": {
"variables": [
{
"name": "Integer Variable",
"type": "integer",
"value": 1
}
]
},
"runAfter": {},
"type": "InitializeVariable"
},
"Initialize_Result": {
"inputs": {
"variables": [
{
"name": "Result",
"type": "array",
"value": "#result('Scope')"
}
]
},
"runAfter": {
"Scope": [
"Succeeded",
"FAILED"
]
},
"type": "InitializeVariable"
},
"Scope": {
"actions": {
"Set_Integer_Variable_(Step_1)": {
"inputs": {
"name": "Integer Variable",
"value": 2
},
"runAfter": {},
"type": "SetVariable"
},
"Set_Integer_Variable_(Step_2)": {
"inputs": {
"name": "Integer Variable",
"value": "#string('Test')"
},
"runAfter": {
"Set_Integer_Variable_(Step_1)": [
"Succeeded"
]
},
"type": "SetVariable"
},
"Set_Integer_Variable_(Step_3)": {
"inputs": {
"name": "Integer Variable",
"value": 3
},
"runAfter": {
"Set_Integer_Variable_(Step_2)": [
"Succeeded"
]
},
"type": "SetVariable"
}
},
"runAfter": {
"Initialize_Integer_Variable": [
"Succeeded"
]
},
"type": "Scope"
}
},
"contentVersion": "1.0.0.0",
"outputs": {},
"parameters": {},
"triggers": {
"Recurrence": {
"evaluatedRecurrence": {
"frequency": "Month",
"interval": 12
},
"recurrence": {
"frequency": "Month",
"interval": 12
},
"type": "Recurrence"
}
}
},
"parameters": {}
}
Naturally, it's a little more intensive and follows the same principals as a normal flow for continuing to the next step after a failure but this will help you with larger flows.
This is what the test flow looks like ...
To explain it quickly, the middle steps are simple Set Variable actions that can be changed to cause the failure.
In the definition I've given you, step 2 will fail but you can change it to step 1 or 3 and you should still see the error come out at the end regardless of the step in the scope action that fails.
I suggest playing with it and looking at the output to the scope action, which is written to variable Result in the Initialize Result step.
For reference, this is the sort of information that comes out of the Scope action that you can use to determine what has failed.
{
"variables": [
{
"name": "Result",
"type": "Array",
"value": [
{
"name": "Set_Integer_Variable_(Step_1)",
"inputs": {
"name": "Integer Variable",
"value": 2
},
"outputs": {
"body": {
"name": "Integer Variable",
"value": 2
}
},
"startTime": "2022-04-22T06:55:57.8965917Z",
"endTime": "2022-04-22T06:55:57.9281959Z",
"trackingId": "0c93fa70-a552-4776-bce1-8ac889933de9",
"clientTrackingId": "08585509963278112157168286283CU11",
"status": "Succeeded"
},
{
"name": "Set_Integer_Variable_(Step_2)",
"startTime": "2022-04-22T06:55:57.9434709Z",
"endTime": "2022-04-22T06:55:57.9434709Z",
"trackingId": "f82b494b-0ecd-412b-887a-d4b08f4a5751",
"clientTrackingId": "08585509963278112157168286283CU11",
"code": "BadRequest",
"status": "Failed",
"error": {
"code": "BadRequest",
"message": "The variable 'Integer Variable' of type 'Integer' cannot be initialized or updated with value of type 'String'. The variable 'Integer Variable' only supports values of types 'Integer'."
}
},
{
"name": "Set_Integer_Variable_(Step_3)",
"startTime": "2022-04-22T06:55:57.9590957Z",
"endTime": "2022-04-22T06:55:57.9590957Z",
"trackingId": "f761d71f-8ec0-4a29-9a8a-a39a81faf660",
"clientTrackingId": "08585509963278112157168286283CU11",
"code": "ActionSkipped",
"status": "Skipped",
"error": {
"code": "ActionConditionFailed",
"message": "The execution of template action 'Set_Integer_Variable_(Step_3)' is skipped: the 'runAfter' condition for action 'Set_Integer_Variable_(Step_2)' is not satisfied. Expected status values 'Succeeded' and actual value 'Failed'."
}
}
]
}
]
}
Take note, you still need to apply the Configure run after properties to ensure it continues on after the Scope action finishes ...
You'd need to put some more error checking in but my suggestion would be to wrap all of that functionality into another LogicApp that you can reuse across your tenant. That's the thinking anyway.

How to post data in RestSharp?

How can I post data in RestSharp ? I am very new to RestSharp and dont quite understand the process.
I am familar with Get Requests, which I have written API tests for with no problems.
Using the below example I want to post the Order Qty:
"name": "PostToCurrentBasket",
"class": [
"PostToCurrentBasket"
],
"method": "POST",
"href": "*",
"title": "Add Product to Current Basket",
"type": "application/json",
"fields": [
{
"name": "ProductId",
"type": "text",
"value": 101112,
"title": "Product ID"
},
{
"name": "Quantity",
"type": "number",
"value": 0,
"title": "Order Qty"
}
]
}
],
What I have so far:
var request = new RestRequest("baskets/current/", Method.POST);
Do I need to be using .AddBody and if so how do I use this correctly?
request.RequestFormat = DataFormat.Json; // If you want it to be json
request.AddBody(new { Name = "Foo", LastName = "Bar" }); // Any object that can be serialized
client.Execute(request);

Can't load JSON into a jstree from WCF service (or How to find what's wrong when jstree stays on "loading...")

I am trying to get jStree (jQuery tree control) working in my ASP.NET (C#) page. I'm using a WCF service to return a test string of JSON.
Opening the WCF service URL in the browser works fine - If I go to the URL (http://localhost/website/GetTree) I get the JSON (looks just like opening XML in browser, with syntax highlighting and collapsible tab thingys)
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"attr": { "id": 2, "rel": "default" }, "data": "A node", "children": [ { "data": "Child 1", "attr": { "id": 43, "rel": "document" } }, {"data": "Child 2", "attr": { "id": 25, "rel": "document"} } ] }</string>
jstree itself works fine - if I put the same JSON in "manually" in my document.ready like so:
"json_data": {
"data":
[{
"attr": { "id": 2, "rel": "default" },
"data": "A node",
"children":
[{
"data": "Child 1", "attr": { "id": 43, "rel": "document" }
},{
"data": "Child 2", "attr": { "id": 25, "rel": "document"}
}]},{
"attr": { "id": "li.node.id", "rel": "document" },
"data": {
"title": "Long format demo",
"attr": { "href": "#" }
}}]},
I get the tree appearing with those nodes in it.
But, combining the two:
"json_data": {
"ajax": {
"url": "GetTree",
"data": function (n) {
return {
};
}
}
},
...fails. The jstree shows up as just the word "loading..." and an animated loading gif. And it does hit a breakpoint inside the WCF service method (just like browsing to it does).
A: An idea where I've gone wrong?
B: An idea how I find out what's wrong? jstree documentation was no help, and I can't see any error messages.
Thanks.
Update: solved
Thanks to Mikael Eliasson for pointing out that my service must be returning XML and not JSON.
WCF service code-behind:
// this responseformat bit below fixed it
[WebGet(UriTemplate = "GetTesto", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
public Testo GetTesto()
{
return new Testo();
}
Might be a stupid question but you have enabled the json_data plugin, right? As akonsu said inspecting the response in a tool like Firebug.
It seems to me that you WCF service is not returning JSON but rather a XML response. I think that is your problem. The best thing is probably to change the service to return JSON. If you can't do that you could add the success function and transform the string to JSON with the function $.parseJSON()
I hope that helps. But again you really should start using Firebug or something similar because there are lot of times when you need to inspect the response or debug javascript.

Deserialize complex JSON object using ASP.NET?

I've successfully created code that serializes a complex javascript object and posts it to an ASP.NET page. I can get the JSON string using Request.Form and the result looks like this (I've added indentation for readability):
{
"gasterPerStolPerVecka": {
"name": "gasterPerStolPerVecka",
"keyValue_id": "2",
"set_id": "1",
"containerElement": "#gasterPerStolPerVecka",
"keyValueComponents": [
{
"name": "gasterPerStolPerVecka_guestsPerWeek",
"value": "200"
},
{
"name": "gasterPerStolPerVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "gäster/stol per vecka",
"keyValueCalculationMethod": "divide",
"isValid": true,
"result": 2
},
"tillgangligaStolstimmarPerVecka": {
"name": "tillgangligaStolstimmarPerVecka",
"keyValue_id": "1",
"set_id": "1",
"containerElement": "#tillgangligaStolstimmarPerVecka",
"keyValueComponents": [
{
"name": "tillgangligaStolstimmarPerVecka_openHoursPerWeek",
"value": "35"
},
{
"name": "tillgangligaStolstimmarPerVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "stolstimmar/vecka",
"keyValueCalculationMethod": "multiply",
"isValid": true,
"result": 3500
},
"planeradIntaktPerTillgangligStolOchVecka": {
"name": "planeradIntaktPerTillgangligStolOchVecka",
"keyValue_id": "",
"set_id": "",
"containerElement": "#planeradIntaktPerTillgangligStolOchVecka",
"keyValueComponents": [
{
"name": "planeradIntaktPerTillgangligStolOchVecka_weeklyRevenue",
"value": ""
},
{
"name": "planeradIntaktPerTillgangligStolOchVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "kr",
"keyValueCalculationMethod": "divide",
"isValid": false,
"result": null,
"errorText": "Ofullständigt underlag för beräkning."
},
"planeradIntaktPerTillgangligaStolstimmar": {
"name": "planeradIntaktPerTillgangligaStolstimmar",
"keyValue_id": "",
"set_id": "",
"containerElement": "#planeradIntaktPerTillgangligaStolstimmar",
"keyValueComponents": [
{
"name": "planeradIntaktPerTillgangligaStolstimmar_weeklyRevenue",
"value": ""
},
{
"name": "planeradIntaktPerTillgangligaStolstimmar_openHoursPerWeek",
"value": "35"
},
{
"name": "planeradIntaktPerTillgangligaStolstimmar_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "kr",
"keyValueCalculationMethod": "divide_divide",
"isValid": false,
"result": null,
"errorText": "Ofullständigt underlag för beräkning."
}
}
Now I try to deserialize this on the server side, but it's difficult. I keep getting the error:
[NullReferenceException: Object reference not set to an instance of an object.]
I don't know where to start looking for errors?
Thanks in advance!
/Thomas Kahn
use stringify instead serialization
You need to use a deserialization library for ASP.NET. See http://json.org/ for libraries that are available or maybe there is one built into ASP.NET. Either way, the code will look like:
String s = getAppropriateFormField();
Object o = JSONLibraryPackage.parse(s);
where obviously you'll have to fill in the blanks for how you get the form field and then what package and method does the parsing.

Categories