Problems to fill information of 2 class - vb.net

I have 2 class in VB.net (Item Class and Tax Class). The Item class calls the Tax class in the form of an array.
See Class (Item-TaX)
Public Class Item
Public Property taxes As Tax()
Public Property code As String
End Class
Public Class Tax
Public Property taxCode As String
Public Property taxAmount As Integer
End Class
I need to add data to the 2 classes to build a JSON file
I'm doing it my way of thinking as follows:
Dim TaxProduct As New Tax
Dim Product As New Item
TaxProduct.taxCode = "01"
TaxProduct.taxAmount = 1000
Even there is going perfectly and the data is added in the class TaxProduct
Product.taxes = TaxProduct 'This line generates an error
Product.code = "10"
I thank you can help me
I hope you can explain to me how to enter the data in the class

A few changes that woudl be worth considering to your class structure below.
You seem to be storing a dollar amount as an integer. This is bad practice as money is frequently dollars and cents. Consider making that a decimal as below.
If you are dynamically adding tax objects to your item taxes array, you should use a List(of Tax)
I can't confirm here, however, it appears that you are storing a lot of int as string. (think code and tax code). Will those always be an integer value? Would you be better off using an enum of some sort instead. Food for thought.
Public Class Item
Public Property taxes As New List(of Tax)
Public Property code As String
End Class
Public Class Tax
Public Property taxCode As String
Public Property taxAmount As Decimal
End Class
After making the changes above, your code to new up and fill tax items into your product would look something like the below. Note the use of With is a VB exclusive and is imo just syntactical sugar. It is not an option in most other languages so use it with discretion.
Dim Product As New Item with {.code = "10" }
Dim TaxProduct As New Tax with {
.taxCode = "01",
.taxAmount = 1000
}
Product.taxes.add(TaxProduct)

Related

Custom Classes and Collection Classes

I have some custom classes and collection classes for those classes. I'm kind of new to actually implementing all of this, and I see a lot of different options but all with their own pros and cons, and I'm having trouble determining the best/right way to do what I need.
For example, I have a Product class with ID and Description properties. I have a ProductCollection class that I basically want to be a dictionary consisting of Product objects. This is a dictionary because there is a performance gain in accessing by key value, which is how I'll reference the objects. The key is Product.ID, and the value is Product.
I'd like to be able to do something like ProductCollection.Add(Product), and the collection will handle signing the dictionary key from the object's ID property. How do I best accomplish this? Implement Dictionary(Of Integer, Product) and override basically all methods to pass in the object and property separately? Or is there a better way?
Also, to give a little more background information to help clarify usage of these classes, there will be a "master" instance of ProductCollection containing all possible products. A ShipTo class will also have a ProductCollection containing specific products that are applicable for that particular ShipTo. My question was specific to the Product/ProductCollection classes, but also applied to the ShipTo classes.
This is how I would hold a collection of products. I have a Product class and a Products collection class.
First create the Product class which holds all the properties:
Imports System.Collections.ObjectModel
Public Class Product
Public Key As String
Public Sub New(ByVal id As Integer,
ByVal description As String)
_id = id
_description = description
End Sub
Private _id As Integer
Public ReadOnly Property ID() As Integer
Get
Return _id
End Get
End Property
Private _description As String
Public ReadOnly Property Description() As String
Get
Return _description
End Get
End Property
End Class
The create a Products collection class to hold the Product class:
Public Class Products
Inherits KeyedCollection(Of String, Product)
Protected Overrides Function GetKeyForItem(ByVal item As Product) As String
Return item.Key
End Function
End Class
You would then use these like this:
Dim myProducts As New Products
myProducts.Add(New Product(1,"Table"))

Entity Framework Conceptual Clarification

This question is purely conceptual! The code below works fine, but I can't figure out how . . .
The Scenario
I've begun reading up on Entity Framework concepts, and I'm currently using the information and examples located here to build my first MVC project. Here's the code example from that link:
Imports System.Collections.Generic
Imports System.Data.Entity
Namespace MyDataAccessDemo
Module Program
Sub Main()
Using context As New ProductContext()
Dim food As New Category With {.CategoryId = "FOOD"}
context.Categories.Add(food)
Dim cheese As New Product With {.Name = "Cheese"}
cheese.Category = context.Categories.Find("FOOD")
context.Products.Add(cheese)
context.SaveChanges()
End Using
End Sub
End Module
Public Class ProductContext : Inherits DbContext
Public Property Products As DbSet(Of Product)
Public Property Categories As DbSet(Of Category)
End Class
Public Class Product
Public Property ProductId As Integer
Public Property Name As String
Public Property Category As Category ' <-- Circular reference?
End Class
Public Class Category
Public Property CategoryId As String
Public Property Name As String
Public Property Products As ICollection(Of Product) ' <-- Circular reference?
End Class
End Namespace
The Problem
So, "Category" is a class and "Product" is a class. Category contains a collection of its products, each product of which contains its category, which contains a collection of its products, each product of which contains its category, which contains a collection of products . . . well, you get the idea.
The Question
Why does this work? Shouldn't this cause some kind of circular reference? I would think the category would contain the product IDs and vice versa, not the objects themselves.
Those are called Navigation Properties, you can find out more information here on the Entity framework website.

Circle reference (provider -> model -> provider)

i'm creating a new way to do the things in my project and i need some help in some point.
I have 3 projects in my solution:
Buusiness, Provider and Model.
The MODEL project, is the one that i have the classes just like the tables in database:
Ex:
public class Person
property Id as integert?
property Name as string
property CPF as string
end class
the PROVIDER project, is the one that makes the communication with database:
public class PersonProvider
public function ListPerson(filter as model.person) as list(of model.person)
public sub insertPerson(byRef person as model.peson)
public sub updatePerson(byRef person as model.peson)
public sub deletePerson(byRef person as model.peson)
end class
and finally, i have the BUSINESS project, that's the project that exposes the CRUD methods to the website (the website must not have access to the PROVIDER, because we have business logic in the BUSINESS)
public class PersonBusiness
public function ListPerson(filter as model.person) as list(of model.person)
return (new provider.PersonProvider).listPerson(filter)
end public
public sub InsertPerson(byRef person as model.person)
dim provider as new provider.PersonProvider()
provider.insertPerson(person)
end public
...
end class
But, i have come to a problem when i need some inner joins like this:
table CUSTOMER have an id_person, so in model.Customer i have a property IdPerson as integer?
but i want to have the properties Name and CPF that the model.Person have, read only property in the model.Customer, so i've made:
Property IdPerson As Integer?
Private _person As Pessoa
Private ReadOnly Property Person As model.Person
Get
If IsNothing(_person) Then
_person = New provider.PersonProvider.ListPerson(new model.Person with {.Id = Me.IdPerson})
End If
Return _person
End Get
End Property
ReadOnly Property Name As String
Get
Return Me.Person.Name
End Get
End Property
ReadOnly Property CPF As String
Get
Return Me.Pessoa.CPF
End Get
End Property
and here comes the question... i found that i can't have reference like:
Website reference Model and Business
Provider reference Model
Business reference Model and Provider
but to do the readonly Properties the Model needs reference to Provider, and that causes a circle reference..visual studio doesn't allow me to do this...
any idea how to do this?
Sorry that my post become so long, i just wanted to make things clear.
Instead of accessing Model by Website and Business, you could add another class that references Provider and Person, and this new class will referenced by Website and Business (instead of Website and Business referencing Person directly).

How to add a "sub property" to a class property

If, in code, I wanted to do something like the following, what would my class definition need to look like? (Keep in mind the fruit/language thing is just an example)
dim myfruit as new fruit()
myfruit.name = "apple"
myfruit.name.spanish = "manzana"
Here is the class I have, just not sure how to add the "sub property".
Public Class Fruit
Private _name As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
In general, for you to have a "sub property", you'd need to make your Property a class itself. This would mean the subproperty is actually a property on the class exposed by the top level property.
Effectively, you'd change the name property from a string to a "Translations" class or similar, ie:
Public Class Fruit
Public Property Name As New Translations
End Class
Public Class Translations
Public Property Primary As String
public Property Spanish As String
End Class
However, this will likely break the code you're displaying, as the second line would need to have a different syntax, ie:
myfruit.Name.Primary = "green"
myfruit.Name.Spanish = "verde"
However, if the goal here is to just handle translation of your user interface, there are other options. For details, see Introduction to International Applications Based on the .NET Framework on MSDN.
I initially thought Reed´s answer was what I was after. In my application, I wanted to use the "sub-property" to set a property on a Form Label. (I was trying to emit only the Label properties I wanted available to a Custom Control.)
I tried this:
Public Class Fruit
Private _name As New Translations
Public Property Name As Translations
Get
Return _name
End Get
Set(value As Translations)
_name = value
_PrimaryCaps = _name.Primary.ToUpper
End Set
End Property
'Private variable is automatically added for unexpanded property
Public Property PrimaryCaps As String
End Class
Public Class Translations
Public Property Primary As String
Public Property Spanish As String
End Class
Then
Dim myFruit As New Fruit
myFruit.Name.Primary = "Apple"
myFruit.Name.Spanish = "Manzana"
Dim primaryCaps As String = myFruit.PrimaryCaps
Weirdly - to me at least - this doesn't work; myFruit.PrimaryCaps returns nothing rather than the hoped-for "APPLE". It appears that the Set for Name is never executed. (Placing the _PrimaryCaps assignment above the Get Return does work, however.)
(I realize that a PrimaryCaps property could be added to the Translations class but, again, this doesn't help if you're wanting to set a foreign variable from within an instance of Fruit.)
I don't know if this is "by-design", whether I've simply misunderstood the intended functionality or what. One thing I did alight on after further research was that this structure isn't very common at all in .NET; for example setting a control's size is done as follows:
oControl.Size = New Drawing.Size(20, 15)
rather than simply setting, say, the Width property directly:
oControl.Size.Width = 20
(The latter won't compile: "Expression is a value and therefore cannot be the target of an assignment.")
If anyone has any more insight than I on this, I'd love to hear it. I know this could simply be done by using an instance of Fruit, for example, but that's not the point.

Only first DataAnnotation validation being applied

I'm currently working on a Winforms application written in VB.NET and implementing the Entity Framework (4.4). I want to add validation attributes to my entities so that I can validate them on the UI - just as I do in MVC.
I have created my 'Buddy Class' which contains an IsValid method and points to a 'MetaData' class that contains the data annotations.
Imports System.ComponentModel.DataAnnotations
Imports System.Runtime.Serialization
Imports System.ComponentModel
<MetadataTypeAttribute(GetType(ProductMetadata))>
Public Class Product
Private _validationResults As New List(Of ValidationResult)
Public ReadOnly Property ValidationResults() As List(Of ValidationResult)
Get
Return _validationResults
End Get
End Property
Public Function IsValid() As Boolean
TypeDescriptor.AddProviderTransparent(New AssociatedMetadataTypeTypeDescriptionProvider(GetType(Product), GetType(ProductMetadata)), GetType(Product))
Dim result As Boolean = True
Dim context = New ValidationContext(Me, Nothing, Nothing)
Dim validation = Validator.TryValidateObject(Me, context, _validationResults)
If Not validation Then
result = False
End If
Return result
End Function
End Class
Friend NotInheritable Class ProductMetadata
<Required(ErrorMessage:="Product Name is Required", AllowEmptyStrings:=False)>
<MaxLength(50, ErrorMessage:="Too Long")>
Public Property ProductName() As Global.System.String
<Required(ErrorMessage:="Description is Required")>
<MinLength(20, ErrorMessage:="Description must be at least 20 characters")>
<MaxLength(60, ErrorMessage:="Description must not exceed 60 characters")>
Public Property ShortDescription As Global.System.String
<Required(ErrorMessage:="Notes are Required")>
<MinLength(20, ErrorMessage:="Notes must be at least 20 characters")>
<MaxLength(1000, ErrorMessage:="Notes must not exceed 1000 characters")>
Public Property Notes As Global.System.String
End Class
The first line in the IsValid method registers the MetaData class (only way I could find that actually worked - otherwise no annotations were honored!). I then use the System.ComponentModel.Validator.TryValidateObject method to perform the validation.
When I call the IsValid method on an instance with an empty (null/nothing) ProductName the validation fails and the ValidationResults collection is populated with the correct error message. So far so good.....
However, if I call IsValid on an instance with a ProductName which is longer than 50 characters the validation passes despite the MaxLength attribute!
Also, if I call IsValid on an instance with a valid ProductName (not empty and not more than 50 characters) but without a ShortDescription the validation passes even though there is a Required annotation on that property.
What am I doing wrong here?
Try the other method signature for TryValidateObject() and explicitly set validateAllProperties to true:
Dim validation = Validator.TryValidateObject(
Me, context, _validationResults, true)