Convert neo4j list of integers to C# array - c#

I have a small C# application that queries a Neo4j database. The queries work fine, but I'm having trouble converting arrays of integers to an appropriate C# list type. It just seems that they should be in a proper List/Array/etc. on the C# side.
Here is the query that I run - it returns the correct results, but I'm not smart enough to get the returned list portion into a proper C# list-type object. Here is the code that is running:
using (var driver = GraphDatabase.Driver("bolt:validURL, AuthTokens.Basic("username", "password")))
// using (var session = driver.Session())
{
var result = session.Run("MATCH (c:Climate) WHERE c.koppen = 'BSh' RETURN c.koppen AS koppen, c.counties AS counties");
foreach (var record in result)
{
var koppen = record["koppen"].As<string>();
var counties = record["counties"];
}
}
}
}
}
The record[counties] is a list of a integers with - so it seems that I should easily be able to put it into a C# list object that I can iterate through. I need to do that in order to process each county and display results. C# is pretty new for me, so thanks for your help in letting me connect these two languages!
EDIT: No responses, so I tried a new approach - to simplify things, I am no longer returning the koppen value - just the list of counties (which is where the problem lies). I found some code in the Neo4j manual, and tried it:
public List<int> GetCounties()
{
using (var driver = GraphDatabase.Driver("bolt://validURL", AuthTokens.Basic("username", "password")))
using (var session = driver.Session())
{
return session.ReadTransaction(tx =>
{
var result = tx.Run("MATCH (c:Climate) WHERE c.koppen = 'BSh' RETURN c.counties");
var a = result.Select(Record => Record[0].As<int>()).ToList();
return a;
});
}
}
}
Now I'm getting an exception:
System.InvalidCastException occurred
HResult=0x80004002
Message=Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]' to type 'System.IConvertible'.
Source=
StackTrace:
The exception occurs on the line ending with the toList() statement. Sorry for my not understanding the conversions that need to occur between Neo4j list results and C# lists/arrays/etc. I'm happy to try any suggestions that I get!

Related

Teradata Query Using Dapper C#

I am trying to dynamically query a Teradata database using Dapper but am having some issues. Here is the code:
// model variable is the parameter passed in with search information
using (IDbConnection con = new TdConnection(connection.GetConnectionString()))
{
var builder = new SqlBuilder();
var selector = builder.AddTemplate($"SELECT * FROM Temp_Table /**where**/");
if (model.Id != 0)
{
builder.Where("Id = ?", new { model.Id });
}
if (!string.IsNullOrEmpty(model.Employee_Id))
{
builder.Where("Employee_Id = ?", new { model.Employee_Id });
}
var data= con.Query<TableModel>(selector.RawSql, model).ToList();
return data;
}
The error I am getting is:
[Teradata Database] [3939] There is a mismatch between the number of
parameters specified and the number of parameters required.
I have used very similar code to query DB2 which worked just fine; what do I need to do differently with Teradata?
Managed to figure it out. Changed the line for getting the data to:
var data= con.Query<TableModel>(selector.RawSql, selector.Parameters).ToList();
Not sure why passing in the model worked just fine in my DB2 version but not this Teradata version.
At first glance it appears to be falling through and not adding any "where" condition. Try to structure it in such a way that if it falls through then add 1=1 or a Teradata equivalent if that doesn't work.
I'm unfamiliar with the SqlBuilder() class; but if you have a way of seeing if there aren't any Where constraints added, then to add a generic one. Or, a dirtier way would be to keep a bool reference and check at the end.
Update
Try passing in the parameters:
var data= con.Query<TableModel>(selector.RawSql, selector.Parameters).ToList();

convert dynamic object to C# object

I’m looking to take a dynamic object from a third party API & convert to my C# object with minimal code.
Sort of like what Dapper does with a SQL statement results to a C# object. Is there a library that would do this?
I can do it manually like below, but it seems like alot of code to write everytime I want to retrieve from this API.
public IEnumerable<Requirement> Get()
{
dynamic requirementsSelect;
requirementsSelect = _RequirementsRepository.GetRequirements();
IList<Requirement> Requirements = new List<Requirement>();
foreach (var req in requirementsSelect)
{
Requirement requirement = new Requirement();
requirement.Text = req.Text;
requirement.Number = req.Number;
Requirements.Add(requirement);
foreach (var node in req.Phrases)
{
Requirement reqNode = new Requirement();
reqNode.Text = node.Text;
reqNode.Number = node.Number;
requirement.Nodes.Add(reqNode);
}
return Requirements;
}
Thanks
I ended up returning the third party as JSON as follows. In my specific case the JSON wasn't showing the properties. I resolved by changing the dynamic object to IEnumerable and I was then able to specify which properties I wanted to retrieve using .Select.
IEnumerable<dynamic> requirements = _RequirementsRepository.GetRequirements();
return JsonConvert.SerializeObject(new
{
Requirement = requirements.Select(x => x.Text),
Number = requirements.Select(x => x.Number),
});
Thanks!

retrieving data using stream api

I'm using the RavenDB streaming API to retrieve all 355,000 DocsToProcess from my database instance using the following code:
_myDocs = new List<DocsToProcess>();
var query = RavenSession.Query<DocsToProcess>();
using (var enumerator = RavenSession.Advanced.Stream(query))
{
while (enumerator.MoveNext())
{
DocsToProcess u = enumerator.Current.Document;
_myDocs.Add(u);
}
}
However, the following exception message is thrown:
StreamQuery does not support querying dynamic indexes. It is designed to be used with large data-sets and is unlikely to return all data-set after 15 sec of indexing, like Query() does.
How I can correctly iterate through all elements of type DocsToProcess in my C# application?
The documentation says explicitly for unbound results:
Important side notes:
the index already exists. Creation of a index won't occur and the query error with an IndexDoesNotExistsException exception.
And that's what your exception is saying. You have to create a static index for streaming results.
Similar to JHo above, the solution that I came up with means that you do not need to make a static index for streaming, because you're relying on the default index and using the StartsWith overload of Stream<T> in the Raven client.
We've found the solution below to work fine for most of our use-cases where we need to get everything from a Raven instance.
public IEnumerable<T> GetAll()
{
var results = new List<T>();
var conventions = _documentStore.Conventions ?? new DocumentConvention();
var defaultIndexStartsWith = conventions.GetTypeTagName(typeof(T));
using(var session = _documentStore.OpenSession())
{
using(var enumerator = session.Advanced.Stream<T>(defaultIndexStartsWith))
{
while(enumerator.MoveNext())
results.Add(enumerator.Current.Document);
}
}
return results;
}
To get by without creating a static index, you can provide some minimal bounding like this:
using (var session = store.OpenSession())
{
IEnumerator<StreamResult<Employee>> stream =
session.Advanced.Stream<Employee>("employees/");
while (stream.MoveNext())
{
// ....
}
}

Receiving error CS0030: Cannot convert type 'char' to 'string' when I try to run this dropdown list

I am very new to C#, and got thrown into it by the company that I work for, so I apologize for my extreme lack of knowledge on all of this. The site uses a dropdown list so the user can select a language to view the site in. This is the code that I started with, which worked perfectly.
protected void CreateLanguageList()
{
// Get the available cultures.
string[] cultures = Telerik.Localization.Configuration.ConfigHelper.Handler.Cultures.Split(',');
foreach (string availableCulture in cultures)
{
var culture = new CultureInfo(availableCulture.Trim());
var item = new ListItem(culture.NativeName, culture.ToString());
LanguageSelector.Items.Add(item);
if (culture.ToString() == currentCultureString)
{
item.Selected = true;
}
}
}
Now that we are migrating to an updated CMS, Telerik.Localization is no longer supported. After contacting their support, they said that I could access the language files by using this code and accessing the name of the culture using the DisplayName() property:
var allCultures = AppSettings.CurrentSettings.AllLanguages.ToList();
Due to my very limited lack of knowledge on C# so far (I am trying to teach myself), I didn't want to change the code too much if I didn't have to, so I found where I could convert a list to a string, which i figured would allow me to leave the rest of the code alone, only having to change the one call to the language files. However, I am receiving a CS0030 error when I try and run this code:
protected void CreateLanguageList()
{
// Get the available cultures.
var allCultures = AppSettings.CurrentSettings.AllLanguages.ToList();
string combinedCultures = string.Join(",", allCultures);
foreach (string availableCulture in combinedCultures)
{
var culture = new CultureInfo(availableCulture.Trim());
var item = new ListItem(culture.NativeName, culture.ToString());
LanguageSelector.Items.Add(item);
if (culture.ToString() == currentCultureString)
{
item.Selected = true;
}
}
}
Any help in explaining what I'm doing wrong and how I could go about fixing it would be monumentally appreciated.
Your problem is that combinedCultures is defined as a string, but then you're trying to iterate over it with a type string in the foreach. When you iterate over a string you get chars. You should be able to just get rid of the combinedCultures variable altogether and foreach using allCultures.
The problem here is that foreach is only working on availableCulture because the type string is implicitly an array of char.
I'm not exactly sure what you're doing, but it looks like you're turning an array into a string when you just need to pass the array in directly.

using the "ScanOperator.In" for DynamoDB in ASP.NET

I'm using the AWS SDK for .NET, and I'm trying to perform a "scan" operation using the "in" operator.
The ScanCondition takes in three arguments, but I'm not sure what the last argument [the values] should be.
Is it an array of strings? (this returns empty, when it should return results)
Is it a comma-delimited list of strings? (this throws an error saying it could not convert a list of strings into a string)
I've tried a number of different things, and nothing has worked.
public void GetUsers()
{
AmazonDynamoDBClient client = new AmazonDynamoDBClient("key", "secret", Amazon.RegionEndpoint.GetBySystemName("systemEndpoint");
DynamoDBContext context = new DynamoDBContext(client);
var results = context.Scan<User>(new ScanCondition("ID", ScanOperator.In, list /* what goes here? */));
}
The values argument should be of type object[].
In your example, (assuming your list is of type int[] or List), it needs to be cast to type object[] first.
var objectValues = list.Select(x => (object)x).ToArray();
var results = context.Scan<User>(new ScanCondition("ID", ScanOperator.In, objectValues));
It's a known usability issue with the API. If your ID property were of type string, it would work as you'd expect.
As the documentation states the object needed is AttributeValueList.
So you will need to wrap your strings as AttributeValues before passing them to the Scan command

Categories

Resources