UDF in Azure Stream Analytics outputs alias in the JSON - azure-stream-analytics

Sript in SAJ:
SELECT
udf.createJsonMessage(param1, param2)
INTO Output
FROM EventHubLocal eventHub
Removed other stuff as not needed here.
The UDF:
function CreateJsonMessageForOutput(param1, param2) {
var obj = new Object();
obj.Prop1 = param1;
obj.Prop2 = param2;
return JSON.stringify(obj);
}
Removed code as not needed here.
The output JSON includes the function alias:
{
"createjsonmessage": "{\"Prop1\":\"param1\",\"Prop2\":\"param2\"}"
}
What do I do to get it in this format:
{
\"Prop1\":\"param1\",
\"Prop2\":\"param2\"
}

One possible way to do that will be to extract the different elements from the object.
See an example below:
WITH step1 AS(
SELECT udf.createJsonMessage(param1, param2)
FROM EventHubLocal eventHub
)
SELECT createJsonMessage.Prop1, createJsonMessage.Prop2
INTO Output
FROM step1
This will just require a small change in the UDF function:
function CreateJsonMessageForOutput(param1, param2) {
var obj = new Object();
obj.Prop1 = param1;
obj.Prop2 = param2;
return obj;
}
Thanks,
JS

To get value for a JSON object we can also use GetRecordPropertyValue method. where the property name as string expression.
This UDF function will return JSON object
function CreateJsonMessageForOutput(param1, param2) {
var obj = new Object();
obj.Prop1 = param1;
obj.Prop2 = param2;
return obj;
}
Query
WITH step1 AS(SELECT udf.createJsonMessage(param1, param2)
FROM EventHubLocal eventHub)
SELECT GetRecordPropertyValue(createJsonMessage,'Prop1') as Prop1, GetRecordPropertyValue(createJsonMessage,'Prop2') as Prop2
INTO Output
FROM step1

Related

Flutter - Class 'Future<dynamic>' has no instance method '[]'

I'm building a weather app for practice and I'm getting following error:
Class 'Future<dynamic>' has no instance method '[]'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: []("weather")
And this is where I think it comes from:
void updateUI(dynamic weatherData) {
var condition = weatherData['weather'][0]['id'];
String cityName = weatherData['name'];
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
}
Had to create a class for my Data i got from my api call:
class WeatherData {
final int conditionID;
final String cityName;
final double temperature;
const WeatherData({
required this.conditionID,
required this.cityName,
required this.temperature,
});
factory WeatherData.fromJson(Map<String, dynamic> json) {
return WeatherData(
conditionID: json['weather'][0]['id'],
cityName: json['name'],
temperature: json['main']['temp'],
);
}
}
And then use it in updateUI() like this:
void updateUI(WeatherData weatherData) {
var condition = weatherData.conditionID;
String cityName = weatherData.cityName;
double temp = weatherData.temperature;
temperature = temp.toInt();
}
As always the documentation helped me a lot:
https://docs.flutter.dev/cookbook/networking/fetch-data

Gmock to test function that returns structure

I am trying to mock function that returns structure. But I get below problem
==> error: use of deleted function
class MockTest: public TestInterface
{
MOCK_METHOD1(func1, struct Response(std::string const &serviceName));
};
TEST_F (Test_1, Start)
{
struct Response Obj;
Obj.var = 5;
EXPECT_CALL(*Mockpointer, func1(_))
.Times(1)
.WillOnce(Return(Obj)); /*Compiler throws error here [error: use of deleted function]*/
auto result = FileToTest_Obj->start(); /*please Assume start function is under test*/
EXPECT_EQ(true, result);
}
Code snippet for reference.
bool start()
{
struct Response response = func1(serviceName);
if(5 == response.var ) {
return true;
}
return false;
}
Is there something I am missing. Is there any sample examples I can refer to mock the function that returns structure

Search where A or B with querydsl and spring data rest

http://localhost:8080/users?firstName=a&lastName=b ---> where firstName=a and lastName=b
How to make it to or ---> where firstName=a or lastName=b
But when I set QuerydslBinderCustomizer customize
#Override
default public void customize(QuerydslBindings bindings, QUser user) {
bindings.bind(String.class).all((StringPath path, Collection<? extends String> values) -> {
BooleanBuilder predicate = new BooleanBuilder();
values.forEach( value -> predicate.or(path.containsIgnoreCase(value) );
});
}
http://localhost:8080/users?firstName=a&firstName=b&lastName=b ---> where (firstName=a or firstName = b) and lastName=b
It seem different parameters with AND. Same parameters with what I set(predicate.or/predicate.and)
How to make it different parameters with AND like this ---> where firstName=a or firstName=b or lastName=b ??
thx.
Your current request param are grouped as List firstName and String lastName. I see that you want to keep your request parameters without a binding, but in this case it would make your life easier.
My suggestion is to make a new class with request param:
public class UserRequest {
private String lastName;
private List<String> firstName;
// getters and setters
}
For QueryDSL, you can create a builder object:
public class UserPredicateBuilder{
private List<BooleanExpression> expressions = new ArrayList<>();
public UserPredicateBuilder withFirstName(List<String> firstNameList){
QUser user = QUser.user;
expressions.add(user.firstName.in(firstNameList));
return this;
}
//.. same for other fields
public BooleanExpression build(){
if(expressions.isEmpty()){
return Expressions.asBoolean(true).isTrue();
}
BooleanExpression result = expressions.get(0);
for (int i = 1; i < expressions.size(); i++) {
result = result.and(expressions.get(i));
}
return result;
}
}
And after you can just use the builder as :
public List<User> getUsers(UserRequest userRequest){
BooleanExpression expression = new UserPredicateBuilder()
.withFirstName(userRequest.getFirstName())
// other fields
.build();
return userRepository.findAll(expression).getContent();
}
This is the recommended solution.
If you really want to keep the current params without a binding (they still need some kind of validation, otherwise it can throw an Exception in query dsl binding)
you can group them by path :
Map<StringPath,List<String>> values // example firstName => a,b
and after that to create your boolean expression based on the map:
//initial value
BooleanExpression result = Expressions.asBoolean(true).isTrue();
for (Map.Entry entry: values.entrySet()) {
result = result.and(entry.getKey().in(entry.getValues());
}
return userRepository.findAll(result);

Generate parameter list with userdefined types at runtime (using C#)

As part of my project, I am trying to build a web UI where user will select a method and pass the values. My program should be able to call the method dynamically and build a parameter list on runtime to pass it to the method.
I have created a comma separated list (string) of key and value pairs. This key/value pair is nothing but the parameter name and value of my method (methodname stored in a variable). Example: string params = "ID:123;Name:Garry;Address:addressObject;AddressLine:108 Plaza Lane;City:Avenel;State:NJ;Zip:07001;". Where ID and Name are simple string varaibles while Address is user defined type. What follows after Address i.e. AddressLine, City, State and Zip is elements of Address object. And my method definition is
public string GetInfo(string ID, string Name, Address addressObject)
{
//return something;
}
I am dynamically calling the method (GetInfo) that is stored in sMethodName variable using DynamicProxy like :
string sMethodName = "GetInfo";
object result = (object) proxy.CallMethod(sMethodName, arguments);
Challenge is how to pass the argument list dynamically? Till now I am just able to extract the values from the csv variable into NamedValueCollection. Here is the code:
public static void StoreParameterValues(string param)
{
nvc = new NameValueCollection();
param = param.TrimEnd(';');
string[] parameters = param.Split(new char[] { ';' });
foreach (string val in parameters)
{
string[] keyValue = val.Split(new char[] { ':' });
nvc.Add(keyValue[0], keyValue[1]);
}
}
..and here is the code that tries to build the parameter:
string methodName = "GetInfo";
DynamicProxyFactory factory = new DynamicProxyFactory("http://../myservice.svc");
string sContract = "";
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
sContract = endpoint.Contract.Name;
}
DynamicProxy proxy = factory.CreateProxy(sContract);
string[] values = null;
// Create the parameter list
object[] arguments = new object[nvc.Count];
int i = -1;
foreach (string key in nvc.Keys)
{
values = nvc.GetValues(key);
foreach (string value in values)
{
arguments[++i] = value;
}
}
object result = (object) proxy.CallMethod(methodName, arguments);
The above code works if I have simple primitive types but not sure how can I build the logic for any other userdefined types. How can I create a object dynamically of type stored in a variable? Not sure if I was able to put my question correctly. I hope so :)
Edit: 01/19/2011: Applied the suggestion from Chris - using Reflection instead of ComponentModel.
I have converted the code to make it more generic. This works now for all primitive and custom types (resursion). Code snippet below:
private object BuildParameterList(Type type)
{
object item = new object();
item = Activator.CreateInstance(type);
PropertyInfo[] propArray = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);
for (int i = 0; i < propArray.Length; i++)
{
PropertyInfo pi = (PropertyInfo)propArray[i];
////Check for custom type
if (IsCustomType(pi.PropertyType))
{
object item1 = BuildParameterList(pi.PropertyType);
pi.SetValue(item, item1, null);
}
else
{
if (property.ContainsKey(pi.Name))
{
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
}
}
}
return item;
}
But if one of the property is Color (I just tested with Color type, will fail with other system types aswell-i guess), then it fails at the following line. Not sure how to handle system types - Color or something similar.
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
Can you not find what types are expected by the method, by inspecting its ParameterInfos:
endpoint.Contract.ContractType.GetMethod(methodName).GetParameters();
and then instantiating the custom types using:
Activator.CreateInstance(parameterType);

SQL Like keyword in Dynamic Linq

I want to use SQL's Like keyword in dynamic LINQ.
The query that I want to make is like this
select * from table_a where column_a like '%search%'
Where the column_a can be dynamically changed to other column etc
In this dynamic LINQ
var result = db.table_a.Where( a=> (a.column_a.Contains("search")) );
But the column can't be dynamically changed , only the search key can
How do we create a dynamic LINQ like
var result = db.table_a.Where("column_a == \"search\"");
That we can change the column and the search key dynamically
This should work for you:
.Where("AColumnName.Contains(#0)", "Criteria")
Create an ExtensionMethods class with this function
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, string keyword)
{
var type = typeof(T);
var property = type.GetProperty(propertyName);
string number = "Int";
if (property.PropertyType.Name.StartsWith(number))
return source;
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constant = Expression.Constant("%" + keyword + "%");
MethodCallExpression methodExp = Expression.Call(null, typeof(SqlMethods).GetMethod("Like", new Type[] { typeof(string), typeof(string) }), propertyAccess, constant);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
And then call it like this:
var result = db.table_a.Like("column_a", "%search%");
http://weblogs.asp.net/rajbk/archive/2007/09/18/dynamic-string-based-queries-in-linq.aspx
Addition:
Use an expression tree
How do I create an expression tree to represent 'String.Contains("term")' in C#?
That is what the dynamic linq library does internally.
I do not believe there is a direct translation to SQL for the LIKE keyword in LINQ. You could build one if you used expression trees, but I haven't gotten that good yet.
What I do is something like this:
using System.Data.Linq.SqlClient;
if (!string.IsNullOrEmpty(data.MailerName))
search = search.Where(a => SqlMethods.Like(a.Mailer.Name, string.Format("%{0}%", data.MailerName)));
where search is the query I'm building and data is the object containing the properties that hold the search criteria. I build the query dynamically by listing all of the possible search criteria in this way, which adds the appropriate Where methods to search.
Maybe a bit late but Another approach is add Extention method that use Contains to simulate Like keyword as :
public static class DbHelpers
{
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, string propertyValue)
{
var prop = typeof(T).GetProperty(propertyName);
if (prop == null || prop.PropertyType.Name.StartsWith("Int"))
return source;
ParameterExpression parameter = Expression.Parameter(typeof(T), "row");
Expression property = Expression.Property(parameter, propertyName);
Expression value = Expression.Constant(propertyValue);
var containsmethod = value.Type.GetMethod("Contains", new[] { typeof(string) });
var call = Expression.Call(property, containsmethod, value);
var lambda = Expression.Lambda<Func<T, bool>>(call, parameter);
return source.Where(lambda);
}
}
And use of it:
var foo = entity.AsQueryable().Like("Name", "bla bla");
If send PropertyName with type of int, the method return original entity that you passed before to it.