Using Params in function like this C# is it a good practice - c#

FUNCTION **
private void GetComboxItems(params int[] type)
{
try
{
/* DEPARTMENT CODE */
if (type[0] == 1)
{
cmbDept.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var Dept = (from i in SFC.Systems_SettingsDepartments
orderby i.Department_ID
select i);
foreach (var q in Dept)
{
cmbDept.Items.Add(q.Department_ID);
}
SFC.Connection.Close();
}
}
/* CORRECTIVE ACTION RECORD CODE */
if (type[1] == 1)
{
cmbCARNo.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var CarNo = (from i in SFC.Systems_CARLogSheets
orderby i.CARDocNo
where i.PostStatus == 0
select new
{
Code = i.CARDocNo
});
foreach (var w in CarNo)
{
cmbCARNo.Items.Add(w.Code);
}
SFC.Connection.Close();
}
}
/* MEASUREMENT CODE */
if (type[2] == 1)
{
cmbMeas.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var Measure = (from i in SFC.Systems_SettingsMeasurements
orderby i.Measurement_ID
where i.CategoryType == "Measurement"
select new
{
DESC = i.Measurement
});
foreach (var e in Measure)
{
cmbMeas.Items.Add(e.DESC);
}
SFC.Connection.Close();
}
}
/* SUB-MEASUREMENT CODE */
if (type[3] == 1)
{
cmbSubMeas.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var SubMeas = (from i in SFC.Systems_SettingsMeasurements
orderby i.Measurement_ID
where i.CategoryType == "Sub-Measurement"
select new
{
DESC = i.Measurement
});
foreach (var r in SubMeas)
{
cmbSubMeas.Items.Add(r.DESC);
}
SFC.Connection.Close();
}
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message.ToString()); }
}
* FORM LOAD **
private void frmSQMProductivityReports_Load(object sender, EventArgs e)
{
GetComboxItems(1, 0, 1, 0);
}
why is it that at this code.. my 1st if statement is "True" so it does what follows the code inside the if statement and it does. now the 2nd if statement is "False" which it skips the function inside it. but then now the 3rd if statement is "True" which is it should have do same as the 1st but as i have checked couple times it skips the function inside the if statement why is it? is there something wrong in my codes i tried looking at it its seems ok to me..

According to your input, the if conditions that meets the criteria are the first and the third.. note that some statements can be "skipped" if an exception is throw, so placing breakpoints there or printing logs may help you understand better what is happening.
Side notes:
The use of params seems to be redundant in this case (it's mostly used when an unknown #arguments should be passed) since the number of arguments is fixed.
use bool type rather then int for flags

Related

LINQ TO SQL: Detect existing data

I need LINQ code to be able to detect if an entry is input but the datum already exists in the table.
public Boolean CheckAssessment(String assessmentName)
{
{
SQL_TA_SCOREBOARDEntities1 d = new SQL_TA_SCOREBOARDEntities1();
Assessment A_List = new Assessment();
{
var qry2 = from b in contxt.View_Assessment
where b.AssessmentName == assessmentName
select b;
if (qry2 = assessmentName.ToString())
{
return true;
}
else
{
return false;
}
}
}
}
Where assessmentName is the value of the textbox in the a separate C# class.
Boolean i;
i = TAClass.CheckAssessment(txtAssessmentName.ToString());
if (i == true)
{
Label2.Text = "Assessment name already exists.";
}
The correct way is to use Any() extension method. Any() will generate optimized query and will return true as soon as the query found the record.
http://msdn.microsoft.com/en-us/library/bb534338.aspx
So, in your CheckAssessment method, you can do like this:
return (from b in assessments
where b.AssessmentName == assessmentName
select b).Any();
Use the Count() extension to check if there are any matching records:
public bool CheckAssessment(string assessmentName)
{
return (from b in contxt.View_Assessment
where b.AssessmentName == assessmentName
select b).Count() > 0;
}
UPDATE: just for your knowledge, your code could work this way:
public Boolean CheckAssessment(String assessmentName)
{
{
SQL_TA_SCOREBOARDEntities1 d = new SQL_TA_SCOREBOARDEntities1();
Assessment A_List = new Assessment();
{
var qry2 = (from b in contxt.View_Assessment
where b.AssessmentName == assessmentName
select b.AssessmentName).FirstOrDefault();
if (qry2 = assessmentName.ToString())
{
return true;
}
else
{
return false;
}
}
}
}
Just one more comment, always that you have something like:
if (a) { return true; } else {return false;}
you can replace by
return a;

Passing properties to a function (only get property error)C#

I have a class thats receive all crystal report req to open the form of the report(a switch and a lot of cases).
and i need to copy and paste every time this code
if (sender.GetType() == typeof(CheckBox))
{
foreach (CheckBox elemento in flowLayoutPanel1.Controls.OfType<CheckBox>())
{
if (elemento.Checked)
{
foreach (string elemento2 in ListaTodos)
{
string Name = elemento.Tag.ToString();
if (Name.Substring(Name.Length - 1, 1) == elemento2.Substring(elemento2.Length - 1, 1))
{
crParceiro.ReportDefinition.ReportObjects[Name].ObjectFormat.EnableSuppress = false;
crParceiro.ReportDefinition.ReportObjects[elemento2].ObjectFormat.EnableSuppress = false;
}
}
}
else
{
foreach (string elemento2 in ListaTodos)
{
string Name = elemento.Tag.ToString();
if (Name.Substring(Name.Length - 1, 1) == elemento2.Substring(elemento2.Length - 1, 1))
{
crParceiro.ReportDefinition.ReportObjects[Name].ObjectFormat.EnableSuppress = true;
crParceiro.ReportDefinition.ReportObjects[elemento2].ObjectFormat.EnableSuppress = true;
}
}
}
}
}
Problem: i created a function and triend to paste this part of code there... and i passed the crParceiro.ReportDefinition, and also crParceiro.ReportDefinition.ReportsObject
but it doesnt have the set property and i cant set it out and return on REF our OUT...
I tried to Return the value and Linq Expressions(it says..."object doesnt have set property") no success
**Reference of Linq Exp and Return Value: **Link here
A good example of the problem are:
ReportDefinition teste = new ReportDefinition();
teste.ReportObjects = null;
//Error: Property or idexer ...cannot be assigned to -- its read only.
what can i do? im very lost..
In the code that you posted you are NOT setting the ReportObjects to null or any other value. You are accesing items of the ReportObjects by index and changing properties of these items but not direcctly on the ReportObjects
So this should work.
private void YourMethod(ReportObjects repObjs, List<string> ListaTodos)
{
foreach (CheckBox elemento in flowLayoutPanel1.Controls.OfType<CheckBox>())
{
bool enableSuppress ;
//enableSuppress changes based on the the "elemento" being checked or not
enableSuppress = !elemento.Checked ;
foreach (string elemento2 in ListaTodos)
{
string Name = elemento.Tag.ToString();
if (Name.Substring(Name.Length - 1, 1) == elemento2.Substring(elemento2.Length - 1, 1))
{
repObjs[Name].ObjectFormat.EnableSuppress = enableSuppress;
repObjs[elemento2].ObjectFormat.EnableSuppress = enableSuppress;
}
}
}
}
Then in your current call you use it like this
if (sender.GetType() == typeof(CheckBox))
{
YourMethod(crParceiro.ReportDefinition.ReportObjects, ListaTodos) ;
}

ObjectListView's TreeListView cell editing very very slow

I am using a TreeListView (ObjectListView) http://objectlistview.sourceforge.net/cs/index.html - and populated it with a number of items. One of the columns I made editable on double click for user input. Unfortunately, the editing is extremely slow and going from one cell edit in the Qty column (see picture further below) to the next cell edit takes about 5-10 seconds each time. Also, the cell editor takes a while to appear and disappear. Below is the code I use to populate the TreeListView:
TreeListView.TreeRenderer renderer = this.treeListView.TreeColumnRenderer;
renderer.LinePen = new Pen(Color.Firebrick, 0.5f);
renderer.LinePen.DashStyle = DashStyle.Solid;
renderer.IsShowLines = true;
treeListView.RowFormatter = delegate(OLVListItem olvi)
{
var item = (IListView)olvi.RowObject;
if (item.ItemType == "RM")
olvi.ForeColor = Color.LightSeaGreen;
};
treeListView.CanExpandGetter = delegate(object x)
{
var job = x as IListView;
if (job != null)
{
if (job.ItemType == "PA" || job.ItemType == "JC")
{
var rm = job.ItemPart.GetRawMaterial();
var subParts = job.ItemPart.SubParts.Where(v => v != null).ToList();
if (rm.Count > 0|| subParts.Count > 0)//
return true;
}
}
return false;
};
this.treeListView.ChildrenGetter = delegate(object x)
{
try
{
var job = x as IListView;
if (job != null)
{
if (job.ItemType == "PA" || job.ItemType == "JC")
{
var part = job.ItemPart;
var rm = part.GetRawMaterial();
var subParts = part.SubParts.Where(v => v != null).ToList();
var items = new List<IListView>();
items.AddRange(subParts.GetRange(0, subParts.Count).ToList<IListView>());
items.AddRange(rm.GetRange(0, rm.Count).ToList<IListView>());
return items;
}
}
return null;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(this, ex.Message, "ObjectListViewDemo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return null;
}
};
var lItems= jobs.ToList<IListView>();
treeListView.SetObjects(lItems );
Expand(lItems[0]);
treeListView.RebuildAll(true);
}
public void Expand(object expItem)
{
treeListView.ToggleExpansion(expItem);
foreach (var item in treeListView.GetChildren(expItem))
{
Expand(item);
}
}
Here is a picture of the cell editing:
Why is the editing so very slow? Am I doing something wrong? What can I do to make it faster?
In your delegates you're using linear searches and several list copies (also linear). And this is for each item.
Bad performance is to be expected.
If you want to improve on this, you can pre-calculate the results instead.

C# SQLite and SQL commands Specified cast not valid

I'm playing around with SQlite and sql commands. I'm trying to make a quizz program and I have a loop, that reads the questions and answers from my database and adds them to a list. I also have a bool that defines if the answer picked from the database is right or wrong.
My problem is that all this works fine the first time my loop executes the code and adds the true and false to my array of bools, but the 2'nd time my loop executes it throws the exception: SPECIFIED CAST NOT VALID. The method that fails looks like this: I made a comment where the code fails:
public void GetQuestion(int categoryRef)
{
Console.Clear();
int arrayIndex = 0;
int qListIndex = 0;
int idListIndex = 0;
List<string> qList = new List<string>();
List<int> idList = new List<int>();
int ansNr = 1;
bool[] isTrue = new bool[3];
SQLiteDataReader sqReader;
SQLiteCommand sqCommand = new SQLiteCommand(sqConnection);
try
{
sqCommand.CommandText = "SELECT Question, ID FROM Questions WHERE CategoryRef=" + categoryRef.ToString();
sqCommand.Connection.Open();
sqReader = sqCommand.ExecuteReader();
foreach (var item in sqReader)
{
qList.Add(sqReader.GetString(0));
idList.Add(sqReader.GetInt32(1));
}
sqReader.Close();
}
finally
{
sqConnection.Close();
}
for (int i = 0; i < qList.Count; i++)
{
try
{
sqCommand.CommandText = "SELECT Answer FROM Answers WHERE QuestionRef=" + idList[idListIndex].ToString();
sqConnection.Open();
sqReader = sqCommand.ExecuteReader();
Console.WriteLine(qList[qListIndex]);
foreach (var answer in sqReader)
{
Console.WriteLine(ansNr + ":" + sqReader.GetString(0));
ansNr++;
}
sqReader.Close();
}
finally
{
sqConnection.Close();
}
try
{
//THIS CODE FAILS 2'nd TIME IT LOOPS THROUGH
sqCommand.CommandText = "SELECT IsTrue FROM Answers WHERE QuestionRef=" + idList[idListIndex].ToString();
sqConnection.Open();
sqReader = sqCommand.ExecuteReader();
foreach (var item in sqReader)
{
isTrue[arrayIndex] = sqReader.GetBoolean(0); //<-- Specified cast is not valid.
arrayIndex++;
}
sqReader.Close();
}
finally
{
sqConnection.Close();
}
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
switch (number)
{
case 1:
if (isTrue[0] == true)
{
Console.WriteLine("Correct");
}
if (isTrue[0] == false)
{
Console.WriteLine("False");
}
break;
case 2:
if (isTrue[1] == true)
{
Console.WriteLine("Correct");
}
if (isTrue[1] == false)
{
Console.WriteLine("False");
}
break;
case 3:
if (isTrue[2] == true)
{
Console.WriteLine("Correct");
}
if (isTrue[2] == false)
{
Console.WriteLine("False");
}
break;
}
Console.ReadLine();
idListIndex++;
qListIndex++;
arrayIndex = 0;
ansNr = 1;
}
}
Mostly likely, that you read DbNull from database, which cannot be cast to bool.
SQLite does not guarantee that the contents of any column will match the cast.
The GetBoolean is failing. You have 3 choices.
Try Catch
Test for Null
Replace your select with a query guaranteed to return true/false
SQLite version 3.7.8 2011-09-19 14:49:19
sqlite> CREATE TABLE Q (A);
sqlite> INSERT INTO Q VALUES (0);
sqlite> INSERT INTO Q VALUES (1);
sqlite> INSERT INTO Q VALUES ('T');
sqlite> INSERT INTO Q VALUES ('F');
sqlite> INSERT INTO Q VALUES ('Y');
sqlite> INSERT INTO Q VALUES (NULL);
sqlite> SELECT not ifnull(A==0 OR A=='F' OR A=='N',1) FROM Q;
0
1
1
0
1
0
In my case, EF was throwing the same error ("Specified cast not valid") because it couldnt resolve "1234" that SQLite was throwing at it.
The solution was to change the type of Name field from STRING to TEXT.
I was getting the same error because SQLite was returning a NULL.
Check for null: if (!sqlite_datareader.IsDBNull(4))
{// then do what is required}

How to know whether there is a round has been caused by parents (A=>B=>C=>A)

I have the following structure:
[Employee]
ID
Manager1ID
Manager2ID
Scenario:
I want to make a validation to ensure that the chosen Manager1 or Manager2 does not cause a round. In other words, I want to know whether this case exists:
The manager of A is B & the manager of B is C and the manger of C is also A // not valid
A => B => C => A
To tell the user that A is not a valid manager for C because C is already a manager of A
.
The problem:
I though of checking in a while loop the managers as parents in a tree, and when I found the chosen manager in the list I know that it is not valid. (Two loops for tow lists for Manager1 and Manager2)
The problem is that every employee might have two managers and a round maybe exists in a case like this:
A => B (Manager1) => C (Manager2) => A
Which is not able to check in my suggested solution.
Any idea!
You try to find a cycle in a directed graph.
starting from the employee in question, do a breadth first search on the set of managers and keep accumulating the list of managers you come across in a list. Each time you add an entry to the list, check if it would create a duplication. If it would, it means you have reached the condition you wanted to check for. Keep continuing this process until you either hit a duplication condition or you reach a node which does not have managers
Use a recursive function:
List<Employee> lineage = new List<Employee>();
Validate(theUser, lineage);
public void Validate(Employee employee, List<Employee> lineage)
{
if (lineage.Contains(employee))
throw new InvalidOperationException("Circular graph");
lineage.Add(employee);
if (employee.Manager != null)
Validate(employee.Manager, lineage)
}
I have provided a complete generic solution for n number of reportees which is more logical than reportees. If you like to rename reportees to managers, you can do so.
You can modify the traversal to suit your needs. I have tested this with cycle and without cycle. It seems to work fine. Let me know if this works for you.
using System;
using System.Collections.Generic;
namespace GenericDictionary
{
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee("Employee", null);
Employee manager = new Employee("Manager", employee);
Employee CEO = new Employee("CEO", manager);
CEO.AddReportee(new Employee("Manager2", employee));
// Uncomment this line to see exception in action
// employee.AddReportee(CEO);
try
{
CEO.DisplayReportees();
}
catch (InvalidOperationException ex)
{
Console.WriteLine();
Console.WriteLine("***** Exception: " + ex.Message + " *****");
}
Console.ReadLine();
}
public class Employee
{
public List<Employee> Reportees { get; private set; }
public string Name { get; private set; }
public Employee(string name, Employee reportee)
{
this.Reportees = new List<Employee>();
this.Name = name;
this.Reportees.Add(reportee);
}
public void AddReportee(Employee reportee)
{
Reportees.Add(reportee);
}
int indentationCount = 0;
List<Employee> traversedNodes = new List<Employee>();
void DisplayReportees(Employee employee)
{
traversedNodes.Add(employee);
for (int i = 0; i < indentationCount; i++)
Console.Write(" ");
Console.WriteLine(employee.Name);
indentationCount = indentationCount + 3;
foreach (Employee reportee in employee.Reportees)
{
if (AlreadyTraversed(reportee))
throw new InvalidOperationException("Circular graph at node " + reportee.Name);
if (reportee != null)
DisplayReportees(reportee);
}
indentationCount = indentationCount - 3;
traversedNodes.Remove(employee);
}
bool AlreadyTraversed(Employee employee)
{
return traversedNodes.Contains(employee);
}
public void DisplayReportees()
{
DisplayReportees(this);
}
}
}
}
Use the following recursive function:
Boolean CheckManagers(Employee emp)
{
if ((emp.Manager1ID.HasValue && emp.Manager1ID == emp.ID) ||
(emp.Manager2ID.HasValue && emp.Manager2ID == emp.ID)) return false;
return
(
(!emp.Manager1ID.HasValue || (emp.Manager1ID.HasValue && CheckManagers((Employee) emp.Manager1)) &&
(!emp.Manager2ID.HasValue || (emp.Manager2ID.HasValue && CheckManagers((Employee) emp.Manager2))
);
}

Categories

Resources