Object optimization and grouping - c#

I have objects that are defined this way:
class BFull
{
public string ImageID { get; set; }
public List<string> Tapes { get; set; }
}
class OptSet
{
public int SetID { get; set; }
public List<string> Tapes { get; set; }
public List<string> Images { get; set; }
}
The BFull object is DB defined and I can't alter it much. The second one is the wanted result of my actions. And the problem is:
I need to optimize those BFulls into OptSets with a limitation that any given OptSet can have max 24 distinct tapes and consist only complete BFulls. Can anybody help how to achieve that?

Related

C# DTO List that consists of 2 other lists

Firstly, apologies if this seems basic, I am new to C#/dotnet and if the answer to this questions is somewhere obvious please point me in the right direction.
I have a DTO class with the following code
public class LessonDetailView : BaseResult
{
public long Id { get; set; }
public string Title { get; set; }
public List<LessonImagesListView> LessonImages { get; set; }
public List<LessonInstructionCardListView> InstructionCards { get; set; }
}
public class LessonImagesListView
{
public long Id { get; set; }
public string Title { get; set; }
public ImageDetailView Image { get; set; }
public LessonImagesListView()
{
Image = new ImageDetailView();
}
}
public class LessonInstructionCardListView
{
public long Id { get; set; }
public string Instructions { get; set; }
}
So I have 2 distinct types of object that I attach to the lesson and send to the frontend.
I will add that in the future I might have 6 different types of object.
These Images, or Instructions are also going to be displayed in a certain order on the front end so instead of sending them all separately I wanted to combine them all and send them in a new List LessonAssetsListView for example.
How can i create Lists in a DTO that combine 2 other lists ?
OR ... is this something I even need to do here ... and can i just do all this in my service.
Help appreciated.
You could simply define a type that composes both your existing and send a List of them
public class LessonAsset
{
public LessonImagesListView Image {get;set; }
public LessonInstructionCardListView Instruction {get;set;}
}
and then
public class LessonDetailView : BaseResult
{
public long Id { get; set; }
public string Title { get; set; }
public List<LessonAsset> LessonAssets { get; set; }
}

C# Casting between objects of different types

First of all I'm new to C#.
The error I get is:
Additional information: Unable to cast object of type 'UserGUI.MyItems' to type 'CommonBookLib.AbstractItem'.
They are 2 different classes:
public class MyItems
{
public string ItemName { get; set; }
public int CopyNumber { get; set; }
public int Guid { get; set; }
public DateTime? TimePrinted { get; set; }
public string Category { get; set; }
public string SubCategory { get; set; }
public bool? BestSeller { get; set; }
}
and
public class AbstractItem : IPropsDetails
{
public int CopyNumber { get; }
public string ItemName { get; }
public DateTime Time { get; }
public int Guid { get; }
public AbstractItem(int copyNumber, string itemName, DateTime time, int guid)
{
this.CopyNumber = copyNumber;
this.ItemName = itemName;
this.Time = time;
this.Guid = guid;
}
}
It happens when I do:
AbstractItem myItemsList = (AbstractItem)LibraryList.SelectedItem;
logicManager.Remove(myItemsList);
Well, as you can see, I have MyItems which are responsible for the DataBindings in my GUI and AbstractItem which responsible for implementing an addition operation to where my data is saved.
Since I did not managed my code well I got into this situation and I really do not want to change MyItems (delete and recode AbstractItem).
How can I Convert the two?
By the way, I know AbstractItem has only 4 properties while MyItems has more.
However, I have children with the exact same properties of AbstractItem.
Any help would be appreciated. Thanks in advance!
Remove fields from the MyItems class that are also present in AbstractItem, and then have MyItems derive from it instead.
You'll have to add a constructor to MyItems that passes the required values to the base constructor, or add an empty constructor to the base class.
public class MyItems : AbstractItem
{
public MyItems(int copyNumber, string itemName, DateTime time, int guid)
:base(copyNumber, itemName, time, guid)
{
}
public DateTime? TimePrinted { get; set; }
public string Category { get; set; }
public string SubCategory { get; set; }
public bool? BestSeller { get; set; }
}
You can make MyItems inherit AbstractItem, or make a method that handle the conversion between them.
You seem to need a mapper more than a cast. Look at AutoMapper or write your own routine as suggested by habibhassani. Also, Grant's answer is very good.
But your question was about casting so here I show how you can implement a casting operator so that your cast would work. This is not a technique you should reach for lightly. It puts a dependency on AbstractItem directly in MyItems and it is not the most discoverable pattern for maintainers of your code.
public class MyItems
{
public string ItemName { get; set; }
public int CopyNumber { get; set; }
public int Guid { get; set; }
public DateTime? TimePrinted { get; set; }
public string Category { get; set; }
public string SubCategory { get; set; }
public bool? BestSeller { get; set; }
public static explicit operator AbstractItem(MyItems myitems)
{
return new AbstractItem(myitems.CopyNumber, myitems.ItemName, myitems.TimePrinted, myitems.Guid);
}
}
A couple more observances. Naming your class AbstractItem is confusing, it implies that it is actually abstract but it is not.
Guid is a poor name for a property because it is already a Type. You have something named Guid that is an int - confusing.

How to: Nested Lists in SQLite-Net Extensions

How to: Do nested lists in sqlite-net-extensions
Answer Found: Keeping the question as an example of how to do it.
The problem i encountered was not sqlite-net-extensions related, but i'm keeping the question for context.
[Old Question]
I've got a problem with TwinCoders SQLite-net extensions.
I'm trying to insert a Series object into my database:
I'm using the Db.InsertWithChildren(SelectedSeriesObject,recursive:true) method.
The Series object is added accordingly with it's attributes.
All the Episodes are added as well, no problems there.
The problem is the BaseSeason.
It will only insert one Season object, which is (for some reason) the last Season Object of the list of Seasons in the Series
public class BaseSeries : BaseMedia
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Indexed]
public int ShowId { get; set; }
public string FirstAirDate { get; set; }
public string LastAirDate { get; set; }
public string Status { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<BaseSeason> Seasons { get; set; }
/// <summary>
/// TvShow = 0, Anime = 1
/// </summary>
public int SeriesType { get; set; }
}
public class BaseSeason
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(BaseSeries))]
public int SeasonId { get; set; }
public int SeasonNumber { get; set; }
public int NumberOfEpisodes { get; set; }
public string Plot { get; set; }
public string Poster { get; set; }
public string AirDate { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<BaseEpisode> Episodes { get; set; }
[ManyToOne]
public BaseSeries BaseSeries { get; set; }
}
public class BaseEpisode
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(BaseSeason))]
public int EpisodeId { get; set; }
public string Title { get; set; }
public string Plot { get; set; }
public string Poster { get; set; } //still path
public string AirDate { get; set; }
public int EpisodeNumber { get; set; }
public int SeasonNumber { get; set; }
public string SeriesName { get; set; }
[ManyToOne]
public BaseSeason BaseSeason { get; set; }
}
Is there anyone with experience regarding nested relationships in sqlite-net-extensions that knows how to make this work or see what i did wrong?
So regarding writing nested lists in sqlite-net-extensions:
My problem turned out the be related to how I handle the creation of these objects, this is by no means related to sqlite-net extensions. So my bad!
Which means that the questions example is valid and works. (I tested it of course)
Setting up the entities for the database:
The example shown in my question, with a Series class, Season class and Episode class, is the correct way of setting it up.
Inserting into the database:
If you're wondering how to insert an object similar to my Series object (with nested lists), use:
db.InsertWitchChildren(yourObject, recursion: true)
Here's an extended example:
public void AddSeries()
{
MediaDB.db.CreateTable<BaseSeries>();
MediaDB.db.CreateTable<BaseSeason>();
MediaDB.db.CreateTable<BaseEpisode>();
MediaDB.db.InsertWithChildren(SelectedSeries, recursion: true);
}
Side Note:
The example uses a static property on class with the connection string. Like so:
public class MediaDB
{
public static SQLiteConnection db => new SQLiteConnection(new SQLitePlatformGeneric(),"Media.db");
}
Refrain from doing this it is not really the best thing to do, since you should use using for the SQLiteConnection, making sure it's disposed once you're done with it.
more info on: sqlite-net-extentions
[UPDATE]: Further expansion of handling nested lists in sqlite-net extensions:
Deleting tables with children:
This is quite simple, but i spent a good hour and half figuring it out anyways.
Just use:
For lists/arrays: db.DeleteAll(yourCollection, recursion: true)
For single objects: db.Delete(yourObject, true);
As an exmaple: here's my implementation of a method that will delete a List
(BaseSeries is the class shown in the original question question):
public static void RemoveCollection<T>(List<T> collection)
{
using (db)
{
if (typeof(T) == typeof(BaseMovie))
{
db.DeleteAll(collection);
}
if (typeof(T) == typeof(BaseSeries))
{
db.DeleteAll(collection, recursion: true);
}
}
}
The BaseMovie class is a simple single entity, recursion is not needed since it holds no children.

Handling many times the same operation

I'm looking for a way to "divide" multiple operations that needs to be done so as to gain efficiency.
Let me put an example to explain my need.
Say that I have this object:
public class CardInfo
{
public int mCardID { get; set; }
public string mCardName { get; set; }
public int? mCardNumber { get; set; }
public string mCardColor { get; set; }
(...)
}
Each objects may be linked to a price list object:
public class PriceListInfo
{
public int mPriceListId { get; set; }
public int mPriceProviderID { get; set; }
public PriceProviderInfo mPriceListProvider { get; set; }
public int mCardID { get; set; }
public CardInfo mCard { get; set; }
public decimal? mPriceLow { get; set; }
public decimal? mPriceMid { get; set; }
public decimal? mPriceHigh { get; set; }
}
Now I have a process which task is to actually get a list of cards and build the price list of each cards, like this:
List<CardInfo> listCards = mCardManager.ListCardsForCardSet(_cardSetID);
foreach(var card in listCards)
{
List<PriceListInfo> listPrices = mPriceManager.ListPricesForCar(card);
}
Something quite simple, however if the list of cards contains more than 500 items, it will take a while. I am wondering (and since I don't know much about Asp.Net, it is why I am asking the question) if there's a way to divide the list by an [X] number and then launch many times the List<PriceListInfo> listPrices = mPriceManager.ListPricesForCar(card); line? Or is there a way to make these operation asynchronously? (please pardon my ignorance, thank you.) Can anybody explain how could I proceed, and if you could provide an example, I'd be more than happy.

How to change a class without re-coding?

I am creating a drivers license object in my project, that employees will all have one of their own linked to their unique clock number. I have a separate table in my database for the driving license but in the future more types of vehicles will need to be added, is there anyway to do this without re-coding?
the columns in my database are the same as the attributes for the class below
public class LicenseDTO
{
public int ClockNo { get; set; }
public bool CBalance { get; set; }
public bool MR16 { get; set; }
public bool OrderPicker { get; set; }
public bool Reach { get; set; }
public bool Pedestrian { get; set; }
public bool Lorry { get; set; }
public bool Sweeper { get; set; }
public bool Washer { get; set; }
}
EDIT
I have tried to create this the best I could but I feel like it's really long winded and can be done a more efficient way. Here's an updated version of my code.
public class LicenseDTO
{
public int ClockNo { get; set; }
public List<Common.VehicleTypeDTO> Vehicles { get; set; }
}
public class VehicleTypeDTO
{
public string VehicleType { get; set; }
public bool Allowed { get; set; }
}
private void btnClockCardIn_Click(object sender, EventArgs e)
{
Common.LicenseDTO License = new Common.LicenseDTO();
List<Common.VehicleTypeDTO> Vehicles = new List<Common.VehicleTypeDTO>();
Common.VehicleTypeDTO CBalance = new Common.VehicleTypeDTO();
Common.VehicleTypeDTO MR16 = new Common.VehicleTypeDTO();
License.Vehicles = Vehicles;
CBalance.VehicleType = "CBalance";
CBalance.Allowed = true;
MR16.VehicleType = "MR16";
MR16.Allowed = false;
License.Vehicles.Add(CBalance);
License.Vehicles.Add(MR16);
foreach (Common.VehicleTypeDTO Vehicle in License.Vehicles)
{
MessageBox.Show(Vehicle.VehicleType + " " + Vehicle.Allowed);
}
}
Why not to create a table with the types of vehicles? In the future you can access to your table and insert more types.
public class VehicleTypeDTO
{
public int Id{ get; set; }
public string Name{ get; set; }
}
public class LicenseDTO
{
public int Id { get; set; }
public List<VehicleTypeDTO> VehicleTypes { get; set; }
}
You should have made an entity LicenseDTO with the attributes ClockNo and CBalance alongside an array of the type Vehicle. which will be an interface. the interface Vehicle can define any common methods the vehicles have. and all future vehicles will have to implement the interface. that way you dont have to change any code. Your current code cannot be "changed" without editing. You could try to extend your LicenseDTO class with another entityclass which implements the above interface. but there isnt much more you can do without editing.
If you want maintainability use interfaces, repository patterns, abstract classes and dependency injection to start with.
Instead of having multiple bit columns in your database to indicate different types of vehicles, have a single VehicleType table. Then you can add as many different vehicle types as you like and use the VehicleTypeID to uniquely identify them. You can then add more and more vehicle types to the table without having to write more code.
VehicleType
VehicleTypeID int
VehicleTypeName varchar(50)
public class LicenseDTO
{
public int ClockNo { get; set; }
public int VehicleTypeID { get; set; }
}
If you want to have multiple types of vehicles against a single ClockNo then use a list of int:
public class LicenseDTO
{
public int ClockNo { get; set; }
public List<int> VehicleTypes { get; set; }
}
Alternately you could have a reference to the VehicleType objects instead of just the ID's.

Categories