Finding longest time in an array - c#

I have an array of phrases, like
"6 days, 7 months, 2 years"
and I need to go through the array to find the longest time and return that value. I've built something to insert into my application as a custom action but it crashes my application. It does not generate an error message.
bool booDayFound = false;
bool booMonthFound = false;
bool booYearFound = false;
string DayPrognosisLength = null;
string MonthPrognosisLength = null;
string YearPrognosisLength = null;
string strOutValue = null;
int LongestDayLength = 0;
int LongestMonthLength = 0;
int LongestYearLength = 0;
string[] arrDayLength = null;
string[] arrMonthLength = null;
string[] arrYearLength = null;
string strPrognosis = Extracted_Prognosis;
char charSeperator = ',';
String[] arrPrognosis = strPrognosis.Split(charSeperator);
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Day") || varPrognosis.Contains("Days") || varPrognosis.Contains("day") || varPrognosis.Contains("days"))
{
booDayFound = true;
DayPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
DayPrognosisLength = DayPrognosisLength + ",";
arrDayLength = DayPrognosisLength.Split(',');
LongestDayLength = arrDayLength.Max(c => int.Parse(c));
}
else
{
booDayFound = false;
DayPrognosisLength = "";
}
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Months") || varPrognosis.Contains("Month") || varPrognosis.Contains("months") || varPrognosis.Contains("month"))
{
booMonthFound = true;
MonthPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
MonthPrognosisLength = MonthPrognosisLength + ",";
arrMonthLength = MonthPrognosisLength.Split(',');
LongestMonthLength = arrMonthLength.Max(c => int.Parse(c));
}
else
{
booMonthFound = false;
MonthPrognosisLength = "";
}
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Year") || varPrognosis.Contains("Years") || varPrognosis.Contains("year") || varPrognosis.Contains("years"))
{
booYearFound = true;
YearPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
YearPrognosisLength = YearPrognosisLength + ",";
arrYearLength = YearPrognosisLength.Split(',');
LongestYearLength = arrYearLength.Max(c => int.Parse(c));
}
else
{
booYearFound = false;
YearPrognosisLength = "";
}
if (booYearFound == true)
{
strOutValue = "Year:" + LongestYearLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestYearLength.ToString() + "Years(s)");
}
else if (booMonthFound == true)
{
strOutValue = "Month:" + LongestMonthLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestMonthLength.ToString() + "Month(s)");
}
else if (booDayFound == true)
{
strOutValue = "Day:" + LongestDayLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestDayLength.ToString() + "Day(s)");
}
return true;
}
catch (Exception ex)
{
AdmiralLog(ex.Message);
return false;
}
}
I've trimmed some Datacap specific functions and I know that my code is not the cleanest but I would like to know what am I missing here?

First, we have to come to terms: let's assume that
1 month == 30 days
1 year == 365 days
Then we can implement Duration function: given a string return duration in days:
Func<string, string, int> DurationTerm = (src, mask) => Regex
.Matches(
src,
$#"(?<number>[0-9]+)\s*{mask.TrimEnd('s', 'S')}s?",
RegexOptions.IgnoreCase)
.Cast<Match>()
.Select(match => int.Parse(match.Groups["number"].Value))
.DefaultIfEmpty()
.Sum();
//TODO: I've assumed 1 Month == 30 days, 1 Year == 365 days
// Correct the logic if required
Func<string, int> Duration = (src) =>
DurationTerm(src, "day") +
// DurationTerm(src, "week") * 7 + //TODO: Add more terms if you want
DurationTerm(src, "month") * 30 +
DurationTerm(src, "year") * 365;
Now we are ready to find out the longest time:
using System.Linq;
...
string[] arrPrognosis = ...
int LongestDayLength = arrPrognosis
.Max(item => Duration(item));

Related

C# extract desired data from passport mrz data

I read passport information through a scanner
When the scanner reads the passport, the data comes out like this
#PGRPMUSAAAA<<BBB<CCCC<<<<<<<<<<<<<<<<<<<<<<<<<\nM987654321USA7303010M20071519876543V12345678\n
I want to get FULL NAME, LAST NAME ,FIRST NAME, NATION CODE,PASSPORTNUM,SEX,BIRTH respectively
I extracted the name and other data by expressing it like this in the code
var MrzArraySplit = mrz.Substring(0).Split(new[] { "<" }, StringSplitOptions.RemoveEmptyEntries);
Data.FullName = OcrArraySplit[0] + OcrArraySplit[1] + OcrArraySplit[2]; //AAABBBCCCC
Data.LastName = OcrArraySplit[0]; // AAA
Data.FirstName1 = OcrArraySplit[1]; // BBB
Data.FirstName2 = OcrArraySplit[2]; // CCCC
Data.PassportNum = OcrArraySplit[3].Replace("\n",""); // \nM987654321USA7303010M20071519876543V12345678\n
Data.Birth = "";
Data.Sex = "";
Data.NationCode = "";
How should I code to extract the data I want to get?
Second line of MRZ (between \n and \n) contains not only password number, but all information you need (see https://en.wikipedia.org/wiki/Machine-readable_passport for example). Extract parts of string from fixed positions:
var line2 = OcrArraySplit[3].Replace("\n","");
d.PasspornNum = line2.Substring(0, 9);
d.Nationality = line2.Substring(10, 3);
etc
Here is my code to parse the strings (https://github.com/yushulx/dotnet-mrz-sdk/blob/main/MrzScanner.cs):
public static JsonNode? Parse(string[] lines)
{
JsonNode mrzInfo = new JsonObject();
if (lines.Length == 0)
{
return null;
}
if (lines.Length == 2)
{
string line1 = lines[0];
string line2 = lines[1];
var type = line1.Substring(0, 1);
if (!new Regex(#"[I|P|V]").IsMatch(type)) return null;
if (type == "P")
{
mrzInfo["type"] = "PASSPORT (TD-3)";
}
else if (type == "V")
{
if (line1.Length == 44)
{
mrzInfo["type"] = "VISA (MRV-A)";
}
else if (line1.Length == 36)
{
mrzInfo["type"] = "VISA (MRV-B)";
}
}
else if (type == "I")
{
mrzInfo["type"] = "ID CARD (TD-2)";
}
// Get issuing State infomation
var nation = line1.Substring(2, 5);
if (new Regex(#"[0-9]").IsMatch(nation)) return null;
if (nation[nation.Length - 1] == '<') {
nation = nation.Substring(0, 2);
}
mrzInfo["nationality"] = nation;
// Get surname information
line1 = line1.Substring(5);
var pos = line1.IndexOf("<<");
var surName = line1.Substring(0, pos);
if (new Regex(#"[0-9]").IsMatch(surName)) return null;
surName = surName.Replace("<", " ");
mrzInfo["surname"] = surName;
// Get givenname information
var givenName = line1.Substring(surName.Length + 2);
if (new Regex(#"[0-9]").IsMatch(givenName)) return null;
givenName = givenName.Replace("<", " ");
givenName = givenName.Trim();
mrzInfo["givenname"] = givenName;
// Get passport number information
var passportNumber = "";
passportNumber = line2.Substring(0, 9);
passportNumber = passportNumber.Replace("<", " ");
mrzInfo["passportnumber"] = passportNumber;
// Get Nationality information
var issueCountry = line2.Substring(10, 3);
if (new Regex(#"[0-9]").IsMatch(issueCountry)) return null;
if (issueCountry[issueCountry.Length - 1] == '<') {
issueCountry = issueCountry.Substring(0, 2);
}
mrzInfo["issuecountry"] = issueCountry;
// Get date of birth information
var birth = line2.Substring(13, 6);
var date = new DateTime();
var currentYear = date.Year;
if (Int32.Parse(birth.Substring(0, 2)) > (currentYear % 100)) {
birth = "19" + birth;
} else {
birth = "20" + birth;
}
birth = birth.Substring(0, 4) + "-" + birth.Substring(4, 2) + "-" + birth.Substring(6, 2);
if (new Regex(#"[A-Za-z]").IsMatch(birth)) return null;
mrzInfo["birth"] = birth;
// Get gender information
var gender = line2[20] + "";
if (!(new Regex(#"[M|F|x|<]").IsMatch(gender))) return null;
mrzInfo["gender"] = gender;
// Get date of expiry information
var expiry = line2.Substring(21, 6);
if (new Regex(#"[A-Za-z]").IsMatch(expiry)) return null;
if (Int32.Parse(expiry.Substring(0, 2)) >= 60) {
expiry = "19" + expiry;
} else {
expiry = "20" + expiry;
}
expiry = expiry.Substring(0, 4) + "-" + expiry.Substring(4, 2) + "-" + expiry.Substring(6);
mrzInfo["expiry"] = expiry;
}
else if (lines.Length == 3)
{
string line1 = lines[0];
string line2 = lines[1];
string line3 = lines[2];
var type = line1.Substring(0, 1);
if (!new Regex(#"[I|P|V]").IsMatch(type)) return null;
mrzInfo["type"] = "ID CARD (TD-1)";
// Get nationality infomation
var nation = line2.Substring(15, 3);
if (new Regex(#"[0-9]").IsMatch(nation)) return null;
nation = nation.Replace("<", "");
mrzInfo["nationality"] = nation;
// Get surname information
var pos = line3.IndexOf("<<");
var surName = line3.Substring(0, pos);
if (new Regex(#"[0-9]").IsMatch(surName)) return null;
surName = surName.Replace("<", " ");
surName.Trim();
mrzInfo["surname"] = surName;
// Get givenname information
var givenName = line3.Substring(surName.Length + 2);
if (new Regex(#"[0-9]").IsMatch(givenName)) return null;
givenName = givenName.Replace("<", " ");
givenName = givenName.Trim();
mrzInfo["givenname"] = givenName;
// Get passport number information
var passportNumber = "";
passportNumber = line1.Substring(5, 9);
passportNumber = passportNumber.Replace("<", " ");
mrzInfo["passportnumber"] = passportNumber;
// Get issuing country or organization information
var issueCountry = line1.Substring(2, 3);
if (new Regex(#"[0-9]").IsMatch(issueCountry)) return null;
issueCountry = issueCountry.Replace("<", "");
mrzInfo["issuecountry"] = issueCountry;
// Get date of birth information
var birth = line2.Substring(0, 6);
if (new Regex(#"[A-Za-z]").IsMatch(birth)) return null;
var date = new DateTime();
var currentYear = date.Year;
if (Int32.Parse(birth.Substring(0, 2)) > (currentYear % 100)) {
birth = "19" + birth;
} else {
birth = "20" + birth;
}
birth = birth.Substring(0, 4) + "-" + birth.Substring(4, 2) + "-" + birth.Substring(6);
mrzInfo["birth"] = birth;
// Get gender information
var gender = line2[7] + "";
if (!(new Regex(#"[M|F|X|<]").IsMatch(gender))) return null;
gender = gender.Replace("<", "X");
mrzInfo["gender"] = gender;
// Get date of expiry information
var expiry = "20" + line2.Substring(8, 6);
if (new Regex(#"[A-Za-z]").IsMatch(expiry)) return null;
expiry = expiry.Substring(0, 4) + "-" + expiry.Substring(4, 2) + "-" + expiry.Substring(6);
mrzInfo["expiry"] = expiry;
}
return mrzInfo;
}

Excel takes only that no of rows which has data in c#...my code works for some excel sheet not for all

Excel sheets made by different different clients...that code works when i make but not when user make..is anything problem with excel sheet so , i can tell user make like that way..or i can do anything with my code.
private void MeterUpdateByExcelSheet(HttpPostedFileBase file)
{
List<string> errorMessages = new List<string>();
int siteId = Helpers.SiteHelpers.Functions.GetSiteIdOfLoginUser().Value;
var stream = file.InputStream;
using (var package = new ExcelPackage(stream))
{
//getting number of sheets
var sheets = package.Workbook.Worksheets;
int totalProcessedMeters = 0;
if (sheets.Count > 0)
{
var sheet = sheets.FirstOrDefault();
//getting number of rows
var rows = sheet.Dimension.End.Row;
for (int row = 2; row <= rows; row++)
{
//get data for a row from excel
var meterNo = Convert.ToString(sheet.Cells[row, 1].Value);
int? sanctionLoadMains = (int)Convert.ToDecimal(sheet.Cells[row, 2].Value);
int? sanctionLoadDG = (int)Convert.ToDecimal(sheet.Cells[row, 3].Value);
int? unitArea = (int)Convert.ToDecimal(sheet.Cells[row, 4].Value);
int? creditLimit = (int)Convert.ToDecimal(sheet.Cells[row, 5].Value);
int? sMSWarning = (int)Convert.ToDecimal(sheet.Cells[row, 6].Value);
int? sMSWarning1 = (int)Convert.ToDecimal(sheet.Cells[row, 7].Value);
string date = sheet.Cells[row, 8].Value.ToString();
DateTime billingDate;
if (string.IsNullOrEmpty(date))
{
errorMessages.Add("Date is not given for MeterNo " + meterNo + " at row " + row);
continue;
}
if (!DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out billingDate))
{
errorMessages.Add("Date format is not correct for MeterNo. " + meterNo + " at row " + row);
continue;
}
if (!string.IsNullOrEmpty(meterNo))
{
meterNo = meterNo.PadLeft(9, '0');
var oldMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
var newMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
int wattUnit = 1000;//loads should be multiple of 1000(watt)
int smsWarningUnit = 100;//sms warnings should be multiple of 100
if (newMeter == null)
{
errorMessages.Add("MeterNo. " + meterNo + " does not exist.");
continue;
}
if (sanctionLoadMains.HasValue && sanctionLoadMains >= 500)
{
newMeter.LoadSenctionMain = sanctionLoadMains.Value;
}
if (sanctionLoadDG.HasValue && sanctionLoadDG >= 500)
{
newMeter.LoadSenctionDG = sanctionLoadDG.Value;
}
if (unitArea.HasValue)
{
newMeter.UnitArea = unitArea.Value;
}
if (creditLimit.HasValue)
{
newMeter.CreditLimit = creditLimit.Value;
}
if (sMSWarning.HasValue && sMSWarning >= 100)
{
newMeter.SMSWarningAmount = sMSWarning.Value;
}
if (sMSWarning1.HasValue && sMSWarning1 >= 100)
{
newMeter.SMSWarning1Amount = sMSWarning1.Value;
}
if (billingDate != null)
{
newMeter.BillingDate = billingDate.ToIndiaDateTime();
}
_meterRepository.AddOrUpdate(newMeter);
var meterNotes = Helpers.MeterHelpers.Functions.GetMeterNote(oldMeter, newMeter);
Helpers.MeterHelpers.Functions.AddMeterNotes(meterNo, meterNotes);
totalProcessedMeters++;
}
}
TempData["SuccessMessage"] = totalProcessedMeters + " Meter(s) have been updated successfully";
}

Not getting the Total Amount(Without VAT)

Country: Bahrain( i am selecting)
Amount:1000
Bank charges: 100(i am entering)
Vat:5%(entering) result:50(autogenerate)
Discount:6%(entering) result:60(autogenerate)
Total:1070(autogenerate)
This is working fine.I am getting the Total(with VAT).
Country:India(i am selecting)
Amount:1000
Bank charges: 100(i am entering)
Discount:5%(entering) result:50(autogenerate)
Total:(here i am not getting the amount)(may be because i set the visibility of VAT field false)
Here i am hidding the field VAT by using vattr.Visible=false. What should i do in order to sort out this issue?
Code behind:
protected void lstCountryy_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstCountryy.SelectedItem.Text == "U.A.E" || lstCountryy.SelectedItem.Text == "BAHRAIN" || lstCountryy.SelectedItem.Text=="SAUDI ARABIA")
{
vattr.Visible = true;
trdeclaration.Visible = false;
}
else
{
vattr.Visible = false;
trdeclaration.Visible = true;
}
}
Javascript:
function calculate(amount) {
var bankcharge = document.getElementById("<%=txtBankCharge.ClientID%>").value;
var vat = document.getElementById("<%=txtvatt.ClientID%>").value;
var discount = document.getElementById("<%=txtDiscount.ClientID%>").value;
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value))
{
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
if (bankcharge.length > 0) {
if (isNaN(bankcharge)) {
alert("Bank charge should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(bankcharge);
}
}
if (vat.length > 0)
{
if (isNaN(vat)) {
alert("VAT should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(vat);
}
}
if (discount.length > 0) {
if (isNaN(discount)) {
alert("Discount amount should be numbers only !!");
return false;
}
else {
sum = sum - parseFloat(discount);
}
}
var atemp = sum.toString().split(".");
if (atemp.length > 1) {
sum = sum.toFixed(2);
}
document.getElementById("<%=txtTotal.ClientID%>").value = sum;
document.getElementById("<%=txtAmountInWords.ClientID%>").value = convertNumberToWords(sum);
}
function vatCalc()//added by chetan
{
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value)) {
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var _txt2 = document.getElementById('<%= txtvat.ClientID %>');
var _txt3 = document.getElementById('<%= txtvatt.ClientID %>');
var t1=0, t2=0;
//if(_txt1.value != "") t1=_txt1.value;
if(_txt2.value != "") t2=_txt2.value;
_txt3.value = (sum * parseFloat(t2) )/ 100;
}
function discountCalc()
{
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value)) {
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var _txt2 = document.getElementById('<%= txtDiscountText.ClientID %>');
var _txt3 = document.getElementById('<%= txtDiscount.ClientID %>');
var t1=0, t2=0;
//if(_txt1.value != "") t1=_txt1.value;
if(_txt2.value != "") t2=_txt2.value;
_txt3.value = (sum * parseFloat(t2)) / 100;
}
The problem is here:
if (vat.length > 0)
{
if (isNaN(vat)) {
alert("VAT should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(vat);
}
}
I wanted to write this condition in such a way that when use selects bahrain,vat should be visible and should be calculated.
when user selects india,vat should be hidden and will yield the total amount.
Finally i got solution.This w orked perfectly.
if (lstCountryy.SelectedValue == "U.A.E" || lstCountryy.SelectedValue == "BAHRAIN" || lstCountryy.SelectedValue == "SAUDI ARABIA")
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "float");
trdeclaration.Visible = false;
//txtvat.Enabled = true;
}
else
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "none");
trdeclaration.Visible = true;
}

Store values from selected checkBox to a array

I have a foreach that if the checkbox of the row is selected it should do some calculations and after that store the result values in something,i'm trying to store in a array.In the end i need to have, for example 4 rows that were selected with his values inside the array,after that i need to put this values inside a session,and recover in other page(A confirmation page).I'm trying this.But i cant figure out a way to store the select rows in a array.I dont necessary need to be array if someone knows a better way.
string[] valoresSelecionados;
foreach (GridViewRow grdCount in grdSimulacao.Rows)
{
if (((CheckBox)grdCount.FindControl("chkSeleciona")).Checked)
{
if (double.Parse(grdCount.Cells[5].Text) >= 0)
vlNotas += double.Parse(grdCount.Cells[5].Text);
else
vlDebito += double.Parse(grdCount.Cells[5].Text);
if (!string.IsNullOrEmpty(grdCount.Cells[8].Text) && grdCount.Cells[8].Text != " ")
vlEncargos += double.Parse(grdCount.Cells[8].Text);
_simulacao.Notas.Rows.Add(grdCount.Cells[1].Text);
if (Culture== "English (United States)")
{
//DateTime data =DateTime.Parse(grdCount.Cells[2].Text);
//var dataInicial = data.ToString("mm-DD-yyyy");
_simulacao.Notas.Rows[u]["DTEMISSAO"] = grdCount.Cells[2].Text;
_simulacao.Notas.Rows[u]["DTVENCIMENTO"] = grdCount.Cells[3].Text;
}
else
{
_simulacao.Notas.Rows[u]["DTEMISSAO"] = grdCount.Cells[2].Text;
_simulacao.Notas.Rows[u]["DTVENCIMENTO"] = grdCount.Cells[3].Text;
}
_simulacao.Notas.Rows[u]["PRAZOPGTO"] = "5";
_simulacao.Notas.Rows[u]["VALTOTAL"] = grdCount.Cells[5].Text;
_simulacao.Notas.Rows[u]["DOCCOMPRAS"] = grdCount.Cells[6].Text;
if (DateTime.Parse(grdCount.Cells[3].Text) < DateTime.Parse(txtDtCredito.Text))
dtok = true;
DateTime antigaData = DateTime.Parse(grdCount.Cells[3].Text);
DateTime novaData = DateTime.Parse(txtDtCredito.Text);
DateTime dataAtual = DateTime.Today;
int diaAtual = dataAtual.DayOfYear;
int diaNovo = novaData.DayOfYear;
int diaAntigo = antigaData.DayOfYear;
int anoAtual = dataAtual.Year;
int anoNovo = novaData.Year;
if (diaAntigo <= diaNovo)
{
dataErro++;
}
if (diaNovo == diaAtual || diaNovo == diaAtual + 1 || diaNovo == diaAtual + 2 ||
diaNovo == diaAtual + 3 || diaNovo < diaAtual || anoAtual < anoNovo)
{
error++;
}
else
{
TimeSpan ts = antigaData - novaData;
if ((double.Parse(grdCount.Cells[5].Text)) < 0)
{
}
else
{
_simulacao.Notas.Rows[u]["DIASANTEC"] = ts.Days;
}
}
if (grdCount.Cells[7].Text != " ")
_simulacao.Notas.Rows[u]["DIASANTEC"] = "10";
else
_simulacao.Notas.Rows[u]["DIASANTEC"] = "0";
if (!string.IsNullOrEmpty(grdCount.Cells[8].Text) && grdCount.Cells[8].Text != " ")
{
_simulacao.Notas.Rows[u]["VLFINAL"] = double.Parse(grdCount.Cells[5].Text) - double.Parse(grdCount.Cells[8].Text);
_simulacao.Notas.Rows[u]["VLENCARGOS"] = grdCount.Cells[8].Text;
}
else
{
_simulacao.Notas.Rows[u]["VLFINAL"] = double.Parse(grdCount.Cells[5].Text);
_simulacao.Notas.Rows[u]["VLENCARGOS"] = "0,00";
}
valoresSelecionados[] = _simulacao.Notas.Rows.Add[u];
u++;
}
}
The first Picture show the first grid with all values.I selected 4 for example,after the calculations of the method i need to show only the 4 select in a model (second Picture),under the first grid of Picture two i will put the new grid with the selected values from before.

Index was out of range. Must be non-negative and less than the size of the collection in List<string>

I am using List object to store the user property.
My code is:
string department=string.Empty;
List<string> otherDepartments = new List<string>();
int no;
string result = string.Empty;
string queryText = string.Empty;
using (SPSite siteCollection = SPContext.Current.Site)
{
using(SPWeb site = siteCollection.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUser spUser = site.CurrentUser;
SPServiceContext context = SPServiceContext.GetContext(siteCollection);
UserProfileManager upm = new UserProfileManager(context);
UserProfile profile = upm.GetUserProfile(spUser.LoginName);
department = profile["oiplbDepartment"].Value.ToString();
UserProfileValueCollection otherDept = profile["oiplbOtherDepartments"];
if (otherDept.Count != 0)
{
foreach (var prop in otherDept)
{
otherDepartments.Add(prop.ToString());
}
}
Label1.Text = department + " Ohter Departments " + otherDepartments;
});
SPList list = site.Lists["Events"];
SPListItemCollection itemColl;
SPQuery query = new SPQuery();
no = 1 + otherDepartments.Count;
for (int i = 1; i <= no; i++)
{
if (no == 1)
{
result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>"+department+"</Value></Eq>"+"</or>";
break;
}
else if (i == 2)
{
result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + department + "</Value></Eq>" +
"<Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + otherDepartments[i-1] + "</Value></Eq>";
}
else if(i >= 3)
{
result = generateOr(result,otherDepartments[i-1]);
}
}
queryText = "<where>"+result +"</Where>";
query.Query = queryText;
itemColl = list.GetItems(query);
Grid.DataSource = itemColl.GetDataTable();
Grid.DataBind();
}
}
public static string generateOr(string temp, string value)
{
string r = "<or>" + temp + " <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + value + "</Value></Eq> </or>";
return r;
}
I am getting the above mentioned error when I run the program.
I am inserting a value if and only if the properties are available otherwise not.
But why am I getting the error?
Its because of
no = 1 + otherDepartments.Count;
change it to
no = otherDepartments.Count;
Even if you subtract 1 from i before you access the item in the list your for-loop loops until i == no. So you could also change i <= no to i < no
for (int i = 1; i < no; i++)

Categories