How do I populate a LiteDB database if some of my values are null - litedb

I am populating a dataGridView from an incomplete excel spreadsheet and generating the LiteDB from the dataGridView. Before the recent update, I wasn't having any issues. Now I am getting the error 'Objects cannot be cast from DBNull to other types'. I can work around this by including dummy values in the original spreadsheet. But ultimately we need to see what information we're missing. How can I accomplish this?
public void CreateDatabase()
{
using (var db = new LiteDatabase(#"C:\Users\BThatcher\Documents\_Personal\Revit\MDL-Sheets\SheetDatabase04.db")) //< ----------------
{
var sheets = db.GetCollection<Sheet>("sheets");
foreach (DataGridViewRow row in dataGridView2.Rows)
{
var sheet = new Sheet
{
SheetSequence = Convert.ToInt32(row.Cells[0].Value),
SheetNumber = row.Cells[1].Value.ToString(),
SheetName = row.Cells[2].Value.ToString(),
AreaNumber = Convert.ToInt32(row.Cells[3].Value),
AreaName = row.Cells[4].Value.ToString(),
SheetDiscipline = row.Cells[5].Value.ToString(),
DisciplineSort = Convert.ToInt32(row.Cells[6].Value),
SheetSort = Convert.ToInt32(row.Cells[7].Value),
ModelName = row.Cells[8].Value.ToString(),
AppearsInSheetlist = row.Cells[9].Value.ToString(),
DesignedBy = row.Cells[10].Value.ToString(),
DrawnBy = row.Cells[11].Value.ToString(),
CheckedBy = row.Cells[12].Value.ToString(),
ApprovedBy = row.Cells[13].Value.ToString(),
SheetTotal = Convert.ToInt32(row.Cells[14].Value),
DesignSoftware = row.Cells[15].Value.ToString(),
HasPdf = row.Cells[16].Value.ToString(),
PdfPath = row.Cells[17].Value.ToString(),
};
sheets.Insert(sheet);
this.Close();
}
}
}

This error are not from LiteDB (there is no DBNull in LiteDB). It's possible this DBNull are getting from row.Cells[n].Value when you try to convert.
LiteDB support nulls and nullable values (like int?).

Related

Access data in Core Data using relationships and predicate

I am using Core data to store two databases that contain a relationships.
There is a logbook database and a IFRApproaches database.
A logbook entry can have multiple approaches.
An approach can only be linked to one logbook entry.
Attached is screenshots of my data model and relationships.
When the "submit" button is pressed this is the code to save the entry to the logbook, and the approaches as well.. I need the approaches (how ever many) associated with a singular entry. My question is How I can use a predicate to query the database at a later time for all the approaches associated with a various entry.
lazy var newEntry = Logbook(context: LoadData.shared.context)
if errorCount == 0 {
if modifyEntry == false {
if entryHolding.date == nil {
newEntry.date = Date()
} else {
newEntry.date = entryHolding.date
}
newEntry.aircraftID = entryHolding.aircraftID
newEntry.aircraftSelect = LoadData.shared.aircraftArray[aircraftArrayIndexPath!.row]
newEntry.categoryAndClass = newEntry.aircraftSelect?.categoryAndClass
newEntry.typeCode = entryHolding.typeCode
newEntry.from = entryHolding.from
newEntry.to = entryHolding.to
newEntry.route = entryHolding.route
newEntry.totalTime = entryHolding.totalTime
newEntry.pic = entryHolding.PIC
newEntry.sic = entryHolding.SIC
newEntry.solo = entryHolding.solo
newEntry.dual = entryHolding.dual
newEntry.crossCountry = entryHolding.crossCountry
newEntry.night = entryHolding.night
newEntry.simInstrument = entryHolding.simInstrument
newEntry.actualInstrument = entryHolding.actualInstrument
newEntry.hold = Int16(entryHolding.hold)
newEntry.dayLanding = Int16(entryHolding.dayLanding)
newEntry.nightLanding = Int16(entryHolding.nightLanding)
newEntry.bfr = entryHolding.BFR
newEntry.checkride = entryHolding.checkRide
newEntry.ipc = entryHolding.IPC
newEntry.comments = entryHolding.comments
for i in 0..<approach.count {
var newApproach = IFRApproaches(context: LoadData.shared.context)
newApproach.airport = approach[i].airportID
newApproach.typeOfApproach = approach[i].type
newApproach.runway = approach[i].runwayNum
//newApproach.entry = newEntry
newEntry.addToApproaches(newApproach)
LoadData.shared.approachArray.append(newApproach)
}
LoadData.shared.entryArray.append(newEntry)
LoadData.shared.saveData()

Corrupt records from OpenXML Spreadsheet creation

I'm trying to generate a simple XLSX file using OpenXML but I'm getting an error when I open my file and the only info in the repairedRecord part of the log file is this:
Repaired Records: Cell information from /xl/worksheets/sheet1.xml part
The strange thing is that all the cells I'm trying to write do have the value I expect them to have. I'm just trying to write a single header row right now, where the headers is just an IEnumerable<string>:
using (var doc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)) {
var workbookPart = doc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet {
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet 1"
};
sheets.Append(sheet);
workbookPart.Workbook.Save();
var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
var row = new Row { RowIndex = 1 };
var column = 1;
foreach (var header in headers)
row.AppendChild(new Cell {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.SharedString,
CellValue = new CellValue(header)
});
sheetData.Append(row);
workbookPart.Workbook.Save();
}
If you're inserting a string value, you should be using CellValues.InlineString
foreach (var header in headers)
row.AppendChild(new Cell (new InlineString(new Text(header))) {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.InlineString
});

View Criteria not returning row

I'm new to ADF BC and I'm trying to save a record in the DB.
If the record already exists, I'll update the fields if not I'll create a new row.
I'm using the same View Criteria in other methods and it works, but not in this method. Here's my code:
public String saveRecord() {
boolean isNewRow = false;
String merchId = generateIds(); //returns the correct Id, I've checked
DCIteratorBinding dc = (DCIteratorBinding)evaluteEL("#{bindings.GaeInitialSetup1Iterator}");
ViewObject vo = dc.getViewObject();
ViewCriteriaManager vcm = vo.getViewCriteriaManager();
vo.setNamedWhereClauseParam("merchId", merchId);
vcm.applyViewCriteria(vo.getViewCriteriaManager().getViewCriteria("GaeInitialSetupVOCriteria"));
vo.executeQuery();
Row rowSelected = vo.next(); //it's always null even if the record exists
if (rowSelected == null) { // null == null - leads to error when trying to insert the same Id twice
isNewRow = true;
rowSelected = vo.createRow();
rowSelected.setAttribute("MerchId", merchId);
rowSelected.setAttribute("MerchLevel", merchLevelCalc(merchId));
rowSelected.setAttribute("ParentId", parentIdCalc(merchId));
}
rowSelected.setAttribute("IpssDefault", validateIPSSDefault());
rowSelected.setAttribute("IpssBase", validateIPSSBase());
rowSelected.setAttribute("LimMinMdqPct", validateLIM_MIN_MDQ_PCT());
rowSelected.setAttribute("LimMinMdqPctNewSku", validateLIM_MIN_MDQ_PCT_NEW_SKU());
rowSelected.setAttribute("DifMdqPctMin", validateDIF_MDQ_PCT_MIN());
rowSelected.setAttribute("VarMinMdqChg", validateVAR_MIN_MDQ_CHG());
rowSelected.setAttribute("LimMinRotDays", validateLIM_MIN_ROT_DAYS());
rowSelected.setAttribute("LimMaxRotDays", validateLIM_MAX_ROT_DAYS());
rowSelected.setAttribute("DaysNewSku", validateDAYS_NEW_SKU());
rowSelected.setAttribute("IncrS1", validateINCR_S1());
rowSelected.setAttribute("IncrS2", validateINCR_S2());
rowSelected.setAttribute("IncrS3", validateINCR_S3());
rowSelected.setAttribute("IncrS4", validateINCR_S4());
rowSelected.setAttribute("ReplSuspComb", validateREPL_SUSP_COMB());
rowSelected.setAttribute("VarPctMinStkRot", validateVAR_PCT_MIN_STK_ROT());
rowSelected.setAttribute("AbcgA", validateABCG_A());
rowSelected.setAttribute("AbcgB", validateABCG_B());
rowSelected.setAttribute("AbcgC", validateABCG_C());
rowSelected.setAttribute("AbcgD", validateABCG_D());
rowSelected.setAttribute("AbcgE", validateABCG_E());
rowSelected.setAttribute("AbcgF", validateABCG_F());
rowSelected.setAttribute("AbcgG", validateABCG_G());
if (isNewRow) {
vo.insertRow(rowSelected);
}
DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
OperationBinding operationBinding = (OperationBinding)bindings.getOperationBinding("Execute");
operationBinding.execute();
OperationBinding operationBinding2 = (OperationBinding)bindings.getOperationBinding("Commit");
operationBinding2.execute();
return null;
}
What am I missing?
Your code seems perfectly right, could you try making the below mentioned changes?
vo.executeQuery();
if (vo.hasNext()) {
Row rowSelected = vo.next();
//write rest of your logic here
}
This will not have null == null check and is the best practice.
I've fixed the problem.
I removed the line: Row rowSelected = vo.next();
And I've added: Row rowSelected = vo.first();

Devexpress xtraChart How to assign x and y values?

I have values in datasource and there is no problem with datasource. I have to assign X and Y values to the chart. Chart throws an error and says there is no column with named "TotalInboundArrivals".
ChartControl chart = new ChartControl();
chart.Location = new Point(38, 301);
chart.Size = new Size(789, 168);
Series series = new Series("Series1", ViewType.Bar);
chart.Series.Add(series);
series.DataSource = ds;
series.ArgumentScaleType = ScaleType.Numerical;
series.ArgumentDataMember = "TotalInboundArrivals"; //throws error here
series.ValueScaleType = ScaleType.Numerical;
series.ValueDataMembers.AddRange(new string[] { "StartTime" }); //throws error here
((SideBySideBarSeriesView)series.View).ColorEach = true;
((XYDiagram)chart.Diagram).AxisY.Visible = true;
chart.Legend.Visible = true;
chart.Visible = true;
chart.Dock = DockStyle.Fill;
xtraTabPage1.Controls.Add(chart);
Where is my Problem? Any Suggestions?
Have you went through Series.DataSource Property. You are making the mistake of assigning DataSet as DataSource to series. Think about it, how could it search columns in Data Source. Try to assign Ds.Tables["TableName"] as the datasource.
Creating DataSource Table
private DataTable CreateChartData(int rowCount) {
// Create an empty table.
DataTable table = new DataTable("Table1");
// Add two columns to the table.
table.Columns.Add("Argument", typeof(Int32));
table.Columns.Add("Value", typeof(Int32));
// Add data rows to the table.
Random rnd = new Random();
DataRow row = null;
for (int i = 0; i < rowCount; i++) {
row = table.NewRow();
row["Argument"] = i;
row["Value"] = rnd.Next(100);
table.Rows.Add(row);
}
Specifying Series properties corresponding to datasource
Series series = new Series("Series1", ViewType.Bar);
chart.Series.Add(series);
// Generate a data table and bind the series to it.
series.DataSource = CreateChartData(50);
// Specify data members to bind the series.
series.ArgumentScaleType = ScaleType.Numerical;
series.ArgumentDataMember = "Argument";
series.ValueScaleType = ScaleType.Numerical;
series.ValueDataMembers.AddRange(new string[] { "Value" });
Check the Examples and go through the Creating Charts -> Providing Data section to better understand it.
Reference
Hope this helps.

Add Hyperlink to Cell in Excel 2007 Using Open XML SDK 2.0

I can't seem to find any documentation or code samples on how to add a hyperlink to a cell in Excel 2007 using the Open XML SDK 2.0. I am using the following code, but is there a step I am missing?
WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program");
workSheetPart.AddHyperlinkRelationship(new Uri("http://www.google.com", UriKind.Absolute), true);
workSheetPart.Worksheet.Save();
mWorkBookPart.Workbook.Save();
Then when I try and open the Excel document it says the file is corrupted because the Relationship Id for the hyperlink cannot be found. How do you setup or create that Relationship Id?
Another possibility, (which I used), is to use the HYPERLINK formula for Excel. I needed to create individual hyperlinks in each cell, yet the cells had to display different text, (I had to display tracking numbers in the cells yet have a hyperlink for each tracking number to the carrier's site and had to handle multiple carriers).
Once I instantiated an individual cell, the formula was applied in this manner to each cell (there are undoubtedly numerous way):
// ...
Cell cell1 = new Cell(){ CellReference = "A1", StyleIndex = (UInt32Value)1U, DataType = CellValues.InlineString };
CellValue cellValue1 = new CellValue();
CellFormula cellFormula1 = new CellFormula() { Space = SpaceProcessingModeValues.Preserve };
cellFormula1.Text = #"HYPERLINK(""http://www.theclash.com"", ""Radio Clash"")";
cellValue1.Text = "Radio Clash";
cell1.Append(cellFormula1);
cell1.Append(cellValue1);
// append cell, etc.
In this way, I was able to create individual hyperlinks and text for each cell. By the way, the links will appear with the default font color unless you reference a style with blue font.
Hope this helps.
I was able to add a hyperlink to a cell using System.IO.Packaging code:
private void HyperlinkCreate(PackagePart part, XmlNamespaceManager nsm, XmlNode _cellElement, string CellAddress)
{
Uri _hyperlink = new Uri("http://www.yahoo.com");
XmlNode linkParent = _cellElement.OwnerDocument.SelectSingleNode("//d:hyperlinks", nsm);
if (linkParent == null)
{
// create the hyperlinks node
linkParent = _cellElement.OwnerDocument.CreateElement("hyperlinks", #"http://schemas.openxmlformats.org/spreadsheetml/2006/main");
XmlNode prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:conditionalFormatting", nsm);
if (prevNode == null)
{
prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:mergeCells", nsm);
if (prevNode == null)
{
prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:sheetData", nsm);
}
}
_cellElement.OwnerDocument.DocumentElement.InsertAfter(linkParent, prevNode);
}
string searchString = string.Format("./d:hyperlink[#ref = '{0}']", CellAddress);
XmlElement linkNode = (XmlElement)linkParent.SelectSingleNode(searchString, nsm);
XmlAttribute attr;
if (linkNode == null)
{
linkNode = _cellElement.OwnerDocument.CreateElement("hyperlink", #"http://schemas.openxmlformats.org/spreadsheetml/2006/main");
// now add cell address attribute
linkNode.SetAttribute("ref", CellAddress);
linkParent.AppendChild(linkNode);
}
attr = (XmlAttribute)linkNode.Attributes.GetNamedItem("id", #"http://schemas.openxmlformats.org/officeDocument/2006/relationships");
if (attr == null)
{
attr = _cellElement.OwnerDocument.CreateAttribute("r", "id", #"http://schemas.openxmlformats.org/officeDocument/2006/relationships");
linkNode.Attributes.Append(attr);
}
PackageRelationship relationship = null;
string relID = attr.Value;
if (relID == "")
relationship = part.CreateRelationship(_hyperlink, TargetMode.External, #"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
else
{
relationship = part.GetRelationship(relID);
if (relationship.TargetUri != _hyperlink)
relationship = part.CreateRelationship(_hyperlink, TargetMode.External, #"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
}
attr.Value = relationship.Id;
}
I then translated this code using the Open XML SDK 2.0 and it doesn't work. It seems the AddHyperlinkRelationship method doesn't actually add the relationship to the .rels file. I'm not sure why, but it sure seems like a bug to me.
private void HyperlinkCreate(PackagePart part, XmlNamespaceManager nsm, XmlNode _cellElement, string CellAddress)
{
WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program");
Uri hyperlinkUri = new Uri("http://www.yahoo.com", UriKind.Absolute);
Hyperlinks hyperlinks = workSheetPart.Worksheet.Descendants<Hyperlinks>().FirstOrDefault();
// Check to see if the <x:hyperlinks> element exists; if not figure out
// where to insert it depending on which elements are present in the Worksheet
if (hyperlinks == null)
{
// Create the hyperlinks node
hyperlinks = new Hyperlinks();
OpenXmlCompositeElement prevElement = workSheetPart.Worksheet.Descendants<ConditionalFormatting>().FirstOrDefault();
if (prevElement == null)
{
prevElement = workSheetPart.Worksheet.Descendants<MergeCells>().FirstOrDefault();
if (prevElement == null)
{
// No FirstOrDefault needed since a Worksheet requires SheetData or the excel doc will be corrupt
prevElement = workSheetPart.Worksheet.Descendants<SheetData>().First();
}
}
workSheetPart.Worksheet.InsertAfter(hyperlinks, prevElement);
}
Hyperlink hyperlink = hyperlinks.Descendants<Hyperlink>().Where(r => r.Reference.Equals(CellAddress)).FirstOrDefault();
if (hyperlink == null)
{
hyperlink = new Hyperlink() { Reference = CellAddress, Id = string.Empty };
}
HyperlinkRelationship hyperlinkRelationship = null;
string relId = hyperlink.Id;
if (relId.Equals(string.Empty))
{
hyperlinkRelationship = workSheetPart.AddHyperlinkRelationship(hyperlinkUri, true);
}
else
{
hyperlinkRelationship = workSheetPart.GetReferenceRelationship(relId) as HyperlinkRelationship;
if (!hyperlinkRelationship.Uri.Equals(hyperlinkUri))
{
hyperlinkRelationship = workSheetPart.AddHyperlinkRelationship(hyperlinkUri, true);
}
}
hyperlink.Id = hyperlinkRelationship.Id;
hyperlinks.AppendChild<Hyperlink>(hyperlink);
workSheetPart.Worksheet.Save();
}
You should be adding it to an object that accepts hyperlinks, such as a cell, instead of the worksheet. Something like this should work for you:
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace GeneratedCode
{
public class GeneratedClass
{
// Creates an Worksheet instance and adds its children.
public Worksheet GenerateWorksheet()
{
Worksheet worksheet1 = new Worksheet(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x14ac" } };
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
worksheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
worksheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
SheetDimension sheetDimension1 = new SheetDimension(){ Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView(){ TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 14.4D, DyDescent = 0.3D };
SheetData sheetData1 = new SheetData();
Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" }, DyDescent = 0.3D };
Cell cell1 = new Cell(){ CellReference = "A1", StyleIndex = (UInt32Value)1U, DataType = CellValues.SharedString };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "0";
cell1.Append(cellValue1);
row1.Append(cell1);
sheetData1.Append(row1);
Hyperlinks hyperlinks1 = new Hyperlinks();
Hyperlink hyperlink1 = new Hyperlink(){ Reference = "A1", Id = "rId1" };
hyperlinks1.Append(hyperlink1);
PageMargins pageMargins1 = new PageMargins(){ Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
worksheet1.Append(sheetDimension1);
worksheet1.Append(sheetViews1);
worksheet1.Append(sheetFormatProperties1);
worksheet1.Append(sheetData1);
worksheet1.Append(hyperlinks1);
worksheet1.Append(pageMargins1);
return worksheet1;
}
}
}
Easiest way is to use the HyperLink formular, but the links aren't blue by default, this is why the styleIndex is set.
private Cell BuildHyperlinkCell(string url) =>
new Cell
{
DataType = new EnumValue<CellValues>(CellValues.String),
CellFormula = new CellFormula($"HyperLink(\"{url}\")"),
StyleIndex = 4u
};
Adding the styling to the workbook:
http://www.dispatchertimer.com/tutorial/how-to-create-an-excel-file-in-net-using-openxml-part-3-add-stylesheet-to-the-spreadsheet/