I have 3 methods that do same stuff. One difference, they work with different models.
Here is the methods code:
public IEnumerable<PropertyImportDto> ImportStandardCsv(string fileData)
{
List<PropertyImportDto> data;
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1))))
{
using (var streamWriter = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamWriter))
{
var records = csvReader.GetRecords<PropertyImportDto>();
data = records.ToList();
}
}
return data;
}
public IEnumerable<ArthurPropertiesImportDto> ImportArthurCsv(string fileData)
{
List<ArthurPropertiesImportDto> data;
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1))))
{
using (var streamWriter = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamWriter))
{
var records = csvReader.GetRecords<ArthurPropertiesImportDto>();
data = records.ToList();
}
}
return data;
}
public IEnumerable<LandlordVisionImportDto> ImportLandlordVision(string fileData)
{
List<LandlordVisionImportDto> data;
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1))))
{
using (var streamWriter = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamWriter))
{
var records = csvReader.GetRecords<LandlordVisionImportDto>();
data = records.ToList();
}
}
return data;
}
And I call it like this
public async Task ImportProperties(PM101ImportDto input)
{
switch (input.fileTypeId)
{
case 1:
{
var properties = _csvAppService.ImportStandardCsv(input.FileBase64);
foreach (var item in properties)
{
var property = new Property
{
PropertyTypeId = 1,
BuildingTypeId = 12,
PhoneNumber = item.PhoneNumber,
PropertyTitleId = 1,
AccountManagerId = AbpSession.TenantId,
Addresses = new List<PropertyAddress>
{
new PropertyAddress
{
Line1 = item.Line1,
Line2 = item.Line2,
Line3 = item.Line3,
PostCode = item.PostalCode,
PostTown = item.Town,
Country = item.Country,
County = item.County,
Latitude = item.Latitude,
Longitude = item.Longitude
},
},
Sites = new List<Site>
{
new Site
{
NumberOfWindows = 0,
NumberOfBedRooms = 0,
ApproximateYearBuilt = 1970,
PropertyAge = 50,
FuelTypeId = 1,
ParkingTypeId = 1,
FurnishingTypeId = 1
}
},
MarketingInformation = new List<PropertyMarketingInformation>
{
new PropertyMarketingInformation
{
MarketingDescription = "", IsBillsIncluded = false
}
}
};
await _propertyRepository.InsertAsync(property);
}
break;
}
case 2:
{
var properties = _csvAppService.ImportLandlordVision(input.FileBase64);
foreach (var item in properties)
{
var property = new Property
{
PropertyTypeId = 1,
BuildingTypeId = 12,
PropertyTitleId = 1,
AccountManagerId = AbpSession.TenantId,
Addresses = new List<PropertyAddress>
{
new PropertyAddress
{
Line1 = item.Line1,
Line2 = item.Line2,
PostCode = item.PostCode,
PostTown = item.Town,
County = item.County
}
},
Sites = new List<Site>
{
new Site
{
NumberOfWindows = 0,
NumberOfBedRooms = 0,
ApproximateYearBuilt = 1970,
PropertyAge = 50,
FuelTypeId = 1,
ParkingTypeId = 1,
FurnishingTypeId = 1
}
},
MarketingInformation = new List<PropertyMarketingInformation>
{
new PropertyMarketingInformation
{
MarketingDescription = "", IsBillsIncluded = false
}
}
};
await _propertyRepository.InsertAsync(property);
}
break;
}
case 3:
{
var properties = _csvAppService.ImportArthurCsv(input.FileBase64);
foreach (var item in properties)
{
var property = new Property
{
PropertyTypeId = 1,
BuildingTypeId = 12,
PropertyTitleId = 1,
AccountManagerId = AbpSession.TenantId,
Addresses = new List<PropertyAddress>
{
new PropertyAddress
{
Line1 = item.Line1,
Line2 = item.Line2,
Line3 = item.Line3,
PostCode = item.PostCode,
PostTown = item.City,
County = item.County,
Country = item.Country,
Latitude = item.Latitude,
Longitude = item.Longitude
}
},
Sites = new List<Site>
{
new Site
{
NumberOfWindows = 0,
NumberOfBedRooms = 0,
ApproximateYearBuilt = 1970,
PropertyAge = 50,
FuelTypeId = 1,
ParkingTypeId = 1,
FurnishingTypeId = 1
}
},
MarketingInformation = new List<PropertyMarketingInformation>
{
new PropertyMarketingInformation
{
MarketingDescription = "", IsBillsIncluded = false
}
}
};
await _propertyRepository.InsertAsync(property);
}
}
break;
}
}
How I can rewrite those 3 methods to one gneric method?
Typical use case for generic type parameters
public IEnumerable<T> ImportStandardCsv<T>(string fileData)
{
var bytes = Convert.FromBase64String(fileData.Substring(fileData.IndexOf(',') + 1));
using (var memoryStream = new MemoryStream(bytes))
using (var streamReader = new StreamReader(memoryStream))
using (var csvReader = new CsvReader(streamReader))
return csvReader.GetRecords<T>();
}
call
IEnumerable<PropertyImportDto> result = ImportStandardCsv<PropertyImportDto>(input.FileBase64);
Related
I am looking to adjust the template project to add an opening for the door so the door will be flush with the wall system instead of appearing embedded in the skin of the wall any help would be very appreciated.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xbim.Common;
using Xbim.Common.Step21;
using Xbim.Ifc;
using Xbim.IO;
using Xbim.Ifc4.ActorResource;
using Xbim.Ifc4.DateTimeResource;
using Xbim.Ifc4.ExternalReferenceResource;
using Xbim.Ifc4.PresentationOrganizationResource;
using Xbim.Ifc4.GeometricConstraintResource;
using Xbim.Ifc4.GeometricModelResource;
using Xbim.Ifc4.GeometryResource;
using Xbim.Ifc4.Interfaces;
using Xbim.Ifc4.Kernel;
using Xbim.Ifc4.MaterialResource;
using Xbim.Ifc4.MeasureResource;
using Xbim.Ifc4.ProductExtension;
using Xbim.Ifc4.ProfileResource;
using Xbim.Ifc4.PropertyResource;
using Xbim.Ifc4.QuantityResource;
using Xbim.Ifc4.RepresentationResource;
using Xbim.Ifc4.SharedBldgElements;
namespace HelloWall
{
class Program
{
/// <summary>
/// This sample demonstrates the minimum steps to create a compliant IFC model that contains a single standard case wall
/// </summary>
static int Main()
{
//first create and initialise a model called Hello Wall
Console.WriteLine("Initialising the IFC Project....");
using (var model = CreateandInitModel("HelloWall"))
{
if (model != null)
{
IfcBuilding building = CreateBuilding(model, "Default Building");
IfcWallStandardCase wall = CreateWall(model, 4000, 300, 2400);
if (wall != null) AddPropertiesToWall(model, wall);
using (var txn = model.BeginTransaction("Add Wall"))
{
building.AddElement(wall);
txn.Commit();
}
if (wall != null)
{
try
{
Console.WriteLine("Standard Wall successfully created....");
//write the Ifc File
model.SaveAs("HelloWallIfc4.ifc", IfcStorageType.Ifc);
Console.WriteLine("HelloWallIfc4.ifc has been successfully written");
}
catch (Exception e)
{
Console.WriteLine("Failed to save HelloWall.ifc");
Console.WriteLine(e.Message);
}
}
}
else
{
Console.WriteLine("Failed to initialise the model");
}
}
Console.WriteLine("Press any key to exit to view the IFC file....");
Console.ReadKey();
LaunchNotepad("HelloWallIfc4.ifc");
return 0;
}
private static void LaunchNotepad(string fileName)
{
Process p;
try
{
p = new Process {StartInfo = {FileName = fileName, CreateNoWindow = false}};
p.Start();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}",
ex.Message, ex.StackTrace);
}
}
private static IfcBuilding CreateBuilding(IfcStore model, string name)
{
using (var txn = model.BeginTransaction("Create Building"))
{
var building = model.Instances.New<IfcBuilding>();
building.Name = name;
building.CompositionType = IfcElementCompositionEnum.ELEMENT;
var localPlacement = model.Instances.New<IfcLocalPlacement>();
building.ObjectPlacement = localPlacement;
var placement = model.Instances.New<IfcAxis2Placement3D>();
localPlacement.RelativePlacement = placement;
placement.Location = model.Instances.New<IfcCartesianPoint>(p=>p.SetXYZ(0,0,0));
//get the project there should only be one and it should exist
var project = model.Instances.OfType<IfcProject>().FirstOrDefault();
project?.AddBuilding(building);
txn.Commit();
return building;
}
}
/// <summary>
/// Sets up the basic parameters any model must provide, units, ownership etc
/// </summary>
/// <param name="projectName">Name of the project</param>
/// <returns></returns>
private static IfcStore CreateandInitModel(string projectName)
{
//first we need to set up some credentials for ownership of data in the new model
var credentials = new XbimEditorCredentials
{
ApplicationDevelopersName = "xbim developer",
ApplicationFullName = "Hello Wall Application",
ApplicationIdentifier = "HelloWall.exe",
ApplicationVersion = "1.0",
EditorsFamilyName = "Team",
EditorsGivenName = "xbim",
EditorsOrganisationName = "xbim developer"
};
//now we can create an IfcStore, it is in Ifc4 format and will be held in memory rather than in a database
//database is normally better in performance terms if the model is large >50MB of Ifc or if robust transactions are required
var model = IfcStore.Create(credentials, IfcSchemaVersion.Ifc4,XbimStoreType.InMemoryModel);
//Begin a transaction as all changes to a model are ACID
using (var txn = model.BeginTransaction("Initialise Model"))
{
//create a project
var project = model.Instances.New<IfcProject>();
//set the units to SI (mm and metres)
project.Initialize(ProjectUnits.SIUnitsUK);
project.Name = projectName;
//now commit the changes, else they will be rolled back at the end of the scope of the using statement
txn.Commit();
}
return model;
}
/// <summary>
/// This creates a wall and it's geometry, many geometric representations are possible and extruded rectangular footprint is chosen as this is commonly used for standard case walls
/// </summary>
/// <param name="model"></param>
/// <param name="length">Length of the rectangular footprint</param>
/// <param name="width">Width of the rectangular footprint (width of the wall)</param>
/// <param name="height">Height to extrude the wall, extrusion is vertical</param>
/// <returns></returns>
static private IfcWallStandardCase CreateWall(IfcStore model, double length, double width, double height)
{
//
//begin a transaction
using (var txn = model.BeginTransaction("Create Wall"))
{
var wall = model.Instances.New<IfcWallStandardCase>();
wall.Name = "A Standard rectangular wall";
//represent wall as a rectangular profile
var rectProf = model.Instances.New<IfcRectangleProfileDef>();
rectProf.ProfileType = IfcProfileTypeEnum.AREA;
rectProf.XDim = width;
rectProf.YDim = length;
var insertPoint = model.Instances.New<IfcCartesianPoint>();
insertPoint.SetXY(0, 400); //insert at arbitrary position
rectProf.Position = model.Instances.New<IfcAxis2Placement2D>();
rectProf.Position.Location = insertPoint;
//model as a swept area solid
var body = model.Instances.New<IfcExtrudedAreaSolid>();
body.Depth = height;
body.SweptArea = rectProf;
body.ExtrudedDirection = model.Instances.New<IfcDirection>();
body.ExtrudedDirection.SetXYZ(0, 0, 1);
//parameters to insert the geometry in the model
var origin = model.Instances.New<IfcCartesianPoint>();
origin.SetXYZ(0, 0, 0);
body.Position = model.Instances.New<IfcAxis2Placement3D>();
body.Position.Location = origin;
//Create a Definition shape to hold the geometry
var shape = model.Instances.New<IfcShapeRepresentation>();
var modelContext = model.Instances.OfType<IfcGeometricRepresentationContext>().FirstOrDefault();
shape.ContextOfItems = modelContext;
shape.RepresentationType = "SweptSolid";
shape.RepresentationIdentifier = "Body";
shape.Items.Add(body);
//Create a Product Definition and add the model geometry to the wall
var rep = model.Instances.New<IfcProductDefinitionShape>();
rep.Representations.Add(shape);
wall.Representation = rep;
//now place the wall into the model
var lp = model.Instances.New<IfcLocalPlacement>();
var ax3D = model.Instances.New<IfcAxis2Placement3D>();
ax3D.Location = origin;
ax3D.RefDirection = model.Instances.New<IfcDirection>();
ax3D.RefDirection.SetXYZ(0, 1, 0);
ax3D.Axis = model.Instances.New<IfcDirection>();
ax3D.Axis.SetXYZ(0, 0, 1);
lp.RelativePlacement = ax3D;
wall.ObjectPlacement = lp;
// Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
var ifcMaterialLayerSetUsage = model.Instances.New<IfcMaterialLayerSetUsage>();
var ifcMaterialLayerSet = model.Instances.New<IfcMaterialLayerSet>();
var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>();
ifcMaterialLayer.LayerThickness = 10;
ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
ifcMaterialLayerSetUsage.ForLayerSet = ifcMaterialLayerSet;
ifcMaterialLayerSetUsage.LayerSetDirection = IfcLayerSetDirectionEnum.AXIS2;
ifcMaterialLayerSetUsage.DirectionSense = IfcDirectionSenseEnum.NEGATIVE;
ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;
// Add material to wall
var material = model.Instances.New<IfcMaterial>();
material.Name = "some material";
var ifcRelAssociatesMaterial = model.Instances.New<IfcRelAssociatesMaterial>();
ifcRelAssociatesMaterial.RelatingMaterial = material;
ifcRelAssociatesMaterial.RelatedObjects.Add(wall);
ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;
// IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
var ifcPresentationLayerAssignment = model.Instances.New<IfcPresentationLayerAssignment>();
ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
ifcPresentationLayerAssignment.AssignedItems.Add(shape);
// linear segment as IfcPolyline with two points is required for IfcWall
var ifcPolyline = model.Instances.New<IfcPolyline>();
var startPoint = model.Instances.New<IfcCartesianPoint>();
startPoint.SetXY(0, 0);
var endPoint = model.Instances.New<IfcCartesianPoint>();
endPoint.SetXY(4000, 0);
ifcPolyline.Points.Add(startPoint);
ifcPolyline.Points.Add(endPoint);
var shape2D = model.Instances.New<IfcShapeRepresentation>();
shape2D.ContextOfItems = modelContext;
shape2D.RepresentationIdentifier = "Axis";
shape2D.RepresentationType = "Curve2D";
shape2D.Items.Add(ifcPolyline);
rep.Representations.Add(shape2D);
txn.Commit();
return wall;
}
}
/// <summary>
/// Add some properties to the wall,
/// </summary>
/// <param name="model">XbimModel</param>
/// <param name="wall"></param>
static private void AddPropertiesToWall(IfcStore model, IfcWallStandardCase wall)
{
using (var txn = model.BeginTransaction("Create Wall"))
{
CreateElementQuantity(model, wall);
CreateSimpleProperty(model, wall);
txn.Commit();
}
}
private static void CreateSimpleProperty(IfcStore model, IfcWallStandardCase wall)
{
var ifcPropertySingleValue = model.Instances.New<IfcPropertySingleValue>(psv =>
{
psv.Name = "IfcPropertySingleValue:Time";
psv.Description = "";
psv.NominalValue = new IfcTimeMeasure(150.0);
psv.Unit = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.TIMEUNIT;
siu.Name = IfcSIUnitName.SECOND;
});
});
var ifcPropertyEnumeratedValue = model.Instances.New<IfcPropertyEnumeratedValue>(pev =>
{
pev.Name = "IfcPropertyEnumeratedValue:Music";
pev.EnumerationReference = model.Instances.New<IfcPropertyEnumeration>(pe =>
{
pe.Name = "Notes";
pe.EnumerationValues.Add(new IfcLabel("Do"));
pe.EnumerationValues.Add(new IfcLabel("Re"));
pe.EnumerationValues.Add(new IfcLabel("Mi"));
pe.EnumerationValues.Add(new IfcLabel("Fa"));
pe.EnumerationValues.Add(new IfcLabel("So"));
pe.EnumerationValues.Add(new IfcLabel("La"));
pe.EnumerationValues.Add(new IfcLabel("Ti"));
});
pev.EnumerationValues.Add(new IfcLabel("Do"));
pev.EnumerationValues.Add(new IfcLabel("Re"));
pev.EnumerationValues.Add(new IfcLabel("Mi"));
});
var ifcPropertyBoundedValue = model.Instances.New<IfcPropertyBoundedValue>(pbv =>
{
pbv.Name = "IfcPropertyBoundedValue:Mass";
pbv.Description = "";
pbv.UpperBoundValue = new IfcMassMeasure(5000.0);
pbv.LowerBoundValue = new IfcMassMeasure(1000.0);
pbv.Unit = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.MASSUNIT;
siu.Name = IfcSIUnitName.GRAM;
siu.Prefix = IfcSIPrefix.KILO;
});
});
var definingValues = new List<IfcReal> { new IfcReal(100.0), new IfcReal(200.0), new IfcReal(400.0), new IfcReal(800.0), new IfcReal(1600.0), new IfcReal(3200.0), };
var definedValues = new List<IfcReal> { new IfcReal(20.0), new IfcReal(42.0), new IfcReal(46.0), new IfcReal(56.0), new IfcReal(60.0), new IfcReal(65.0), };
var ifcPropertyTableValue = model.Instances.New<IfcPropertyTableValue>(ptv =>
{
ptv.Name = "IfcPropertyTableValue:Sound";
foreach (var item in definingValues)
{
ptv.DefiningValues.Add(item);
}
foreach (var item in definedValues)
{
ptv.DefinedValues.Add(item);
}
ptv.DefinedUnit = model.Instances.New<IfcContextDependentUnit>(cd =>
{
cd.Dimensions = model.Instances.New<IfcDimensionalExponents>(de =>
{
de.LengthExponent = 0;
de.MassExponent = 0;
de.TimeExponent = 0;
de.ElectricCurrentExponent = 0;
de.ThermodynamicTemperatureExponent = 0;
de.AmountOfSubstanceExponent = 0;
de.LuminousIntensityExponent = 0;
});
cd.UnitType = IfcUnitEnum.FREQUENCYUNIT;
cd.Name = "dB";
});
});
var listValues = new List<IfcLabel> { new IfcLabel("Red"), new IfcLabel("Green"), new IfcLabel("Blue"), new IfcLabel("Pink"), new IfcLabel("White"), new IfcLabel("Black"), };
var ifcPropertyListValue = model.Instances.New<IfcPropertyListValue>(plv =>
{
plv.Name = "IfcPropertyListValue:Colours";
foreach (var item in listValues)
{
plv.ListValues.Add(item);
}
});
var ifcMaterial = model.Instances.New<IfcMaterial>(m =>
{
m.Name = "Brick";
});
var ifcPrValueMaterial = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Material";
prv.PropertyReference = ifcMaterial;
});
var ifcMaterialList = model.Instances.New<IfcMaterialList>(ml =>
{
ml.Materials.Add(ifcMaterial);
ml.Materials.Add(model.Instances.New<IfcMaterial>(m =>{m.Name = "Cavity";}));
ml.Materials.Add(model.Instances.New<IfcMaterial>(m => { m.Name = "Block"; }));
});
var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>(ml =>
{
ml.Material = ifcMaterial;
ml.LayerThickness = 100.0;
});
var ifcPrValueMatLayer = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:MaterialLayer";
prv.PropertyReference = ifcMaterialLayer;
});
var ifcDocumentReference = model.Instances.New<IfcDocumentReference>(dr =>
{
dr.Name = "Document";
dr.Location = "c://Documents//TheDoc.Txt";
});
var ifcPrValueRef = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Document";
prv.PropertyReference = ifcDocumentReference;
});
var ifcTimeSeries = model.Instances.New<IfcRegularTimeSeries>(ts =>
{
ts.Name = "Regular Time Series";
ts.Description = "Time series of events";
ts.StartTime = new IfcDateTime("2015-02-14T12:01:01");
ts.EndTime = new IfcDateTime("2015-05-15T12:01:01");
ts.TimeSeriesDataType = IfcTimeSeriesDataTypeEnum.CONTINUOUS;
ts.DataOrigin = IfcDataOriginEnum.MEASURED;
ts.TimeStep = 604800; //7 days in secs
});
var ifcPrValueTimeSeries = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:TimeSeries";
prv.PropertyReference = ifcTimeSeries;
});
var ifcAddress = model.Instances.New<IfcPostalAddress>(a =>
{
a.InternalLocation = "Room 101";
a.AddressLines.AddRange(new[] { new IfcLabel("12 New road"), new IfcLabel("DoxField" ) });
a.Town = "Sunderland";
a.PostalCode = "DL01 6SX";
});
var ifcPrValueAddress = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Address";
prv.PropertyReference = ifcAddress;
});
var ifcTelecomAddress = model.Instances.New<IfcTelecomAddress>(a =>
{
a.TelephoneNumbers.Add(new IfcLabel("01325 6589965"));
a.ElectronicMailAddresses.Add(new IfcLabel("bob#bobsworks.com"));
});
var ifcPrValueTelecom = model.Instances.New<IfcPropertyReferenceValue>(prv =>
{
prv.Name = "IfcPropertyReferenceValue:Telecom";
prv.PropertyReference = ifcTelecomAddress;
});
//lets create the IfcElementQuantity
var ifcPropertySet = model.Instances.New<IfcPropertySet>(ps =>
{
ps.Name = "Test:IfcPropertySet";
ps.Description = "Property Set";
ps.HasProperties.Add(ifcPropertySingleValue);
ps.HasProperties.Add(ifcPropertyEnumeratedValue);
ps.HasProperties.Add(ifcPropertyBoundedValue);
ps.HasProperties.Add(ifcPropertyTableValue);
ps.HasProperties.Add(ifcPropertyListValue);
ps.HasProperties.Add(ifcPrValueMaterial);
ps.HasProperties.Add(ifcPrValueMatLayer);
ps.HasProperties.Add(ifcPrValueRef);
ps.HasProperties.Add(ifcPrValueTimeSeries);
ps.HasProperties.Add(ifcPrValueAddress);
ps.HasProperties.Add(ifcPrValueTelecom);
});
//need to create the relationship
model.Instances.New<IfcRelDefinesByProperties>(rdbp =>
{
rdbp.Name = "Property Association";
rdbp.Description = "IfcPropertySet associated to wall";
rdbp.RelatedObjects.Add(wall);
rdbp.RelatingPropertyDefinition = ifcPropertySet;
});
}
private static void CreateElementQuantity(IfcStore model, IfcWallStandardCase wall)
{
//Create a IfcElementQuantity
//first we need a IfcPhysicalSimpleQuantity,first will use IfcQuantityLength
var ifcQuantityArea = model.Instances.New<IfcQuantityLength>(qa =>
{
qa.Name = "IfcQuantityArea:Area";
qa.Description = "";
qa.Unit = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.LENGTHUNIT;
siu.Prefix = IfcSIPrefix.MILLI;
siu.Name = IfcSIUnitName.METRE;
});
qa.LengthValue = 100.0;
});
//next quantity IfcQuantityCount using IfcContextDependentUnit
var ifcContextDependentUnit = model.Instances.New<IfcContextDependentUnit>(cd =>
{
cd.Dimensions = model.Instances.New<IfcDimensionalExponents>(de =>
{
de.LengthExponent = 1;
de.MassExponent = 0;
de.TimeExponent = 0;
de.ElectricCurrentExponent = 0;
de.ThermodynamicTemperatureExponent = 0;
de.AmountOfSubstanceExponent = 0;
de.LuminousIntensityExponent = 0;
});
cd.UnitType = IfcUnitEnum.LENGTHUNIT;
cd.Name = "Elephants";
});
var ifcQuantityCount = model.Instances.New<IfcQuantityCount>(qc =>
{
qc.Name = "IfcQuantityCount:Elephant";
qc.CountValue = 12;
qc.Unit = ifcContextDependentUnit;
});
//next quantity IfcQuantityLength using IfcConversionBasedUnit
var ifcConversionBasedUnit = model.Instances.New<IfcConversionBasedUnit>(cbu =>
{
cbu.ConversionFactor = model.Instances.New<IfcMeasureWithUnit>(mu =>
{
mu.ValueComponent = new IfcRatioMeasure(25.4);
mu.UnitComponent = model.Instances.New<IfcSIUnit>(siu =>
{
siu.UnitType = IfcUnitEnum.LENGTHUNIT;
siu.Prefix = IfcSIPrefix.MILLI;
siu.Name = IfcSIUnitName.METRE;
});
});
cbu.Dimensions = model.Instances.New<IfcDimensionalExponents>(de =>
{
de.LengthExponent = 1;
de.MassExponent = 0;
de.TimeExponent = 0;
de.ElectricCurrentExponent = 0;
de.ThermodynamicTemperatureExponent = 0;
de.AmountOfSubstanceExponent = 0;
de.LuminousIntensityExponent = 0;
});
cbu.UnitType = IfcUnitEnum.LENGTHUNIT;
cbu.Name = "Inch";
});
var ifcQuantityLength = model.Instances.New<IfcQuantityLength>(qa =>
{
qa.Name = "IfcQuantityLength:Length";
qa.Description = "";
qa.Unit = ifcConversionBasedUnit;
qa.LengthValue = 24.0;
});
//lets create the IfcElementQuantity
var ifcElementQuantity = model.Instances.New<IfcElementQuantity>(eq =>
{
eq.Name = "Test:IfcElementQuantity";
eq.Description = "Measurement quantity";
eq.Quantities.Add(ifcQuantityArea);
eq.Quantities.Add(ifcQuantityCount);
eq.Quantities.Add(ifcQuantityLength);
});
//need to create the relationship
model.Instances.New<IfcRelDefinesByProperties>(rdbp =>
{
rdbp.Name = "Area Association";
rdbp.Description = "IfcElementQuantity associated to wall";
rdbp.RelatedObjects.Add(wall);
rdbp.RelatingPropertyDefinition = ifcElementQuantity;
});
}
}
}
I will also have questions about assigning materials in the future but for now, I really need help with the opening.
In a list i have 4 rows and I am try to get all the rows of the list but it is giving only one row, how to get all the rows of the list.
I have tried below code
public async Task<ResponseUserModel> get()
{
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
using (nae2sasqld0003Entities context = new nae2sasqld0003Entities())
{
var listt = context.Producers.Select(all => all).ToList();
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
}
}
please let me know where i to fix the issue
Use list to return all:
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
then
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
Note: change return type of the method to IList<ResponseUserModel>
or in this way
using (var context = new nae2sasqld0003Entities())
{
return context.Producers.Select(item =>
new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
}).ToList();
}
I'm using the following code:
DynamoDBContextConfig config = new DynamoDBContextConfig()
{
ConsistentRead = false,
Conversion = DynamoDBEntryConversion.V2
};
using (DynamoDBContext context = new DynamoDBContext(config))
{
long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
QTrackStatus qTrackStatus = new QTrackStatus()
{
Key = "m#m.com",
EventCode = "CC",
EventDateTime = "2019-09-09 14:00:30",
EventLocation = "BFS",
EventLastUpdate = unixTimestamp
};
DynamoDBOperationConfig dynamoDBOperationConfig = new DynamoDBOperationConfig()
{
QueryFilter = new List<ScanCondition>()
{
{ new ScanCondition("EventCode", ScanOperator.NotEqual, "CC") }
},
ConditionalOperator = ConditionalOperatorValues.And
};
await context.SaveAsync(qTrackStatus, dynamoDBOperationConfig);
}
What I'm trying to do is only save the record if the EventCode is not CC. Currently it's always saving. I could retrieve the record first, do a check and then call SaveAsync if required - however I'd like to do it all in the SaveAsync call. Is this possible?
Unless I've missed something, it doesn't look like this is possible with the higher level api. I ended up re-factoring to the following:
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
{
TableName = "QTrackStatus",
ReturnValues = ReturnValue.ALL_NEW,
ConditionExpression = "EventCode <> :ec",
UpdateExpression = "SET EventCode = :ec, EventDateTime = :edt, EventLocation = :el, EventLastUpdate = :elu",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{ ":ec", new AttributeValue("CC") },
{ ":edt", new AttributeValue("2019-09-09 14:00:30") },
{ ":el", new AttributeValue("BFS") },
{ ":elu", new AttributeValue() { N = ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString() } }
},
Key = new Dictionary<string, AttributeValue>()
{
{ "Key", new AttributeValue("m#m.com") }
}
};
try
{
UpdateItemResponse updateItemResponse = await client.UpdateItemAsync(updateItemRequest);
}
catch(ConditionalCheckFailedException e)
{
}
This allows me to achieve my goal.
I want to create pie chart on Excel using OpenXml. Is there any source from where i can get help?.
I have already developed the Bar Chart.
Here's my reference:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using C = DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
I'm using here MemoryStream to create excel file:
WorkbookPart workbookPart = null;
using (var memoryStream = new MemoryStream())
{
using (var excel = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true))
{
workbookPart = excel.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
string relationshipId = "rId1";// workbookPart.GetIdOfPart(worksheetPart);
Sheets sheets = new Sheets();
uint sheetId = 1;
string sheetName = "Sheet" + sheetId;
Sheet sheet1 = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet1);
workbookPart.Workbook.Append(sheets);
//// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{
Id = worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save();
string chartTitle = "Generator Utilisation";
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("Running", 92);
data.Add("Stopped", 8);
InsertPieChartInSpreadSheet(drawingsPart, chartTitle, data, 1, 1, 17, 8);
excel.Close();
}
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Plant Summary Report.xlsx", FileMode.Create, FileAccess.Write);
memoryStream.WriteTo(fileStream);
fileStream.Close();
memoryStream.Close();
}
Here is InsertPieChartInSpreadSheet method:
private static void InsertPieChartInSpreadSheet(DrawingsPart drawingsPart,string chartTitle, Dictionary<string, int> data, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
ChartSpace chartSpace = new ChartSpace();
chartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
ManualLayout manualLayout1 = new ManualLayout();
LayoutTarget layoutTarget1 = new LayoutTarget() { Val = LayoutTargetValues.Inner };
LeftMode leftMode1 = new LeftMode() { Val = LayoutModeValues.Edge };
TopMode topMode1 = new TopMode() { Val = LayoutModeValues.Edge };
Left left1 = new Left() { Val = 0.5D };
Top top1 = new Top() { Val = 0.2D };
Width width1 = new Width() { Val = 0.95622038461448768D };
Height height1 = new Height() { Val = 0.54928769841269842D };
manualLayout1.Append(layoutTarget1);
manualLayout1.Append(leftMode1);
manualLayout1.Append(topMode1);
manualLayout1.Append(left1);
manualLayout1.Append(top1);
manualLayout1.Append(width1);
manualLayout1.Append(height1);
layout.Append(manualLayout1);
NoFill noFill = new NoFill();
C.ShapeProperties shapeProperties = new C.ShapeProperties();
DocumentFormat.OpenXml.Drawing.Outline outline15 = new DocumentFormat.OpenXml.Drawing.Outline();
DocumentFormat.OpenXml.Drawing.SolidFill noFill17 = new DocumentFormat.OpenXml.Drawing.SolidFill();
RgbColorModelHex schemeColor29 = new RgbColorModelHex() { Val = "FFFFFF" };
noFill17.Append(schemeColor29);
outline15.Append(noFill17);
shapeProperties.Append(noFill);
shapeProperties.Append(outline15);
plotArea.Append(shapeProperties);
PieChart pieChart = plotArea.AppendChild<PieChart>(new PieChart());
PieChartSeries pieChartSeries = pieChart.AppendChild<PieChartSeries>(new PieChartSeries(
new Index() { Val = (UInt32Value)0U },
new Order() { Val = (UInt32Value)0U },
new SeriesText(new NumericValue() { Text = "PieChartSeries" })));
CategoryAxisData catAx = new CategoryAxisData();
StringReference stringReference = new StringReference();
StringCache stringCache = new StringCache();
PointCount pointCount = new PointCount() { Val = (uint)data.Count };
stringCache.Append(pointCount);
uint i = 0;
foreach (var key in data.Keys)
{
stringCache.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(key));
i++;
}
stringReference.Append(stringCache);
catAx.Append(stringReference);
pieChartSeries.Append(catAx);
C.Values values = new C.Values();
NumberReference numberReference = new NumberReference();
NumberingCache numberingCache = new NumberingCache();
i = 0;
foreach (var key in data.Keys)
{
numberingCache.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(data[key].ToString()));
i++;
}
numberReference.Append(numberingCache);
values.Append(numberReference);
pieChartSeries.Append(values);
AddChartTitle(chart, chartTitle);
pieChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
pieChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
CategoryAxis catAx1 = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId()
{ Val = new UInt32Value(48650112u) }, new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Center) },
new LabelOffset() { Val = new UInt16Value((ushort)100) }));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>
(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
// Add the chart Legend.
Legend legend = chart.AppendChild<Legend>(new Legend(new LegendPosition() { Val = new EnumValue<LegendPositionValues>(LegendPositionValues.Bottom) },
new Layout()));
chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) });
chartPart.ChartSpace = chartSpace;
PositionChart(chartPart, drawingsPart, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
}
Here's an additional method which will set chart position:
private static void PositionChart(ChartPart chartPart, DrawingsPart drawingsPart, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId(startColumnIndex.ToString()),
new ColumnOffset("581025"),
new RowId(startRowIndex.ToString()),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId(endColumnIndex.ToString()),
new ColumnOffset("276225"),
new RowId(endRowIndex.ToString()),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) })
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
}
This method will add chart title:
private static void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart, string title)
{
var ctitle = chart.AppendChild(new Title());
var chartText = ctitle.AppendChild(new ChartText());
var richText = chartText.AppendChild(new RichText());
var bodyPr = richText.AppendChild(new BodyProperties());
var lstStyle = richText.AppendChild(new ListStyle());
var paragraph = richText.AppendChild(new Paragraph());
var apPr = paragraph.AppendChild(new ParagraphProperties());
apPr.AppendChild(new DefaultRunProperties());
var run = paragraph.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "en-CA" });
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text() { Text = title });
//ctitle.AppendChild(new Overlay() { Val = new BooleanValue(false) });
}
I need to use several filters (range and terms) for query request with ElasticSearch 5.1. If I use them separately (only one filter) it is OK:
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
}
}
}
}
};
OR
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
}
};
If I use them both I get response 400 error:
string url = "http://localhost:9200/neg_collector/posts/_search";
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
},
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
}
};
request.Method = "POST";
var jsonObj = JsonConvert.SerializeObject(o);
var data = Encoding.UTF8.GetBytes(jsonObj);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseString = string.Empty;
var response = (HttpWebResponse)request.GetResponse();
What am I doing wrong? Thank you
Your filter simply needs to be an array of objects:
...
filter = new object[]
{
new {
terms = new
{
SourceId = new[] {10,11,12}
}
},
new {
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}