C# extract desired data from passport mrz data - c#

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;
}

Related

How would i optimise this if statement

Im finally done with my project and im going through my code and optimising it and trying to cut down on the chunky lines of code, how would i optimize this, it a series of if statments that matches text and adds value to a corresponding text box
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Manga vol 1-5 ")
{
var Book1 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book1 = Book1 + Global.Book1;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Manga vol 6-15 ")
{
var Book2 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book2 = Book2 + Global.Book2;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Novels 1-199 ")
{
var Book3 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book3 = Book3 + Global.Book3;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Novels 200-400 ")
{
var Book4 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book4 = Book4 + Global.Book4;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Comics series mainstream ")
{
var Book5 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book5 = Book5 + Global.Book5;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Comics series secondary ")
{
var Book6 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book6 = Book6 + Global.Book6;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Text book 1 semester/2 modules ")
{
var Book7 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book7 = Book7 + Global.Book7;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Text book module add-ons ")
{
var Book8 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book8 = Book8 + Global.Book8;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Hardcover ")
{
var Hardcover = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Hardcover = Hardcover + Global.Hardcover;
}
}
thx for the help
By using a dictionary:
var actions = new Dictionary<string, Action<int>>
{
["Manga vol 1-5 "] = book => Global.Book1 += book,
["Manga vol 6-15 "] = book => Global.Book2 += book
//...
};
Then:
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
var book = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
var action = actions[POSDGV.Rows[i].Cells[0].Value.ToString()];
action(book);
}
Or using a foreach loop:
foreach (var row in POSDGV.Rows)
{
var book = Int32.Parse(row.Cells[1].Value.ToString());
var action = actions[row.Cells[0].Value.ToString()];
action(book);
}
You can also use switch with strings
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
var value = POSDGV.Rows[i].Cells[0].Value.ToString();
var book = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
switch (value)
{
case "Manga vol 1-5 ":
{
Global.Book1 = Book + Global.Book1;
break;
}
//other cases
}
}
}
Using foreach makes it much more readable
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
foreach (var row in POSDGV.Rows)
{
var value = row.Cells[0].Value.ToString();
var book = Int32.Parse(row.Cells[1].Value.ToString());
switch (value)
{
case "Manga vol 1-5 ":
{
Global.Book1 = Book + Global.Book1;
break;
}
//other cases
}
}
}
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
string str1 = POSDGV.Rows[i].Cells[0].Value.ToString();
string str2 = POSDGV.Rows[i].Cells[1].Value.ToString();
var Book = Int32.Parse(str2);
if (str1 == "Manga vol 1-5 ")
{
Global.Book1 = Book + Global.Book1;
}
else if (str1 == "Manga vol 6-15 ")
{
Global.Book2 = Book + Global.Book2;
}
else if (str1 == "Novels 1-199 ")
{
Global.Book3 = Book + Global.Book3;
}
else if (str1 == "Novels 200-400 ")
{
Global.Book4 = Book + Global.Book4;
}
else if (str1 == "Comics series mainstream ")
{
Global.Book5 = Book + Global.Book5;
}
else if (str1 == "Comics series secondary ")
{
Global.Book6 = Book + Global.Book6;
}
else if (str1 == "Text book 1 semester/2 modules ")
{
Global.Book7 = Book + Global.Book7;
}
else if (str1 == "Text book module add-ons ")
{
Global.Book8 = Book + Global.Book8;
}
else if (str1 == "Hardcover ")
{
var Hardcover = Int32.Parse(str2);
Global.Hardcover = Hardcover + Global.Hardcover;
}
}
}
Using a variable will lessen the characters in a code. You can also try using enumerations so you can use switch-case.

Finding longest time in an array

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));

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";
}

When parsing a string in to DateTime, parse the string to take data before putting each variable into the DateTime Object

I have checked all answer related to this error but I couldn't solve it.
I have an admission form. They are fields like DateOfAdmission, PhoneNumber **, **TimeOfAdmission and other things . When I try to retrieve values from the form and convert them. And then try to insert them in SQL Server Database. The application breaks saying...
'System.FormatException'
When parsing a string into DateTime, parse the string to take data before putting each variable into the DateTime Object.
Here is my code please look at it and tell me where I am getting wrong.
public partial class AdmissionForm : Window
{
public AdmissionForm()
{
InitializeComponent();
}
private void SubmitFormClick(object sender, RoutedEventArgs e)
{
// Parsing Values
// STIRNG TO INT
int AdmissionNumber = int.Parse(AdmissionNumberTextBox.Text);
int CNIC = int.Parse(CNICTextBox.Text);
int Age = int.Parse(AgeTextBox.Text);
int PhoneNumber = int.Parse(PhoneTextBox.Text);
int MobileNumber = int.Parse(MobileTextBox.Text);
int EmergencyNumber = int.Parse(EmergencyTextBox.Text);
// Converting time 'String' into Byte[]
//string time = DateTime.Now.ToString("hh:mm:tt"); //TimeOfDay.ToString("HH:mm:ss")
byte[] TimeOfAdmission = Encoding.ASCII.GetBytes(DateTime.Now.ToString("hh:mm:tt"));
// Converting date 'String' into DateTime
//string date = DateTime.Now.ToString("dd/MM/yyyy");
DateTime DateOfAdmission = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));
// String
var StudentName = StudentNameTextBox.Text;
var FatherName = FatherNameTextBox.Text;
var Qualification = QualificationTextBox.Text;
var Nationality = NationalityTextBox.Text;
var Adress = AdressTextBox.Text;
var Timing = SheduleTime.SelectedValue.ToString();
var ClassLevel = ClassValue.SelectedValue.ToString();
var Reference = ReferenceTextBox.Text;
// DB context Getting Entites and attributes
var context = new AcademyEntities();
// Creating new Model
var Model = new StudentTable();
// Getting and Setting values
// Reading Values
Model.StudentName = StudentName;
Model.FatherName = FatherName;
Model.StudentCNIC = CNIC;
Model.GuardianName = null;
Model.Nationality = Nationality;
Model.Qualification = Qualification;
Model.StudentAge = Age;
Model.AdmissionNumber = AdmissionNumber;
Model.TimeOfAdmission = TimeOfAdmission;
Model.DateOfAdmission = DateOfAdmission;
Model.MobileNumber = MobileNumber;
Model.PhoneNumber = PhoneNumber;
Model.EmergencyNumber = EmergencyNumber;
Model.Adress = Adress;
Model.ClassID = ClassTime(Timing);
Model.CourseLevelID = CourseLevelID(ClassLevel);
Model.Reference = Reference;
context.StudentTables.Add(Model);
context.SaveChanges();
// Class Time Id
int ClassTime(string Timing)
{
int classId = 1;
if (Timing == "2 to 3 PM")
{
return classId;
}
else if (Timing == "3 to 4 PM")
{
classId = 2;
return classId;
}
else if (Timing == "4 to 5 PM")
{
classId = 3;
return classId;
}
else if (Timing == "5 to 6 PM")
{
classId = 4;
return classId;
}
else if (Timing == "6 to 7 PM")
{
classId = 5;
return classId;
}
return classId;
}
// Course Level Id
int CourseLevelID(string ClassLevel)
{
int courseLevelId = 1;
if (ClassLevel == "Lower Basic")
{
return courseLevelId;
}
else if (ClassLevel == "Basic")
{
courseLevelId = 2;
return courseLevelId;
}
else if (ClassLevel == "Pre Starter")
{
courseLevelId = 3;
return courseLevelId;
}
else if (ClassLevel == "Starter")
{
courseLevelId = 4;
return courseLevelId;
}
else if (ClassLevel == "Intermediate")
{
courseLevelId = 5;
return courseLevelId;
}
else if (ClassLevel == "Advance")
{
courseLevelId = 5;
return courseLevelId;
}
return courseLevelId;
}
}
Well I searched and found one solution to parse date as SQL SERVER timestamp
string currentTime = DateTime.Now.ToString("hh:mm:tt");
byte[] TimeOfAdmission = Encoding.ASCII.GetBytes(currentTime);

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