looping through data table to get specifics values from each row - c#

when looping through this datatable im unable to use the stored values in an if else statement i get the following error
The system cannot execute the specified program.
what i expected to happen is the if else block to check the toValue and go from there
ps - a continuation from a prior question looping thru datatable values
edit* added the full code block for clarity
string conString = "user id =user1; password =password;" + "data source = database.home.org";
OracleConnection con = new OracleConnection
{
ConnectionString = conString
};
con.Open();
var pullRecord = new OracleCommand("select * FROM email_records", con);
var dt= new DataTable();
var da = new OracleDataAdapter(pullRecord);
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string toValue = (dt.Rows[x].ItemArray[0].ToString() + " ");
string ccValue = (dt.Rows[x].ItemArray[1].ToString() + " ");
string bodyValue = (dt.Rows[x].ItemArray[4].ToString() + " ");
if(toValue == "one" || toValue == "two" || toValue == "three")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "four" || toValue == "five")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "six" || toValue == "seven")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "eight" || toValue == "nine")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "ten" || toValue == "eleven")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "twelve")
{
Console.WriteLine(bodyValue);
}
else if (toValue == "thirteen")
{
Console.WriteLine(bodyValue);
}
else
{
Console.WriteLine(bodyValue);
}
}

Related

What is the value of arg in Task.Factory.StartNew

I have Task.Factory.StartNew in C# code with args argument. I am not quite understand what value will arg be. So what value will args be and how the value is determined?
int count = table.Rows.Count;
Dictionary<int, string> expDic = new Dictionary<int, string>();
List<Task> taskList = new List<Task>();
for (int f = 0; f < count; f++)
{
DataRow tempformula = table.Rows[f];
string formulaSymbol = Convert.ToString(tempformula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
var t = Task.Factory.StartNew(new Action<object>((args) => {
int i = (int)args;
_sem.Wait();
StringBuilder expression = new StringBuilder(1024);
DataRow formula = table.Rows[i];
int indID = Convert.ToInt32(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.IndicatorID]);
int sequence = Convert.ToInt32(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.Sequence]);
int? referenceIndID = Common.Util.TryToConvertToInt32(formula, Common.Systems.Sustainability.Constants.IndicatorFormula.ReferenceIndicatorID);
decimal? val = Common.Util.TryToConvertToDecimal(formula, Common.Systems.Sustainability.Constants.IndicatorFormula.Value);
string symbol = Convert.ToString(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
string formulaOutputUnit = Convert.ToString(formula[Common.Systems.Sustainability.Constants.Indicator.Unit]);
if (!string.IsNullOrWhiteSpace(callerAcceptedUnit)) // added by HC on 2016-05-27
{
formulaOutputUnit = callerAcceptedUnit;
}
if (referenceIndID == null)
{
if (val == null)
{
DataSet indicator = GetIndicatorByIDFromCache(companyID, indID); // added by HC on 2017-05-12, for performance tuning.
//using (DataSet indicator = indicatorMgr.GetIndicatorByID(companyID, indID))
{
DataRow dr = indicator.Tables[0].Rows[0];
int indicatorType = Convert.ToInt32(dr[Common.Systems.Sustainability.Constants.Indicator.IndicatorType]);
if (indicatorType == (int)Common.Systems.Sustainability.Constants.IndicatorTypes.Currency
|| indicatorType == (int)Common.Systems.Sustainability.Constants.IndicatorTypes.Numeric)
{
decimal? total = SumTotal(companyID, indID, indicatorType, fromDate, toDate, formulaOutputUnit, callerIndicatorID, breakToMonthly, specifiedLocations, approvalStatus
, usageDataSet, interval
, indicatorIDsChain
, allowNull
);
expression.Append(total.ToString());
}
else if (symbol == "+"
|| symbol == "-"
|| symbol == "*"
|| symbol == "/")
{
expression.Append(symbol);
}
}
}
else
{
expression.Append(val.ToString());
}
}
else
{
string exp = GetExpression(companyID, fromDate, toDate, referenceIndID.Value.ToString(), indID.ToString(), formulaOutputUnit, breakToMonthly, specifiedLocations, approvalStatus
, usageDataSet, interval
, indicatorIDsChain
);
//expression.Append(exp);
using (DataTable dt = new DataTable())
{
// fault tolerance, for in-case users assigned symbol in the last line of formula
if (exp.EndsWith("+")
|| exp.EndsWith("-")
|| exp.EndsWith("*")
|| exp.EndsWith("/"))
{
exp = exp.Substring(0, exp.Length - 1);
}
object result = dt.Compute(exp, "");
expression.Append(result);
}
} // end if (referenceIndID == null)...
if ("IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "THEN".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "ELSE IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "ELSE".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| ">".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| ">=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "<=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "<".Equals(symbol, StringComparison.OrdinalIgnoreCase)
)
{
//--------------------------------------------------------
// Begin, added by HC on 2016-12-14
// as requested by CQS users, add "IF" statement for GRI indicators
string exp = HandleIFCondition(table, i, companyID, fromDate, toDate, indicatorIDs, callerIndicatorID, callerAcceptedUnit, breakToMonthly, specifiedLocations, approvalStatus, usageDataSet, interval, indicatorIDsChain);
expression.Append(exp);
// End, added by HC on 2016-12-14
//--------------------------------------------------------
// Find End if, added by Alex Poon on 20190306
int ifIndex = i;
for (var j = ifIndex; j < count; j++)
{
string endIfSymbol = Convert.ToString(table.Rows[j][Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
if ("END IF".Equals(endIfSymbol, StringComparison.OrdinalIgnoreCase))
{
i = j;
break;
}
}
}
else
{
if (!string.IsNullOrWhiteSpace(symbol)
&& expression.Length > 0 // added by HC on 2016-06-24
)
{
if (i + 1 >= count && symbol != ")")
{
// ignore the symbol
}
else if (expression.ToString() != symbol)
{
expression.Append(symbol);
}
}
else if (expression.Length == 0 && symbol == "(")
{
expression.Append(symbol);
}
if (symbol == "days")
{
// added by HC on 2017-01-23, a new requirements for calculating average values by days.
if (fromDate != null && toDate != null)
{
int days = toDate.Value.Subtract(fromDate.Value).Days + 1;
expression.Append(days);
}
else
{
expression.Append(1);
}
}
} // end if ("IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)...
if (expDic != null && expression != null)
{
expDic.Add(i, expression.ToString());
}
_sem.Release();
}), f);
taskList.Add(t);
if ("IF".Equals(formulaSymbol, StringComparison.OrdinalIgnoreCase))
{
for (var j = f; j < count; j++)
{
string endIfSymbol = Convert.ToString(table.Rows[j][Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
if ("END IF".Equals(endIfSymbol, StringComparison.OrdinalIgnoreCase))
{
f = j;
break;
}
}
}
}
Task.WaitAll(taskList.ToArray());
List<int> keys = expDic.Keys.ToList();
keys.Sort();
string finalExpression = "";
foreach (var key in keys)
{
finalExpression += expDic[key];
}
return finalExpression;
}
args in your case is data that will be passed to a delegate specified by Action<object> parameter.
See docs.
When using overload of StartNew with Action<object>, you need to supply next argument of type object, which will be used in passed delegate.
Task.Factory.StartNew((o) => {/* 1 will be used here */}, 1, token, options, scheduler);
MSDN
The args argument (referred to as "state" in the documentation) is a parameter you need to specify when you call to Task.Factory.StartNew.
state (Object): An object containing data to be used by the action delegate.
Sample:
object param = somevalue;
Task.Factory.StartNew( (arg) =>
{ /* get the arg value here.*/
}, param);

Looping datatable for assigning values to a string

I have a gridview, in which there are multiple columns and rows.
While debugging it generates datatable as below
and its query is
DataTable dttable2 = new DataTable();
dttable2 = CF.ExecuteDT("select cr.Mkey, cr.Rating1,cr.Rating2,cr.Rating3,cr.Rating4 from p_emp_Company_Rating cr "+
"join p_emp_Exit_Interview ei on ei.Mkey=cr.Mkey where ei.mkey='" + HidMKey.Value + "'");
I want to loop it as much as it contains rows.
I tried with below code but it is going once and coming out.
string strgrid1 = string.Empty;
if (dttable2.Rows.Count > 0)
{
/** Job security **/
if (dttable2.Rows[0]["Rating1"].ToString() == "Y")
{
strgrid1 = "Poor";
}
if (dttable2.Rows[0]["Rating2"].ToString() == "Y")
{
strgrid1 = "Satisfactory";
}
if (dttable2.Rows[0]["Rating3"].ToString() == "Y")
{
strgrid1 = "Good";
}
if (dttable2.Rows[0]["Rating4"].ToString() == "Y")
{
strgrid1 = "Excellent";
}
}
Below is screenshot of the gridview
how to loop it ?
Try a foreach loop instead of an if statement.
string strgrid1 = string.Empty;
foreach (DataRow row in dttable2.Rows)
{
/** Job security **/
if (row["Rating1"].ToString() == "Y")
{
strgrid1 = "Poor";
}
if (row["Rating2"].ToString() == "Y")
{
strgrid1 = "Satisfactory";
}
if (row["Rating3"].ToString() == "Y")
{
strgrid1 = "Good";
}
if (row["Rating4"].ToString() == "Y")
{
strgrid1 = "Excellent";
}
}
You can also try For Loop to achieve desired results.
string strgrid1 = string.Empty;
if (dttable2.Rows.Count > 0)
{
/** Job security **/
for(int i = 0; i < dttable2.Rows.Count - 1; i++)
{
if (dttable2.Rows[i]["Rating1"].ToString() == "Y")
{
strgrid1 = "Poor";
}
if (dttable2.Rows[i]["Rating2"].ToString() == "Y")
{
strgrid1 = "Satisfactory";
}
if (dttable2.Rows[i]["Rating3"].ToString() == "Y")
{
strgrid1 = "Good";
}
if (dttable2.Rows[i]["Rating4"].ToString() == "Y")
{
strgrid1 = "Excellent";
}
}
}

Update table using linq

I want to update table but its not working
Here is the code:
public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
string sectionames = "";
Transcription_Master Trans_Mastr = new Transcription_Master();
try
{
var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == Trans_ID && Trans_Mast.Entity_Id == Job_ID select new
{
Trans_Mast.Completed_Trans_Sections
}).Distinct().ToList();
var complt_trans = Trans_Master.AsEnumerable().Where(dr = > dr.Completed_Trans_Sections != null).ToList();
if (complt_trans.Count == 0)
{
if (sectionames == "")
{
Trans_Mastr.Completed_Trans_Sections = SectioName;
}
}
else
{
Trans_Mastr.Completed_Trans_Sections = "," + SectioName;
}
int sc = r2ge.SaveChanges();
}
}
It does not update database..what is wrong in it??
You should change this piece of code to such a thing:
var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master
where Trans_Mast.Transcription_Id == Trans_ID
&& Trans_Mast.Entity_Id == Job_ID
select Trans_Mast).Distinct().ToList();
In this case Your variable Trans_Maser will be refference to object from collection, so changes will be done on object taken from EF context, and SaveChanges will give correct result.
Solved my own problem Transcription_Master Trans_Mastr = new Transcription_Master(); no need to create new object
public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
string sectionames = "";
try
{
var empQuery = r2ge.Transcription_Master.Where(l => l.Transcription_Id == Trans_ID && l.Entity_Id == Job_ID).ToList();
foreach (Transcription_Master Trans_Mastrr in empQuery)
{
if (empQuery.Count == 0)
{
if (sectionames == "")
{
Trans_Mastrr.Completed_Trans_Sections = SectioName;
}
}
else
{
Trans_Mastrr.Completed_Trans_Sections = Trans_Mastrr.Completed_Trans_Sections + "," + SectioName;
}
}
int sc = r2ge.SaveChanges();
}

Linq Select Statement help needed - NullReferenceException after using FirstOrDefault

I have a LINQ statement handling the Login process. It works fine when passed valid username and password combinations. However when I test on invalid credentials, I get a NullReferenceException error on the line below indicated by <<<---------------- Need some help on proper handling of invalid credentials please?
public int _accountID;
public int _securityLevelID;
public void GetLoginInfo(string EmailAddress, string Password)
{
LoginItem l = null;
{
try
{
using (RootsDataContext RDC = new RootsDataContext())
l = (from a in RDC.DBLogIns
where a.EmailAddress == EmailAddress
&& a.Password == Password
&& a.IsActive == 1
select new LoginItem
{
AccountIDFK = a.AccountIDFK,
SecurityLevelIDFK = a.SecurtityLevelIDFK,
}).FirstOrDefault();
_accountID = (int)l.AccountIDFK; <<<----------------
_securityLevelID = (int)l.SecurityLevelIDFK;
if (_accountID < 1 || _accountID == null)
{
lbl_LoginStatus.Text = "Invalid";
}
}
catch (Exception ex)
{
string error = ex.Message;
}
if (_accountID > 0)
{
if (_accountID == 1 && _securityLevelID == 1) // [Quentin]
{
Response.Redirect("~/AccountsMaster.aspx");
}
if (_accountID > 1 && _securityLevelID == 2) // [Companies]
{
Response.Redirect("~/CompanyMaster.aspx");
}
if (_accountID > 1 && _securityLevelID == 3) // [Branch]
{
Response.Redirect("~/BranchMaster.Aspx");
}
if (_accountID > 1 && _securityLevelID == 4) // [Clients]
{
Response.Redirect("~/Home.aspx");
}
}
}
}
By saying
// ...
}).FirstOrDefault();
You will either get an DBLogIn object if a match is found, or null if it is not.
You will need to check for null before accessing the property AccountIDFK and SecurityLevelIDFK:
// ... }).FirstOrDefault();
if (l != null)
{
_accountID = (int)l.AccountIDFK;
_securityLevelID = (int)l.SecurityLevelIDFK;
}
Some other points to consider:
You shouldn't store passwords directly in the database. A more secure approach is to store hashed (and potentially salted) passwords in the database, and then to find the user (by EmailAddress and Active = 1), and then compare the hashes of what the user typed, and what is stored in the DB.
This code swallows exceptions - this makes diagnosing problems a nightmare:
catch (Exception ex)
{
string error = ex.Message;
}
Don't make fields public (public int _accountID;) - Make them private if they are not used externally, or convert them to (autogenerated) Properties if they are externally visible from your class.
FirstOrDefault method will return null if there's no DBLogIn records match the criteria you give, so you need to check if l is null first before accessing (int)l.AccountIDFK. Moreover, it looks like lbl_LoginStatus.Text = "Invalid"; should be done when l is null, so you need to remove if (_accountID < 1 || _accountID == null) block and change your code as follows:
if (l != null)
{
_accountID = (int)l.AccountIDFK;
_securityLevelID = (int)l.SecurityLevelIDFK;
}
else
{
// logic when l is null
lbl_LoginStatus.Text = "Invalid";
}
Alternatively you can also use C# Ternary Operator to check if l is null
_accountID = l != null ? (int)l.AccountIDFK : 0;
_securityLevelID = l != null ? (int)l.SecurityLevelIDFK : 0;
if (_accountID < 1)
{
lbl_LoginStatus.Text = "Invalid";
}
You should check for null value in 'l' before using it.
if(l!=null)
{
_accountID = (int)l.AccountIDFK;
_securityLevelID = (int)l.SecurityLevelIDFK;
}
else
{
lbl_LoginStatus.Text = "Invalid";
}
Linq FirstOrDefault returns null if there is no item in the list matching your query.So if you get null in your code means that user login is invalid.
public int _accountID;
public int _securityLevelID;
public void GetLoginInfo(string EmailAddress, string Password)
{
LoginItem l = null;
{
try
{
using (RootsDataContext RDC = new RootsDataContext())
l = (from a in RDC.DBLogIns
where a.EmailAddress == EmailAddress
&& a.Password == Password
&& a.IsActive == 1
select new LoginItem
{
AccountIDFK = a.AccountIDFK,
SecurityLevelIDFK = a.SecurtityLevelIDFK,
}).FirstOrDefault();
if(l==null || _accountID < 1 || _accountID == null)
{
lbl_LoginStatus.Text = "Invalid";
Response.Redirect("~/InvalidCredentials.aspx"); // redirect to invalid login page.
}
else
{
_accountID = (int)l.AccountIDFK;
_securityLevelID = (int)l.SecurityLevelIDFK;
}
}
catch (Exception ex)
{
string error = ex.Message;
}
if (_accountID > 0)
{
if (_accountID == 1 && _securityLevelID == 1) // [Quentin]
{
Response.Redirect("~/AccountsMaster.aspx");
}
if (_accountID > 1 && _securityLevelID == 2) // [Companies]
{
Response.Redirect("~/CompanyMaster.aspx");
}
if (_accountID > 1 && _securityLevelID == 3) // [Branch]
{
Response.Redirect("~/BranchMaster.Aspx");
}
if (_accountID > 1 && _securityLevelID == 4) // [Clients]
{
Response.Redirect("~/Home.aspx");
}
}
}
}
You should have a check for LoginItem's default value null, and if its null (in case of invalid credentials) then do whatever you want.

How do I add multiple optional parameters to linq query

I Have to check and add the optional parameter in function but its taking lengthy code to go through IF-Else statement, If I choose switch statement then Cannot convert 'var' variable to string error keep coming up, How do I check and add optional parameters to linq query please help. Here is my code. (I will provide both the one with If statement and other one with switch statement which is throwing error)
Code 1 If-else statement:
public static void loadGrid(ref GridView gvMain, string cID, string desig = "All", string importancy = "All", string status = "All")
{
int _cId = Convert.ToInt32(cID);
List<clsclass> list = new List<clsclass>();
var db = new MyEntities();
if (_cId == 0 && desig == "All" && importancy == "All" && status == "All")
{
var query = from table in db.Members select table;
list.Clear();
foreach (var item in query)
{
clsclass ctl = new clsclass();
ctl.Id = Convert.ToInt32(item.LID);
ctl.Name = item.FirstName + " " + item.LastName;
ctl.Gender = item.Gender;
ctl.Age = Convert.ToInt32(item.Age);
ctl.Mobile = item.Mobile;
ctl.Workphone = item.WorkPhone;
ctl.Designation = item.Designation;
ctl.Importancy = item.Importancy;
list.Add(ctl);
}
}
else if (_cId != 0 && desig == "All" && importancy == "All" && status == "All")
{
var query = from table in db.Members where table.CID == _cId select table;
list.Clear();
foreach (var item in query)
{
clsclass ctl = new clsclass();
ctl.Id = Convert.ToInt32(item.LID);
ctl.Name = item.FirstName + " " + item.LastName;
ctl.Gender = item.Gender;
ctl.Age = Convert.ToInt32(item.Age);
ctl.Mobile = item.Mobile;
ctl.Workphone = item.WorkPhone;
ctl.Designation = item.Designation;
ctl.Importancy = item.Importancy;
list.Add(ctl);
}
}
//AND SO ON I HAVE TO CHECK THE OPTIONAL PARAMETERS......
//else if()
//{
//}
}
And In below code If I try to use switch statement to bind query based condition its throwing error:
Code 2:Switch statement:
public static void LoadGrid(ref GridView gvMain, string cID, string desig = "All", string importancy = "All", string status = "All")
{
int _cId = Convert.ToInt32(cID);
List<clsclass> list = new List<clsclass>();
var db = new MyEntities();
var query;
switch (query)
{
case _cId == 0 && desig == "All" && importancy == "All" && satus == "All":
query = from b in db.ConstituencyLeaders select b;
case _cId != 0 && desig == "All" && importancy == "All" && satus == "All":
query = from b in db.ConstituencyLeaders where b.ConstituencyID == _cId select b;
}
foreach (var item in query)
{
clsclass cl = new clsclass();
cl.LeaderId = item.LID;
//...remaining members add
list.Add(cl);
}
gvMain.DataSource = list;
gvMain.DataBind();
}
So basically I got two questions How to shorten the codes to capture the optional parameters if switch statement is better option then how would I achieve var query from Case:
any help much appreciated.
What you can do is.
var query = db.Members.AsQuerryable();
if(_cid != "")
{
query = query.where(table => table.CID == _cId);
}
Then use that in your statement
var result = from table in query where table.CID == _cId select table;
or we also used to do or statements.
var query= from table in query where (table.CID == _cId || _cId = "") select table;
so if the value is empty it just goes through or if there is a value it checks.

Categories