Linq XML code not yielding the desired result. Shows no item - wpf

i have the following code but don't understand where am i getting wrong. There are five items in the xml file but this code shows none.
public static List<string> LoadLedgersString()
{
List<string> ListLedgerStringRecords = new List<string>();
// Execute the query using the LINQ to XML
XDocument doc = XDocument.Load(#"Ledgers.xml");
var records = from r in doc.Element("Ledgers").Elements("Ledger") select r;
foreach (var record in records)
{
string lLedgerString = record.Element("Name").Value;
ListLedgerStringRecords.Add(lLedgerString);
}
return ListLedgerStringRecords;
}
The code that is calling and utilizing its result is following
List<string> ledgerList = new List<string>();
ledgerList = DAL_Ledgers.LoadLedgersString();
ledgerListView.DataContext = ledgerList;
ICollectionView view =
CollectionViewSource.GetDefaultView(ledgerList);
new TextSearchFilter(view, this.searchTextBox);

This will probably be a problem with namespacing or with pathing.
Please post some example XML, then we can try to help.

Related

Using Dapper in C# MVVM and SQL Server 2019/Visual Studios Pro 2019

I am writing an application using C#, WPF, MVVM and SQL Server, and I am using Dapper as an ORM. Below is a snippet of the sample code I am trying to make work:
public List<MAKE THIS GENERIC> ExecuteSQLSPROC(string SPROCName, SqlParameter[] parameters, IEnumerable<MAKE THIS GENERIC> model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(DBHelper.CNNVal("MyDatabaseName")))
{
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
command.Connection = (SqlConnection)connection;
command.CommandText = SPROCName;
DynamicParameters parms = new DynamicParameters();
for (int i = 0; i < parameters.Length; i++)
{
var parmname = parameters[i].ParameterName;
var parmvalue = parameters[i].Value;
// I KNOW I can put DIRECTION as a parameter variable but right now I don't want to!!
parms.Add(parmname, parmvalue);
}
var output = connection.Query<Make THIS GENERIC>(SPROCName, parms, commandType: CommandType.StoredProcedure).ToList();
return output; // return the recordset to the caller - a List<> of one object/model is acceptable - NOT POPULATING EXCEL spreadsheet with
// the results
}
}
I want to call this piece of code (which does not compile right now for obvious reasons) by supplying any ViewModel and be able to execute this code as if the ViewModel is generic within the routine. I need to know how to correctly code the above and also make the call to this routine with generic ViewModels (probably using a Lambda expression of some sort).
Basically, I want to be able to say "execute this SPROC, with these dynamic parameters and map the output to a ViewModel that is generic and return the results to the caller. Next time you're called it will be same logic, different SPROC, different parameters and ViewModel". I do NOT want extraneous comments that DO NOT directly answer this question. I know that I can add the parameter direction in a call the SQL SPROCs; but that knowledge is irrelevant to this question I am asking!
You can put your method in a generic class if you have other methods:
public class DbStuff<T>
{
public IList<T> ExecuteSQLSPROC(string SPROCName, SqlParameter[] parameters, IEnumerable<T> model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(DBHelper.CNNVal("MyDatabaseName")))
{
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
command.Connection = (SqlConnection)connection;
command.CommandText = SPROCName;
DynamicParameters parms = new DynamicParameters();
for (int i = 0; i < parameters.Length; i++)
{
var parmname = parameters[i].ParameterName;
var parmvalue = parameters[i].Value;
// I KNOW I can put DIRECTION as a parameter variable but right now I don't want to!!
parms.Add(parmname, parmvalue);
}
var output = connection.Query<T>(SPROCName, parms, commandType: CommandType.StoredProcedure).ToList();
return output; // return the recordset to the caller - a List<> of one object/model is acceptable - NOT POPULATING EXCEL spreadsheet with
// the results
}
}
}
Then call it via:
var stuff = new DbStuff<MyViewModel>();
var results = stuff.ExecuteSQLSPROC("", blah, blah);
Or just make the method generic:
public IList<T> ExecuteSQLSPROC<T>(string SPROCName, SqlParameter[] parameters, IEnumerable<T> model)

advance search text box in angular

I work on an online search project
I want to make a search textbox that works like: if I want to search about a book that Joe wrote it with title my book and publisher is tia.
I type in the search: joe my book tia or tia jo book >
so I will get a result for it.
tia is from a table in SQL database
joe is from a table in SQL database
my book is from a table in SQL database
can somebody help me?
You can easily accomplish that if you add another column, that will contain concatenated data from other three columns, to your data table (in your database) and then make a search in that column.
writer title publisher search_column
joe my book tia joe my book tia
Then, you can make SQL query to search by that column with LIKE
example with ExecuteReader.
var query = "select * from my_table where 1 = 1 " + filterQuery;
Create parameters:
public static SqlParameter AddSqlParameter(string parameterName, object value)
{
var p = new SqlParameter(parameterName, value);
return p;
}
List<SqlParameter> sqlParameters = new List<SqlParameter>();
var filterQuery = "";
this will split your search input by spaces
string[] words = searchInput.Split(' ');
loop through your search phrases and add one parameter for each phrase found:
for (int i = 0; i < words.Count; i++) {
sqlParameters.Add(AddSqlParameter("#p" + i.ToString(), words[i]));
filterQuery = filterQuery + " AND search_column LIKE " + "#p" + i.ToString();
}
add your search query and parameters to ExecuteReader:
public static List<T> ExecuteReader<T>(string commandText, List<SqlParameter> parameters) where T : new()
{
List<T> output = new List<T>();
using (SqlConnection con = new SqlConnection(mySetting.ConnectionString))
using (SqlCommand cmd = new SqlCommand(commandText, con))
{
cmd.Parameters.AddRange(parameters.ToArray());
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
T t = new T();
for (int i = 0; i < rdr.FieldCount; i++)
{
Type type = t.GetType();
PropertyInfo prop = type.GetProperty(rdr.GetName(i));
if (prop != null)
{
prop.SetValue(t, rdr.GetValue(i) is DBNull ? null : rdr.GetValue(i), null);
}
}
output.Add(t);
}
return output;
}
}
}
call your ExecuteReader like this:
var result = ExecuteReader<myClass>(query, sqlParameters );
If you have further questions, just ask.

Multi-threading NpgsqlConnections and readers producing duplicate results. C#

I have thousands of queries I need to run on thousands of different Schema over 10 databases. I am trying to thread these queries and use a BlockingCollection to write results into, while also using another thread to read from this collection and write it to disk as the result sets of these queries are too large to store in memory.
Here is the problem area in my code:
public class Node {
public string ConnectionString;
public string Query;
public Node(string databaseDetails, string query) {
//Cannot put in actual logic, but this part is fine
ConnectionString = {logic for connection string}
Query = "set search_path to {schema from databaseDetails};" + query
}
}
public void runQuery(string query, BlockingCollection<Dictionary<string, object>> producer) {
List<Node> nodes = getNodes(query);
Parallel.ForEach(nodes, node => {
NpgsqlConnection conn = new NpgsqlConnection(node.ConnectionString);
conn.Open();
NpgsqlCommand npgQuery = new NpgsqlCommand(node.Query, conn);
NpgsqlDataReader reader = npgQuery.ExecuteReader();
while (reader.Read()) {
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++) {
row[reader.GetName(i)] = reader.GetValue(i);
}
producer.Add(row);
}
conn.Close();
});
producer.CompleteAdding();
}
This code runs, and retrieves all of the results, but it duplicates a lot of the results as well, so the blocking collection has 5-10 times more records than it should. Any help would be greatly appreaciated.
So I was just an idiot and was comparing my generated result set to the UNION of all the queries I was running not the UNION ALL, so my "true" result set had no duplicates in it because the union was removing them :/

Dynamic Entity for Raw Sql Query using Entity Framework

I am scratching my head here. I have a bootstrap modal that has a field for entering in a sql query. The query I pass uses an AJAX call to a controller and executes the sql query using the code below and returns a JSON object. Something like this:
context.Database.SqlQuery(typeof(object), query);
But all I get are empty objects. I can't pass a type when I don't know the columns. For instance I could do something like this:
public class CusType {
public CusType(){}
public int Id { get; set; }
public string Name { get; set; }
}
and then do something like this:
context.Database.SqlQuery(typeof(CusType), query);
But that won't help me when I don't know or can't know the columns. I even tried an idea using ExpandoObjects. Example:
List<string> columns = new List<string>();
string tmpCol = query;
string[] seperator = new string[] { "from" };
tmpCol = query.ToLower()
.Replace(#"\s+", "")
.Replace("select", "");
tmpCol = tmpCol.Split(seperator, 1, StringSplitOptions.RemoveEmptyEntries)[0];
for (int i = 0; i < tmpCol.Split(',').Length; i++)
{
columns.Add(tmpCol.Split(',')[i]);
}
dynamic data = new ExpandoObject();
IDictionary<string, object> props = (IDictionary<string, object>)data;
foreach (var column in columns)
{
props.Add(column.ToString(), column.ToString());
}
return context.Database.SqlQuery(data.GetType(), query);
But what do I do when I want to execute the query?
context.Database.SqlQuery(data.GetType()??, query);
Even when I do put in the data.GetType() it returns empty objects.
In both examples (using typeof(object) and typeof(data.GetType()) I get this JSON object returned:
[{},{},{},{},{},{},{},{},{},{},{},{},{}]
Any ideas/suggestions?
Entity Framework populates a model based on the type specified. You'll need to use something else or go old school with a DataReader.

Get a list of API Names of all Fields for an Object.

Is it possible to get a list of all API Names for all fields on an object?
Schema.DescribeSObjectResult r =Object__c.sObjectType.getDescribe();
List<String>apiNames = new list<String>();
for(Schema.DescribeSObjectResult result : r){
apiNames.add(); //this is where I am lost.
}
You can use the fields method to get the Schema.SObjectTypeFields.
Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();
List<String>apiNames = new list<String>();
for(string apiName : r.fields.getMap().keySet()){
apiNames.add(apiName);
}
System.debug(apiNames);

Resources