calling methods and arrays objects Library Book console app C# - c#

My professor wants us to create a reusable class and console app that lists book objects. I got the first part of the assignment where I am supposed to print the books I created, but now I am stuck on the part where I have to modify the data and print again using the same method and then check out two books and print again. I have tried to look at example online and although some of them have helped, none have been able to get me to pass this roadblock.
class LibraryBook
{
private string _bookTitle;
private string _authorName;
private string _publisher;
private int _copyrightYear;
private string _callNumber;
public LibraryBook(string booktitle, string authorname, string publisher, int ccyear, string callnumber)
{
BookTitle = booktitle;
AuthorName = authorname;
Publisher = publisher;
CopyrightYear = ccyear;
CallNumber = callnumber;
}
public string BookTitle
{
get
{
return _bookTitle;
}
set
{
_bookTitle = value;
}
}
public string AuthorName
{
get
{
return _authorName;
}
set
{
_authorName = value;
}
}
public string Publisher
{
get
{
return _publisher;
}
set
{
_publisher = value;
}
}
public int CopyrightYear
{
get
{
return _copyrightYear;
}
set
{
const int CYEAR = 2019;
if (value > 0)
_copyrightYear = value;
else
_copyrightYear = CYEAR;
}
}
public string CallNumber
{
get
{
return _callNumber;
}
set
{
_callNumber = value;
}
}
public bool Avail;
public void CheckOut()
{
Avail = true;
}
public void ReturnToShelf()
{
Avail = false;
}
public bool IsCheckedOut()
{
return Avail;
}
public override string ToString()
{
return $"Book Title: {BookTitle}{Environment.NewLine}" +
$"Author Name: {AuthorName}{Environment.NewLine}" +
$"Publisher: {Publisher}{Environment.NewLine}" +
$"Copyright Year: {CopyrightYear}{Environment.NewLine}" +
$"Call Number: {CallNumber}{Environment.NewLine}" +
$"Checked Out: {IsCheckedOut()}{Environment.NewLine}";
}
}
}
class Program
{
static void Main(string[] args)
{
LibraryBook[] favBooksArray = new LibraryBook[5];
favBooksArray[0] = new LibraryBook("Harry Potter and the Philospher's Stone", "J.K. Rowling", "Scholastic Corporation", 1997, "HA-12.36");
favBooksArray[1] = new LibraryBook("Harry Potter and the Chamber of Secret", "J.K. Rowling", "Scholastic Corporation", 2001, "HA-13.48");
favBooksArray[2] = new LibraryBook("Tangerine", "Edward Bloor", "Harcourt", 1997, "TB-58.13");
favBooksArray[3] = new LibraryBook("Roll of Thunder, Hear My Cry", "Mildred D. Taylor", "Dial Press", 1976, "RT-15.22");
favBooksArray[4] = new LibraryBook("The Giver", "Lois Lowry", "Fake Publisher", -1, "Fk200-1");
WriteLine($"------LIBRARY BOOKS------{Environment.NewLine}");
BooksToConsole(favBooksArray);
WriteLine($"------CHANGES MADE----- {Environment.NewLine}");
ChangesToBooks(favBooksArray);
BooksToConsole(favBooksArray);
WriteLine($"------RETURNING BOOKS TO SHELF------{Environment.NewLine}");
ReturnBooksToConsole(favBooksArray);
BooksToConsole(favBooksArray);
}
public static void BooksToConsole(LibraryBook[] favBooksArray)
{
foreach (LibraryBook books in favBooksArray)
{
WriteLine($"{books}{Environment.NewLine}");
}
}
public static void ChangesToBooks(LibraryBook[] favBooksArray)
{
favBooksArray[1].AuthorName = "*****The Rock*****";
favBooksArray[3].BookTitle = "****Totally Not A Fake Name*****";
favBooksArray[1].CheckOut();
favBooksArray[4].CheckOut();
}
public static void ReturnBooksToConsole(LibraryBook[] favBooksArray)
{
favBooksArray[1].ReturnToShelf();
favBooksArray[4].ReturnToShelf();
}
}
}

Related

Singleton property not updating during "OnClicked" event

I'm sure I remember this being a threading issue, but I can't find an answer. It seems like it should be simple. I have the following code:
private void Dingle_Clicked(object sender, RoutedEventArgs e)
{
dynamic doc = ScraperBrowser.Document;
string htmlText = doc.documentElement.InnerHtml;
htmlText = htmlText.Replace("\r\n", " ");
Regex targetStart = new Regex(this works just fine);
MatchCollection target = targetStart.Matches(htmlText);
string priceData = target[0].Value;
foreach (StorePriceData spData in Lists.Singleton.MedicineList[medIndex].Prices)
{
Regex rx = new Regex(spData.StoreName + #".+?(\$\d+\.\d+)");
MatchCollection matches = rx.Matches(priceData);
if (matches.Count > 0)
{
if (matches[0].Groups.Count > 0)
{
spData.MedicinePrice = matches[0].Groups[1].Value;
}
}
}
string cookie = Application.GetCookie(new Uri("https://www.goodrx.com"));
++medIndex;
ScraperBrowser.Navigate(Lists.Singleton.MedicineList[medIndex].GoodRxUrlString);
}
The problem I'm having is that the spData.MedicinePrice takes the value, but the value in the singleton "MedicineList" is not being updated. How can I make that value update?
The singleton code:
public class Lists
{
private static Lists _singleton;
public static Lists Singleton
{
get
{
if (_singleton == null) _singleton = new Lists(); return _singleton;
}
}
public List<MedicineInfo> MedicineList {
get
{
return new List<MedicineInfo>()
{
new MedicineInfo() { Name = "ZOLPIDEM TAB 10MG", Doses = "30 tablets" },
new MedicineInfo() { Name = "PANTOPRAZOLE TAB 40MG", Doses = "30 tablets" }
};
}
}
}
MedicineInfo class code:
public class MedicineInfo
{
public MedicineInfo()
{
Prices = new List<StorePriceData>()
{
new StorePriceData() { StoreName = "xxxx" },
new StorePriceData() { StoreName = "yyyy" },
new StorePriceData() { StoreName = "zzzz" },
};
}
public string Name { get; set; }
public string Doses { get; set; }
public List<StorePriceData> Prices { get; set; }
}
Thanks!
Carl
You are returning a new List<MedicineInfo> each time the getter of MedicineList is called.
Also, Lists is not really a singleton. A better implementation would look something like this:
public sealed class Lists
{
private static readonly Lists _singleton = new Lists();
private readonly List<MedicineInfo> _medicineList = new List<MedicineInfo>
{
new MedicineInfo() { Name = "ZOLPIDEM TAB 10MG", Doses = "30 tablets" },
new MedicineInfo() { Name = "PANTOPRAZOLE TAB 40MG", Doses = "30 tablets" }
};
private Lists() { }
public static Lists Singleton => _singleton;
public List<MedicineInfo> MedicineList => _medicineList;
}

Huge List<T> processing and Pdf generate

I have a pdf file as Byte[] and I'm using iTextSharp to modify the file and embed a specific details in it.
in the List I have min. 25K objects, and I need to generate 25K pdf files.
I'm using Parallel.ForEach but it takes 16.40 mins to be done in Total.
I used ToLookUp method like this:
var valuesToLookupWith = Recipients.ToLookup(item => item.ID);
List<int> Ids = Recipients.Select(item => item.ID).ToList();
Partitioner<int> partitioner = Partitioner.Create(Ids, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions { MaxDegreeOfParallelism = 6 } ,(id) =>
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile((fileAsByteArray,id, "www.xyz.ca"));
...
});
and I used ForEach and also it takes approx. > 25 minutes.
foreach (int id in Ids)
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile(fileAsByteArray,id, "www.xyz.ca");
...
}
any suggested way to speedup the process please?
FYI I'm not writing anything on the disk, all is done in memory as Byte[] and then I'm writing the values back to the Db.
and also all the time spent - mentioned in the question is only the time spent for Parallel.ForEach / ForEach statements.
Db calls is not an issue for me at all, I'm making only two calls to the Db , one when I load list of recipients from it and another call when writing values back to the Db
public static byte[] GeneratePdfFromPdfFile(byte[] file, int id, string landingPage)
{
try
{
using (var ms = new MemoryStream())
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
var doc = new iTextSharp.text.Document();
//Create a writer that's bound to our PDF abstraction and our stream
var writer = PdfWriter.GetInstance(doc, ms);
//Open the document for writing
doc.Open();
PdfContentByte cb = writer.DirectContent;
// doc.NewPage();
//var srHtml = new StringReader(source);
////parse html code to xml
//iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
PdfReader reader = new PdfReader(file);
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
doc.NewPage();
//Insert to Destination on the first page
PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
// Add a new page to the pdf file
doc.NewPage();
// set pdf open action to open the link embedded in the file.
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + GetCampaignRecipientCode(id) + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
writer.SetOpenAction(act);
doc.Close();
return ms.ToArray();
}
}
catch { return null; }
}
Recipient Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CampaignLauncherLibrary
{
public class CampaignRecipientLib
{
private int _id;
private int _crid;
private string _crcode;
private int _cmpId;
private string _cmpStatus;
private string _email;
private string _firstName;
private string _lastName;
private string _language;
private string _cmpDefaultlanguage;
private bool _isdoubleBarrle;
private DateTime? _scheduled;
private string _offset;
private string _emailTo;
private string _emailFrom;
private string _emailBody;
private string _emailSubject;
private byte[] _emailAttachment;
private string _emailReplyTo;
private string _attachmentName;
private bool _readytobesent;
private bool _pickupready;
private TimeSpan _Toffset;
private int? _cmprIDnextRecipient;
private string _CampaignGroupCode;
private bool _Reschedule;
private List<int> _Campaigns;
private List<int> _SentCampaigns;
private bool _restrictToWorkHours;
private TimeSpan? _whStart;
private TimeSpan? _whEnd;
private string _emailName;
public CampaignRecipientLib()
{
}
public CampaignRecipientLib(CampaignRecipientLib _recipient)
{
ID = _recipient.ID;
CampaignId = _recipient.CampaignId;
CampaignStatus = _recipient.CampaignStatus;
CMPRID = _recipient.CMPRID;
CMPRCode = Guid.NewGuid().ToString("N");
Email = _recipient.Email;
FirstName = _recipient.FirstName;
LastName = _recipient.LastName;
Language = _recipient.Language;
DefaultLanguage = _recipient.DefaultLanguage;
IsdoubleBarrle = _recipient.IsdoubleBarrle;
Scheduled = _recipient.Scheduled;
Offset = _recipient.Offset;
EmailTo = _recipient.EmailTo;
EmailFrom = _recipient.EmailFrom;
EmailBody = _recipient.EmailBody;
EmailSubject = _recipient.EmailSubject;
EmailAttachment = _recipient.EmailAttachment;
EmailReplyTo = _recipient.EmailReplyTo;
AttachmentName = _recipient.AttachmentName;
ReadyTobeSent = _recipient.ReadyTobeSent;
PickupReady = _recipient.PickupReady;
IDnextRecipient = _recipient.IDnextRecipient;
CampaignGroupCode = _recipient.CampaignGroupCode;
Reschedule = _recipient.Reschedule;
Campaigns = _recipient.Campaigns;
SentCampaigns = _recipient.SentCampaigns;
EmailName = _recipient.EmailName;
Toffset = _recipient.Toffset;
}
public void AssingRandomCampaign()
{
int result = 0;
List<int> cmp = _Campaigns;
List<int> sentcmp = _SentCampaigns;
if (cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList().Count > 0)
{
cmp = cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList();
result = cmp.Shuffle().Take(1).ToList()[0];
}
else
{
int N = 0;
if (sentcmp.Count == 2) N = 1;
else if (sentcmp.Count == 3) N = 2;
else N = sentcmp.Count % 2 == 0 ? 2 : 3;
List<int> lastN = sentcmp.Skip(Math.Max(0, sentcmp.Count) - N).ToList();
cmp = cmp.Where(predicate: x => !lastN.Contains(x)).ToList();
sentcmp = sentcmp.Where(predicate: x => cmp.Contains(x)).ToList();
List<int> grpOccurrences = sentcmp.GroupBy(i => i).OrderByDescending(item => item.Count()).SelectMany(i => i).Distinct().ToList();
result = grpOccurrences.Shuffle().PickRandom(1).ToList()[0];
}
if (result > 0)
{
_SentCampaigns.Add(result);
CampaignId = result;
}
}
public bool reAdjustScheduleDate()
{
try
{
Scheduled = Utilities.FixDate(Scheduled.Value, RestrictToWorkHours, Offset, WhStart, WhEnd);
}
catch (Exception ex)
{
return false;
}
return true;
}
public TimeSpan Toffset
{
get { return _Toffset; }
set { _Toffset = value; }
}
public string EmailName
{
get { return _emailName; }
set { _emailName = value; }
}
public int? IDnextRecipient
{
get { return _cmprIDnextRecipient; }
set { _cmprIDnextRecipient = value; }
}
public string CampaignGroupCode
{
get { return _CampaignGroupCode; }
set { _CampaignGroupCode = value; }
}
public bool RestrictToWorkHours
{
get { return _restrictToWorkHours; }
set { _restrictToWorkHours = value; }
}
public TimeSpan? WhStart
{
get { return _whStart; }
set { _whStart = value; }
}
public TimeSpan? WhEnd
{
get { return _whEnd; }
set { _whEnd = value; }
}
public bool Reschedule
{
get { return _Reschedule; }
set { _Reschedule = value; }
}
public List<int> Campaigns
{
get { return _Campaigns; }
set { _Campaigns = value; }
}
public List<int> SentCampaigns
{
get { return _SentCampaigns; }
set { _SentCampaigns = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public int CMPRID
{
get { return _crid; }
set { _crid = value; }
}
public string CMPRCode
{
get { return _crcode; }
set { _crcode = value; }
}
public int CampaignId
{
get { return _cmpId; }
set { _cmpId = value; }
}
public string CampaignStatus
{
get { return _cmpStatus; }
set { _cmpStatus = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Language
{
get { return _language; }
set { _language = value; }
}
public string DefaultLanguage
{
get { return _cmpDefaultlanguage; }
set { _cmpDefaultlanguage = value; }
}
public bool IsdoubleBarrle
{
get { return _isdoubleBarrle; }
set { _isdoubleBarrle = value; }
}
public DateTime? Scheduled
{
get { return _scheduled; }
set { _scheduled = value; }
}
public string EmailTo
{
get { return _emailTo; }
set { _emailTo = value; }
}
public string Offset
{
get { return _offset; }
set { _offset = value; }
}
public string EmailFrom
{
get { return _emailFrom; }
set { _emailFrom = value; }
}
public string EmailBody
{
get { return _emailBody; }
set { _emailBody = value; }
}
public string EmailSubject
{
get { return _emailSubject; }
set { _emailSubject = value; }
}
public byte[] EmailAttachment
{
get { return _emailAttachment; }
set { _emailAttachment = value; }
}
public string EmailReplyTo
{
get { return _emailReplyTo; }
set { _emailReplyTo = value; }
}
public string AttachmentName
{
get { return _attachmentName; }
set { _attachmentName = value; }
}
public bool ReadyTobeSent
{
get { return _readytobesent; }
set { _readytobesent = value; }
}
public bool PickupReady
{
get { return _pickupready; }
set { _pickupready = value; }
}
}
}

Code coverage differences in sonarqube .Net

I found a scenario with SonarQube 5.3 where different values are being reported in code coverage from Visual Studio code coverage analysis.
Here is a small reproduction, using the MSTest framework.
I'm not able to determine if there is something wrong in what we are doing or if one of the applications is wrong.
The object being tested
[Serializable]
public class Document : IEquatable<Document>
{
public long Id { get; set; }
public string Name { get; set; }
public long DocumentHandle { get; set; }
public long BatchId { get; set; }
public string BatchName { get; set; }
public string RepositoryName { get; set; }
public long DocumentTypeId { get; set; }
public string DocumentTypeName { get; set; }
public int SequenceNumber { get; set; }
public string LoanNumber { get; set; }
public bool IsJunked { get; set; }
public DateTime ArrivalDate { get; set; }
public bool Equals(Document other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (Id != other.Id)
{
return false;
}
if (!string.Equals(Name, other.Name))
{
return false;
}
if (DocumentHandle != other.DocumentHandle)
{
return false;
}
if (BatchId != other.BatchId)
{
return false;
}
if (!string.Equals(BatchName, other.BatchName))
{
return false;
}
if (!string.Equals(RepositoryName, other.RepositoryName))
{
return false;
}
if (DocumentTypeId != other.DocumentTypeId)
{
return false;
}
if (!string.Equals(DocumentTypeName, other.DocumentTypeName))
{
return false;
}
if (SequenceNumber != other.SequenceNumber)
{
return false;
}
if (!string.Equals(LoanNumber, other.LoanNumber))
{
return false;
}
if (IsJunked != other.IsJunked)
{
return false;
}
if (ArrivalDate != other.ArrivalDate)
{
return false;
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return Equals((Document) obj);
}
public static bool operator == (Document document1, Document document2)
{
return ReferenceEquals(document1, null) ? ReferenceEquals(document2, null) : document1.Equals(document2);
}
public static bool operator != (Document document1, Document document2)
{
return !(document1 == document2);
}
public override int GetHashCode()
{
// ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode
// This was done to suppress the messages about needing to override GetHashCode
// Because this class has no ReadOnly properties there is no way to provide a better hashcode
return base.GetHashCode();
}
}
The code has the following tests:
[TestClass]
[ExcludeFromCodeCoverage]
public class DocumentTests
{
private Document defaultDocument;
private Document alteredDocument;
[TestInitialize]
public void Setup()
{
defaultDocument = new Document
{
Id = 1,
Name = "Growlithe",
DocumentHandle = 2,
BatchId = 3,
BatchName = "Vulpix",
RepositoryName = "Pancham",
DocumentTypeId = 4,
DocumentTypeName = "Skrelp",
SequenceNumber = 5,
LoanNumber = "Zorua",
IsJunked = true,
ArrivalDate = new DateTime(1, 1, 1)
};
alteredDocument = new Document
{
Id = 1,
Name = "Growlithe",
DocumentHandle = 2,
BatchId = 3,
BatchName = "Vulpix",
RepositoryName = "Pancham",
DocumentTypeId = 4,
DocumentTypeName = "Skrelp",
SequenceNumber = 5,
LoanNumber = "Zorua",
IsJunked = true,
ArrivalDate = new DateTime(1, 1, 1)
};
}
[TestMethod]
public void ToStringMethod_DocumentPOCO_ConvertObjectToString()
{
// Arrange
var expectedStringDocument = "Document" + Environment.NewLine +
"\tId: 101" + Environment.NewLine +
"\tName: TestName" + Environment.NewLine +
"\tDocumentHandle: 5000000" + Environment.NewLine +
"\tBatchId: 500000000" + Environment.NewLine +
"\tBatchName: TestBatchName" + Environment.NewLine +
"\tRepositoryName: TestRepositoryName" + Environment.NewLine +
"\tDocumentTypeId: 5000000" + Environment.NewLine +
"\tDocumentTypeName: TestDocumentTypeName" + Environment.NewLine +
"\tSequenceNumber: 101" + Environment.NewLine +
"\tLoanNumber: TestLoanNumber" + Environment.NewLine +
"\tIsJunked: False" + Environment.NewLine +
"\tArrivalDate: " + DateTime.Now + Environment.NewLine;
alteredDocument = new Document
{
Id = 101,
Name = "TestName",
DocumentHandle = 5000000,
BatchId = 500000000,
BatchName = "TestBatchName",
RepositoryName = "TestRepositoryName",
DocumentTypeId = 5000000,
DocumentTypeName = "TestDocumentTypeName",
SequenceNumber = 101,
LoanNumber = "TestLoanNumber",
IsJunked = false,
ArrivalDate = DateTime.Now
};
// Act
var processedDocumentObj = StringUtility.StringUtility.ConvertToString(alteredDocument);
// Assert
Assert.IsTrue(processedDocumentObj.Equals(expectedStringDocument));
}
[TestMethod]
public void EqualsReturnsTrueForEquivalentDocument()
{
Assert.IsTrue(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForNullDocument()
{
alteredDocument = null;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentId()
{
alteredDocument.Id = 9;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentName()
{
alteredDocument.Name = "Arcanine";
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentDocumentHandle()
{
alteredDocument.DocumentHandle = 9;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentBatchId()
{
alteredDocument.BatchId = 9;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentBatchName()
{
alteredDocument.BatchName = "Ninetails";
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentRepositoryName()
{
alteredDocument.RepositoryName = "Pangoro";
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentDocumentTypeId()
{
alteredDocument.DocumentTypeId = 9;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentDocumentTypeName()
{
alteredDocument.DocumentTypeName = "Dragalge";
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentSequenceNumber()
{
alteredDocument.SequenceNumber = 9;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentLoanNumber()
{
alteredDocument.LoanNumber = "Zoroark";
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentIsJunked()
{
alteredDocument.IsJunked = false;
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsReturnsFalseForDifferentArrivalDate()
{
alteredDocument.ArrivalDate = new DateTime(2, 2, 2);
Assert.IsFalse(defaultDocument.Equals(alteredDocument));
}
[TestMethod]
public void EqualsOperatorWorksForNonNullValues()
{
Assert.IsTrue(defaultDocument == alteredDocument);
}
[TestMethod]
public void NotEqualsOperatorWorksForNonNullValues()
{
alteredDocument = null;
Assert.IsTrue(defaultDocument != alteredDocument);
}
[TestMethod]
public void EqualsOperatorReturnsFalseForNullDotNonNull()
{
alteredDocument = null;
Assert.IsFalse(alteredDocument == defaultDocument);
}
[TestMethod]
public void EqualsOperatorReturnsFalseForNonNullDotNull()
{
alteredDocument = null;
Assert.IsFalse(defaultDocument == alteredDocument);
}
[TestMethod]
public void EqualsOperatorReturnsTrueForNullDotNull()
{
alteredDocument = null;
defaultDocument = null;
Assert.IsTrue(defaultDocument == alteredDocument);
}
}
Visual Studio shows the percentage as: 90.10%
SonarQube shows the percentage as: 40.00%
Sonar doesn't appear to consider the early return statements after the
if (ReferenceEquals(other, null))
{
return false;
}
of the method: public bool Equals(Document other)
I have debugged the tests to validate the lines are hit.
It may be a difference between line/branch coverage:
What is the difference between code coverage and line coverage in sonar
... or white spacing/line wrapping.
You can find the formula for SonarQube's metric description page here: http://docs.sonarqube.org/display/SONAR/Metric+definitions#Metricdefinitions-Tests
coverage = (CT + CF + LC)/(2*B + EL)
where
CT - branches that evaluated to "true" at least once
CF - branches that evaluated to "false" at least once
LC - lines covered (lines_to_cover - uncovered_lines)
B - total number of branches (2*B = conditions_to_cover)
EL - total number of executable lines (lines_to_cover)
Actually could be like others say that you have to build in debug mode. But my coworker has found a strange thing:
If you add () to [TestClass] and [TestMethod] decorators as
[TestClass()] and [TestMethod()] it works fine.
Problem is telling all the developers that Sonar requires it, while Microsoft docs does not.
This applies to Sonarqube DE. In community Edition works fine, without ()

Binding to New Member Display; BuildComboList

I am trying to build a combo list for a program to fill the combobox with a list of applications. it keeps throwing up "Cannot bind to the new display member. Parameter name: newDisplayMember"
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}
Applicant Class
public class Applicant
{
//Members
private int applicant_ID;
private string applicant_fname;
private string applicant_lname;
private string applicant_phone;
private string applicant_address1;
private string applicant_address2;
private string applicant_city;
private string applicant_state;
private string applicant_zip;
private string applicant_email;
//properties
public int Applicant_ID
{
get { return applicant_ID; }
set { applicant_ID = value; }
}
public string Applicant_fname
{
get { return applicant_fname; }
set { applicant_fname = value; }
}
public string Applicant_lname
{
get { return applicant_lname; }
set { applicant_lname = value; }
}
public string Applicant_phone
{
get { return applicant_phone; }
set { applicant_phone = value; }
}
public string Applicant_address1
{
get { return applicant_address1; }
set { applicant_address1 = value; }
}
public string Applicant_address2
{
get { return applicant_address2; }
set { applicant_address2 = value; }
}
public string Applicant_city
{
get { return applicant_city; }
set { applicant_city = value; }
}
public string Applicant_state
{
get { return applicant_state; }
set { applicant_state = value; }
}
public string Applicant_zip
{
get { return applicant_zip; }
set { applicant_zip = value; }
}
public string Applicant_email
{
get { return applicant_email; }
set { applicant_email = value; }
}
//Constructors
private void DefaultValues()
{
applicant_ID = 0;
applicant_fname = "";
applicant_lname = "";
applicant_phone = "";
applicant_address1 = "";
applicant_address2 = "";
applicant_city = "";
applicant_state = "";
applicant_zip = "";
applicant_email = "";
}
private void Rec2Members(ApplicantRecord record)//defined in ApplicantDL
{
applicant_ID = record.applicant_ID;
applicant_fname = record.applicant_fname;
applicant_lname = record.applicant_lname;
applicant_phone = record.applicant_phone;
applicant_address1 = record.applicant_address1;
applicant_address2 = record.applicant_address2;
applicant_city = record.applicant_city;
applicant_state = record.applicant_state;
applicant_zip = record.applicant_zip;
applicant_email = record.applicant_email;
}
public ApplicantRecord ToRecord()
{
ApplicantRecord record = new ApplicantRecord();
record.applicant_ID = applicant_ID;
record.applicant_fname = applicant_fname;
record.applicant_lname = applicant_lname;
record.applicant_phone = applicant_phone;
record.applicant_address1 = applicant_address1;
record.applicant_address2 = applicant_address2;
record.applicant_city = applicant_city;
record.applicant_state = applicant_state;
record.applicant_zip = applicant_zip;
record.applicant_email = applicant_email;
return record;
}
public List<ApplicantRecord> GetList()
{
return Approval_Form.ApplicantRecord.ApplicantDL.GetList();
}
public void Insert()
{
applicant_ID = Approval_Form.ApplicantRecord.ApplicantDL.Insert(applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
public void Select(int applicant_ID)
{
ApplicantRecord record = Approval_Form.ApplicantRecord.ApplicantDL.Select(applicant_ID);
Rec2Members(record);
}
public void Update()
{
if (applicant_ID != 0)
{
Approval_Form.ApplicantRecord.ApplicantDL.Update(applicant_ID, applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
}
}
I think it should be:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "Applicant_fname";
applicantList.ValueMember = "Applicant_ID";
}
You can change the applicant class further as follows:
Add two properties.
public string DisplayName
{
get { return (applicant_fname + " " + applicant_lname; }
}
public string DisplayValue
{
get { return (applicant_ID.ToString(); }
}
Keep data binding as:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}

Displaying all items in another class

My problem is that I have a List<> variable connected to another class, and I want to get all the items from that List<> and put it into a string.
In the result string, i'd like to see callNum, copyNum, content, author, year, title
Here is where I'm trying to put it into a string
public class CItemControl
{
//declare a list variable
private List<CItem> mItems;
private CItem mNewItem;
//a method that instantiates the list
public CItemControl()
{
mItems = new List<CItem>();
}
//attribute to get all items
public List<CItem> Items
{
get { return mItems; }
}
public CItem NewItem
{
get { return mNewItem; }
}
//method to add item to the CItem list
public void AddItem(int callNum, int copyNum, string content, string author, string year)
{
mNewItem = new CItem(callNum, copyNum, content, author, year);
mItems.Add(mNewItem);
}
//method to return all items to a string
public CItem ListAllItems()
{
string allItems;
}
Here is the class where I'm trying to get the items from. There will be variables added later.
class CItem
{
//declare attributes
private string mTitle;
private string mAuthor;
private string mContent;
private string mYear;
private int mCopyNum;
private int mCallNum;
private bool mHold = false;
private bool mBorrowed = false;
private bool mShelf = false;
//overload a constructor
public CItem(int CallNum, int CopyNum, string Content, string Author, string Year)
{
callNum = CallNum;
copyNum = CopyNum;
content = Content;
author = Author;
year = Year;
}
//create the default constructor
public CItem()
{
callNum = 0;
copyNum = 0;
content = "";
author = "";
year = "";
}
//set attributes
public int callNum
{
get { return mCallNum; }
set { mCallNum = value; }
}
public string content
{
get { return mContent; }
set { mContent = value; }
}
public string author
{
get { return mAuthor; }
set { mAuthor = value; }
}
public string year
{
get { return mYear; }
set { mYear = value; }
}
public string title
{
get { return mTitle; }
set { mTitle = value; }
}
public int copyNum
{
get { return mCopyNum; }
set { mCopyNum = value; }
}
public bool hold
{
get { return mHold; }
}
public bool borrowed
{
get { return mBorrowed; }
}
public bool shelf
{
get { return mShelf; }
}
//display information for users
public string displayInfo()
{
return "Call Number: " + callNum + ". Copy Number: " + copyNum + ". Title: " + title +
". Author: " + author + ". Year Published: " + year + ". Content: " + content;
}
//new method to display status of item
public string displayStatus()
{
if (borrowed == true)
return "Item is currently being borrowed.";
if (shelf == true && hold == false)
return "Item is available for borrowing.";
else
return "Item is on hold";
}
Any help is much appreciated!
Thanks in advance.
ListAllItems shall look something like this
public string ListAllItems()
{
var sb = new StringBuilder(); // var is of type StringBuilder
mItems.ForEach(item => sb.Append(item.displayInfo());
return sb.ToString();
}
return String.Join("; ", allItems.Select(item => item.displayInfo()));
You don't provide a lot of informations on how and what informations you want in your result string.
Can't you achieve this objective with a simple loop ?
using System.Text;
(...)
public string ListAllItems()
{
StringBuilder allItems = new StringBuilder();
foreach(CItem itm in Items){
allItems.AppendLine(itm.displayInfo());
}
return allItems.ToString();
}
Stringbuilder is optional but is faster than string concatenation.
I don't normally like to add formatter methods to property bags like this. If you want the flexibility to change have many formatting implementations, you might want to make a seperate class do the formatting.
public interface IFormatter<in T>
{
string Format(T obj);
}
public class CItemFormatter : IFormatter<CItem>
{
public string Format(CItem item)
{
//formatting logic
}
}

Categories