error while calling the variable in a reader - c#

I have this piece of code:
while (reader.Read())
{
count++;
string Text = (String.Format("{0}", Object.Equals(Variables.buffering, reader.GetValue(0))));
List<string> mystring = new List<string>();
mystring.Add(Text);
if (Convert.ToBoolean(Text))
{
string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart, mainWindow.richtextbox2.Document.ContentEnd).Text;
var str = Regex.Replace(myText, #"( |\r?\n)\1+", "$1", RegexOptions.Multiline);
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("hello")))));
string text = "s";
mainWindow.WriteSerial(text);
Console.WriteLine(Text);
}
}
foreach (string element in mystring)
{
Console.WriteLine(element);
}
why is that the mystring in my foreach loop has an error of:
Error 2 The name 'mystring' does not exist in the current context
*This is another problem encountered. Please neglect the previous one.

I suspect that
Convert.ToBoolean(Text)
Evaluates to false
Did you step through the code in debug?
And why a Reader for a single row:
RowCount = (Int32)createCommand.ExectueScalar.ToString();

If you just want the row count, you don't have to select on a specific column. Just do this:
using(SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString))
{
sqliteCon.Open();
using(SQLiteCommand createCommand = new SQLiteCommand("SELECT COUNT(*) FROM EmployeeList", sqlliteCon))
{
createCommand.CommandType = System.Data.CommandType.Text;
int RowCount = 0;
RowCount = Convert.ToInt32(createCommand.ExecuteScalar());
}
}
Note Updated for proper use of using statements

Related

csvHelper Put values from different lines into one filed in Database

I have a .csv file structured like so, first row is the header column, for each SomeID I need to add the NetCharges together(or substract if the code calls for it) and put each item into its own column by the SomeCode column.
Heres the file I receive;
SomeID,OrderNumber,Code,NetCharge,Total
23473,30388,LI 126.0000, 132.00
96021, 000111, LI, 130.00, 126.00
23473,30388,FU 6.0000, 132.00
4571A,10452,LI,4100.0000, 4325.0000
4571A,10452,FU,150.00,4325.0000
4571A,10452,DT,75.00,4325.0000
I need to insert the data to my sql table which is structured like this. This is what I'm aiming for:
ID OrderNumber LICode LICodeValue FUCode FUCodeValue DTCode, DTCodeValue, total
23473 30388n LI 126.000 FU 6.0000 NULL NULL 132.0000
4571A 10452 LI 4100.0000 FU 150.0000 DT 75.00 4325.0000
My SomeID will not always be grouped together like the 4571A id is.I basically need to iterate over this file and create one record for each SomeID. I cannot seem to find a way with csvHelper. I'm using C# and csvHelper. I have trid this so far but I cannot get back to the SomeId after passing on to the nexr one:
using (var reader = new StreamReader( "C:\testFiles\some.csv" ))
using (var csv = new CsvReader( reader, CultureInfo.InvariantCulture ))
{
var badRecords = new List<string>();
var isRecordBad = false;
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.HeaderValidated = null;
csv.Configuration.IgnoreBlankLines = true;
csv.Configuration.Delimiter = ",";
csv.Configuration.BadDataFound = context =>
{
isRecordBad = true;
badRecords.Add( context.RawRecord );
};
csv.Configuration.MissingFieldFound = ( s, i, context ) =>
{
isRecordBad = true;
badRecords.Add( context.RawRecord );
};
List<DataFile> dataFile = csv.GetRecords<DataFile>().ToList();
//initialize variable
string lastSomeId = "";
if (!isRecordBad)
{
foreach (var item in dataFile)
{
// check if its same record
if (lastSomeId != item.SomeID)
{
MyClass someClass = new MyClass();
lastSomeId = item.SomeID;
//decimal? LI = 0;//was going to use these as vars for calculations not sure I need them???
//decimal? DSC = 0;
//decimal? FU = 0;
someClass.Id = lastSomeId;
someClass.OrdNum = item.OrderNumber;
if (item.Code == "LI")
{
someClass.LICode = item.Code;
someClass.LICodeValue = item.NetCharge;
}
if (item.Code == "DT")
{
someClass.DTCode = item.Code;
someClass.DTCodeValue = item.NetCharge
}
if (item.Code == "FU")
{
someClass.FUCode = item.Code;
someClass.FUCodeValue = item.NetCharge;
}
someClass.Total = (someClass.LICodeValue + someClass.FUCodeValue);
//check for other values to calculate
//insert record to DB
}
else
{
//Insert into db after maipulation of values
}
}
}
isRecordBad = false;
}//END Using
Any clues would be greatly appreciated. Thank you in advance.

Testing DB content, Zooming in on 1 value

I have a SQLite database that returns 1 number to
Select value from Income where symbol = "AE" and statementitem = "Revenues" and periodtype = "Annual" and yearmonth = "Dec 2019"; --1811.2
I use a bit of c# code to test this to make sure nothing is missed:
public string GetIncome(string dbFile, string symbol, string aq, string yearmonth)
{
var answer = String.Empty;
try
{
using (var con = new SQLiteConnection($"URI=file:{dbFile}"))
{
con.Open();
using var cmd = new SQLiteCommand(con)
{
CommandText = $"Select value from Income where symbol = '{symbol}' and statementitem = 'Revenues' and periodtype = '{aq}' and yearmonth = '{yearmonth}';"
};
using SQLiteDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
answer = dataReader.GetString(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
return answer;
}
This errors out with System.IndexOutOfRangeException : Index was outside the bounds of the array.
Whats the best way to pick up on that value please?
See official docs:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.data.sqlite.sqlitedatareader.getstring?view=msdata-sqlite-3.1.0#Microsoft_Data_Sqlite_SqliteDataReader_GetString_System_Int32_
It tells that GetString only argument is "The zero-based column ordinal". In your case you're trying to access second item (by index 1), but your query has only single field returned. Use index 0 in
answer = dataReader.GetString(0);

Overwriting of variable in SqlDataReader while-loop

I have read some threads that seem to be similar to this but can't find the fix for my issue, I've not used stack overflow much so pls bear with me
I have a while loop using an SqlDataReader which is pulling information from a DB and putting it into a List for Development Requests as below
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
I also have a List for getting Evaluators of the requests
public static List<SelectListItem> GetEvaluators()
{
List<SelectListItem> evaluators = new List<SelectListItem>();
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetEvaluators, Conn);
cmd.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
evaluators.Add(
new SelectListItem
{
Text = reader["Staff Name"].ToString(),
Value = reader["Staff Code"].ToString(),
});
}
Conn.Close();
return evaluators;
}
Finally I have a List that will pass the above Evaluators List in and the Evaluator that was pulled from the DB: string evaluator = reader["Evaluator"].ToString(); and will set the default value of the select list based on whether the Evaluator name matches the Text value, and set it as the selected select list item.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
if (item.Text == evaluator)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
return evaluators;
}
The issue is that the first item in the loop has the Evaluator "Bill" and "Bill" is selected, and works fine, however the second item in the loop is "John", and when it sets "John" to selected, it replaces "Bill" as the selected value in the first item with "John"
The code has ended up a mess as I have tried multiple different ways to fix but I'm stumped and would appreciate help.
Sorry if the post is formatted poorly to read, I can try to reformat and provide more information if requested.
Cheers
EDITED CODE:
GetDevRequests()
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<SelectListItem> evaluatorList = new List<SelectListItem>();
while (reader.Read())
{
string changeID = reader["ChangeID"].ToString();
string evaluator = reader["Evaluator"].ToString();
string status = reader["Status"].ToString();
string priority = reader["Priority"].ToString();
string eliteID = reader["RequestorID"].ToString();
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
ChangeID = (changeID.PadLeft(4, '0')),
Evaluator = evaluator,
Evaluators = evaluatorList,
Status = status,
Priority = priority,
EliteID = eliteID,
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
DisplayCurrentEvaluator()
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> selectListItems, string selectListDefaultItem)
{
foreach (var item in selectListItems)
{
item.Selected = item.Text == selectListDefaultItem;
}
return selectListItems;
}
The problem is in this line:
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
First, this can also be written as
List<SelectListItem> evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
Your DisplayCurrentEvaluator already returns a correct list, so there is no need to copy it into a new one.
But this is a minor point as you don't use that evaluatorList as far as I can see. In every iteration of that while-loop you are creating a new one (which probably isn't what you want) and then you forget about it. I also don't see where evaluator is set, but that is probably in code you didn't show.
So you will need to generate this list once, outside the loop and keep it (probably in a class-level field or property).
And an extra tip, that DisplayCurrentEvaluator method can also be written as
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
item.Selected = item.Text == evaluator;
}
return evaluators;
}
EDIT after code was shown that set evaluator and used the resulting evaluatorList
Your DisplayCurrentEvaluator updates the original evaluators list and returns it. This effectively results in every evaluatorList pointing to the same list, where the last update wins. So make sure you return a new list.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
var result = new List<SelectListItem>(evaluators.Count);
foreach (var item in evaluators)
{
result.Add(new SelectListItem { Text = item.Text, Value = item.Value, Selected= item.Text == evaluator};
}
return result;
}
Additionally, declare the evaluatorList (only) inside of the loop.
var evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);

Messagebox.show method not working with an int variable?

My WPF application contains a form which when loaded, obtains two variables which contain a PID (procid) and a processname (procname) of a certain process currently running on the local computer.
I have a data table which contains netstat -ano data outputs in each column. Now i will need to compare either (procid) or (procname) with the associated data contained in the datatable, if both variable matches, store the current index/row number and use that index to get the remote ip address (remoteIp) of the associated datarow to be stored as variables.
But for some reason when i try to test the variable remoteIp the messagebox does not show up or just displays nothing. Is there something wrong with my code?
Pageone.xaml.cs
public partial class Pageone : Page
{
public Pageone(MainWindow mainWindow)
{
InitializeComponent();
}
private string remoteIp;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//instantiate the MainWindow and assign it to the 'window' variable
var window = (MainWindow)Application.Current.MainWindow;
string procName = window.proc1;
int subprocPid = window.proc2;
string procPID = subprocPid.ToString();
MessageBox.Show(procPID);
using (Process ns = new Process())
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("Protocol"),
new DataColumn("Local Address"),
new DataColumn("Foreign Address"),
new DataColumn("State"),
new DataColumn("PID"),
new DataColumn("Process Name"),
});
ProcessStartInfo psi = new ProcessStartInfo("netstat.exe", "-ano");
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
ns.StartInfo = psi;
// Run it, and read the results
ns.Start();
using (StreamReader r = ns.StandardOutput)
{
string output = r.ReadToEnd();
ns.WaitForExit();
//Parse those results into a DataTable, polling the Process info
string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string line in lines)
{
string[] elements = line.Split(' ');
if (elements.Length < 5) continue;
if (elements.Contains("Proto")) continue;
DataRow dr = dt.NewRow();
List<string> validElements = new List<string>();
//Weed out empty elements.
foreach (string element in elements)
{
//skip blanks
if (element.Trim() == "") continue;
validElements.Add(element);
}
foreach (string element in validElements)
{
foreach (DataColumn dc in dt.Columns)
{
// fill in the buckets. Note that UDP doesn't have a state
if (dr["Protocol"].ToString() == "UDP" && dc.ColumnName == "State") continue;
if (dr[dc] == DBNull.Value)
{
dr[dc] = element;
break;
}
}
}
dr["Process Name"] = Process.GetProcessById(int.Parse(dr["PID"].ToString())).ProcessName;
dt.Rows.Add(dr);
}
foreach (DataRow row in dt.Rows)
{
int index = dt.Rows.IndexOf(row);
object cellprocPid = row["PID"];
object cellprocName = row["Process Name"];
object cellprocremoteIp = row["Foreign Address"];
if(cellprocPid.ToString() == procPID)
{
//MessageBox.Show(dt.Rows[index]["Process Name"].ToString());
//MessageBox.Show(index.ToString());
remoteIp = dt.Rows[index]["Foreign Address"].ToString();
}
}
}
}
MessageBox.Show(remoteIp);
}
}
It seems like the if statement condition did not match due to both of the variable having different process Id's, which resulting in the messagebox displaying nothing.

Add new value in var type with old value

i want that my variable var repFolderTree hold old value with new value .
foreach (DataRow row in _dt.Rows)
{
string strFolderData = row["ReportFolder"].ToString();
var repFolderTree = crcr.GetAllReportsHierarchical(username, strFolderData);
repFolderTree.FolderName = "All Reports";
uxAllCatalogHierarchical.Text = string.Format("<div class=\"hierarchicalCatalog\">{0}</div>", HierarchicalCatalogView(repFolderTree, 0, showFolder));
}
public CrissCrossLib.Hierarchical.CrcReportFolder GetAllReportsHierarchical(string username,string path)
{
var hierItems = GetAllReportsHierarchicalNoCache(username, path);
m_cacheManager.AllReportsHierarchicalCacheByUsername.Add(username, hierItems);
return hierItems;
}
private string HierarchicalCatalogView(CrcReportFolder rootFolder, int level, string showFolder)
{
_dt = _ssrsDAC.GetReportListByUser(Convert.ToInt32(Session["LoginID"]));
StringBuilder sb = new StringBuilder();
sb.Append("<div class=\"folderBox\">");
string scrollTo = "";
if (PathMatch(showFolder, rootFolder.Path))
scrollTo = " scrollToFolder";
sb.AppendFormat("<div class=\"folderName{1}\">{0}</div>", rootFolder.FolderName, scrollTo);
string show = "none";
if (level == 0 || PathContains(showFolder, rootFolder.Path))
show = "block";
sb.AppendFormat("<div class=\"folderChildren\" style=\"display:{0}\">", show);
foreach (CrcReportFolder subFolderLoop in rootFolder.SubFolders)
sb.Append(HierarchicalCatalogView(subFolderLoop, level + 1, showFolder));
foreach (CrcReportItem itemLoop in rootFolder.Reports)
{
string str = itemLoop.DisplayName;
DataRow[] foundAuthors = _dt.Select("ReportName = '" + str + "'");
if (foundAuthors.Length != 0)
{
sb.Append("<div class=\"reportRow\">");
sb.AppendFormat("<a class=\"reportLink vanillaHover\" href=\"Report.aspx?path={0}\" >{1}</a>",
Server.UrlEncode(itemLoop.ReportPath), itemLoop.DisplayName);
if (!string.IsNullOrEmpty(itemLoop.ShortDescription))
sb.AppendFormat("<div class=\"reportInfo\">{0}</div>", itemLoop.ShortDescription);
sb.Append("<div class=\"clear\"></div></div>");
}
}
sb.Append("</div></div>");
return sb.ToString();
}
i have a control where i am listing all the value that i am getting from
var repFolderTree = crcr.GetAllReportsHierarchical(username, strFolderData);
so every time loop after that i lost the last value and contain the current value. so i want that i can get all the value after the loop and bind on this control that i am doing in this this line of code
uxAllCatalogHierarchical.Text = string.Format("<div class=\"hierarchicalCatalog\">{0}</div>", HierarchicalCatalogView(repFolderTree, 0, showFolder));
i think my code make some scene for you .
you can use List or Collection to store all the values , with Add operation to add the var value.
List<object> repFolderTree = new List<object>();
foreach (DataRow row in _dt.Rows)
{
string strFolderData = row["ReportFolder"].ToString();
var repFolderTree = crcr.GetAllReportsHierarchical(username, strFolderData);
repFolderTree .Add(repFolderTree );
repFolderTree.FolderName = "All Reports";
uxAllCatalogHierarchical.Text = string.Format("<div class=\"hierarchicalCatalog\">{0}</div>", HierarchicalCatalogView(repFolderTree, 0, showFolder));
}

Categories