How to retrieve values by index from a dynamic Object - xelement

String zohoResponse = #"
[
{
'Title':'Mr.',
'First Name':'ram',
'Last Name':'chang',
'Employed at Trade Client Name':'mile travel',
'Telephone':'657498333',
'E-mail':'abc#traveller.com',
'Fax':' ',
'Street':'123 Street',
'City':'Winnipeg',
'State / Province':'Manitoba',
'Country':'Canada',
'Postcode':'R4T 600',
'Agent ID':70,
'Primary Sales Agent':' ',
'Employed at From':'09/12/2008',
'Employed at To':'09/12/2028'
}
]
";
dynamic jsonObj = JsonConvert.DeserializeObject(zohoResponse);
xmlData = new XDocument(
`enter code here` new XElement("Leads",
new XElement("row", new XAttribute("no", "1"),
new XElement("FL", new XAttribute("val", "Lead Source"), jsonObj["Last Name"]),
new XElement("FL", new XAttribute("val", "Title"), jsonObj["First Name"])
)));
I want to retrieve the dynamic index values. i have used new
XElement("FL", new XAttribute("val", "Title"),
jsonObj.GetType().GetProperty("Title").GetValue(jsonObj,null))
but am still getting exception on retrieve the values by index

jsonObj is an array so you need to reach the first element in the array first before querying the json literal.
dynamic jsonObj = JsonConvert.DeserializeObject(zohoResponse);
dynamic arr = jsonObj.First;
var xmlData = new XDocument(
new XElement("Leads",
new XElement("row", new XAttribute("no", "1"),
new XElement("FL", new XAttribute("val", "Lead Source"), arr["Last Name"]),
new XElement("FL", new XAttribute("val", "Title"), arr["First Name"])
)));

Related

Linq List to Byte Array

I search in google, stackoverflow but did not get easy answer. Is there any way to convert a linq list to byte array?
public FileResult GetCustomerListCSV()
{
List<Customer> CustomerList = new List<Customer>();
CustomerList = dbContext.Customer.ToList(); // Need to convert this into byte array
return File(CustomerList, "text/csv", "CustomerList.csv");
}
Please help.
You have to create a CSV string first, then convert it to bytes:
var lines = CustomerList.Select(c => $"{c.Id}, {c.Name}");
var csv = string.Join(Environment.NewLine, lines);
var bytes = Encoding.UTF8.GetBytes(csv);
return File(bytes, "text/csv", "CustomerList.csv");
Alternatively, using CsvHelper library:
using var ms = new MemoryStream();
using var writer = new StreamWriter(ms);
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(CustomerList);
csv.Flush();
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "text/csv", "CustomerList.csv");

Unable to create an index with nested json using Jest elastic client

I am using java and Jest (https://github.com/searchbox-io/Jest) as a client for elastic search cluster.
Trying to create and index with the below structure in http://localhost:9200/myindex/mytype
{
"doc": {
"_content": "mycontent",
"_name": "mypdf.pdf",
"_content_type": "application/pdf"
}
}
And below is my java code,
XContentBuilder docObject = jsonBuilder().startObject().field("_content", doc).field("_name", name).field("_content_type", contentType)
.field("title", title).field("author", author).endObject();
index1 = new Index.Builder(docObject).build();
source = jsonBuilder()
.startObject()
.field("doc", docObject.string())
.endObject().string();
Index index = new Index.Builder(source).index(baseIndexName).type(ElasticConstants.BASE_TYPE).build();
But when this gets executed , the source is not passed as a Json and value for the key "doc" is passed as a string literal because of which the index is not getting created . How do I pass nested json objects to the Index.Builder using Jest ?
//Instantiate JEST Client
JestClientFactory factory = new JestClientFactory();
HttpClientConfig config = new HttpClientConfig.
Builder("http://localhost:9201")
.multiThreaded(true).build();
factory.setHttpClientConfig(config);
JestClient jestClient = factory.getObject();
//create index
jestClient.execute(new CreateIndex.Builder("so4index").build());
//create index mapping
RootObjectMapper.Builder rootObjMapBuilder1 = new RootObjectMapper.Builder("so1type");
RootObjectMapper.Builder rootObjMapBuilder = new RootObjectMapper.Builder("doc");
rootObjMapBuilder.add(new StringFieldMapper.Builder("_content").store(true));
rootObjMapBuilder.add(new StringFieldMapper.Builder("_name").store(true));
rootObjMapBuilder.add(new StringFieldMapper.Builder("_content_type").store(true));
rootObjMapBuilder1.add(rootObjMapBuilder);
DocumentMapper docMapper = new DocumentMapper.Builder("so4index", null, rootObjMapBuilder1).build(null);
String source = docMapper.mappingSource().toString();
PutMapping putMapping = new PutMapping.Builder("so4index", "so1type", source).build();
JestResult mappingResult = jestClient.execute(putMapping);
//Insert Document Content
String doc="mycontent";
String name="mypdf.pdf";
String contentType = "application/pdf";
XContentBuilder docObject = jsonBuilder()
.startObject()
.startObject("doc").field("_content", doc)
.field("_name", name)
.field("_content_type", contentType)
.endObject()
.endObject();
Index index = new Index.Builder(docObject.string()).index("so4index").type("so1type").build();
JestResult jestResult= jestClient.execute(index);
jestClient.shutdownClient();

Must declare the scalar variable "#historyId" exception

I have a working raw Sql command execution
using (var cmd = SqlUtils.CreateSqlCommand(cmdText, sqlConn))
{
cmd.Parameters.Add(new SqlParameter("historyId", SqlDbType.Int)).Value = AAverage.CashFlowRelevantHistoryId;
cmd.Parameters.Add(new SqlParameter("nodeId", SqlDbType.Int)).Value = AAverage.CashNodeId;
cmd.Parameters.Add(new SqlParameter("denomId", SqlDbType.Int)).Value = AAverage.DenominationId;
cmd.Parameters.Add(new SqlParameter("dayId", SqlDbType.Int)).Value = AAverage.CashFlowDayCategoryId;
cmd.Parameters.Add(new SqlParameter("hour", SqlDbType.Int)).Value = AAverage.Hour;
cmd.Parameters.Add(new SqlParameter("type", SqlDbType.Int)).Value = AAverage.ValueType;
cmd.Parameters.Add(new SqlParameter("average", SqlDbType.Real)).Value = AAverage.AverageDerivative;
using (var reader = cmd.ExecuteReader())
if (reader.HasRows && reader.Read())
{
IDataRecord record = (IDataRecord)reader;
AAverage.Id = record.GetInt32ByName("Id");
}
}
but if I've changed it to use SqlQuery method, I get the error in the subject:
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT INTO CashFlowAverageDerivatives");
cmdText.AppendLine(" (CashFlowRelevantHistoryId, CashNodeId, DenominationId, CashFlowDayCategoryId, Hour, ValueType, AverageDerivative)");
cmdText.AppendLine("VALUES");
cmdText.AppendLine(" (#historyId, #nodeId, #denomId, #dayId, #hour, #type, #average)");
cmdText.AppendLine("SELECT Id FROM CashFlowAverageDerivatives WHERE ##ROWCOUNT > 0 and Id = scope_identity()");
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId,
new SqlParameter("nodeId", SqlDbType.Int).Value = AAverage.CashNodeId,
new SqlParameter("denomId", SqlDbType.Int).Value = AAverage.DenominationId,
new SqlParameter("dayId", SqlDbType.Int).Value = AAverage.CashFlowDayCategoryId,
new SqlParameter("hour", SqlDbType.Int).Value = AAverage.Hour,
new SqlParameter("type", SqlDbType.Int).Value = AAverage.ValueType,
new SqlParameter("average", SqlDbType.Real).Value = AAverage.AverageDerivative
).First<int>();
and I have no idea why. If I tried to rename "historyId" in Sql text to something else, exception reports this new name. It seems like parameter definition was missing or misspelled, but list of parameters has been copy&pasted, VS IDE search command finds it, prefix "#" does not matter...
Sure I can live with my working version, but I'm learning EF and it tease me I'm not able to solve this
You were sending the sql parameter as value directly.
When you did this
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId
You actually sent a value of AAverage.CashFlowRelevantHistoryId, not a SqlParameter.
Try changing it with this and see if it works.
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", AAverage.CashFlowRelevantHistoryId),
new SqlParameter("nodeId", AAverage.CashNodeId),
new SqlParameter("denomId", AAverage.DenominationId),
new SqlParameter("dayId", AAverage.CashFlowDayCategoryId),
new SqlParameter("hour", AAverage.Hour),
new SqlParameter("type", AAverage.ValueType),
new SqlParameter("average", AAverage.AverageDerivative)
).First<int>();
Or this
AAverage.Id = ADbContext.Database.SqlQuery<int>(
cmdText.ToString(),
new SqlParameter("historyId", SqlDbType.Int) { Value = AAverage.CashFlowRelevantHistoryId },
new SqlParameter("nodeId", SqlDbType.Int) { Value = AAverage.CashNodeId },
new SqlParameter("denomId", SqlDbType.Int) { Value = AAverage.DenominationId },
new SqlParameter("dayId", SqlDbType.Int) { Value = AAverage.CashFlowDayCategoryId },
new SqlParameter("hour", SqlDbType.Int) { Value = AAverage.Hour },
new SqlParameter("type", SqlDbType.Int) { Value = AAverage.ValueType },
new SqlParameter("average", SqlDbType.Real) { Value = AAverage.AverageDerivative }
).First<int>();

I'm trying to create a dynamic object based on the value of a column using linq

Based on the values of a column I am trying to create an object with a specific property value. How do I modify the following query to do that?
//object alertCode has properties of "code" and "description" code will be set depending on what the alert_type value thats returned from the query.
var medicalcodes = new string[]{"M", "D", "5"};
var specialedcodes = new string []{"C", "I"};
var personalcommentscodes = new string []{"A"};
var academiccodes = new string[]{"R", "E", "S"};
List<alertCode alertCollections = (from a in alertinfo
select new alertCode{
where medicalcodes.Contains(a.alert_type)
code = 'M',
where specialcodes.Contains(a.alert_type)
code = 'S',
where personalcommentscodes.Contains(a.alert_type)
code = 'P',
where academiccodes.Contains(a.alert_type)
code = 'A',
desc = a.description
} ).ToList();
I'd moved code calculation to separate method
var query = alertinfo.Select(a => new alertCode()
{
code = GetCodeFor(a.alert_type),
desc = a.description
}).ToList();
Code calculation:
private char GetCodeFor(string alertType)
{
if (medicalcodes.Contains(alertType)
return 'M';
if (specialcodes.Contains(alertType)
return 'S';
if (personalcommentscodes.Contains(alertType)
return 'P';
if (academiccodes.Contains(alertType))
return 'A';
// return default value
}

JSON.NET Argument Exception when creating JSON with LINQ

I'm using JSON.NET Linq to JSON, when I execute the below I get the following argument exception:
Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject
What's wrong with the code
string content = new JObject(
new JObject("auth",
new JProperty("user", "anemail#gmail.com"),
new JProperty("secret", "somepassword")
),
new JObject("config",
new JProperty("template", "1")
),
new JObject("data",
new JProperty("email", "body")
)
).ToString();
As per the JSON.NET documentation, you need to wrap your JObjects in JProperties themselves:
string content = new JObject(
new JProperty("auth",
new JObject(
new JProperty("user", "anemail#gmail.com"),
new JProperty("secret", "somepassword")
)
),
new JProperty("config",
new JObject(
new JProperty("template", "1")
)
),
new JProperty("data",
new JObject(
new JProperty("email", "body")
)
)
).ToString();

Resources