Automapper in VB.Net - vb.net

I am having a devil of a time attempting to translate the following piece of code from c# to VB.Net. I have little experience in VB.Net and all my searches have proven fruitless to date.
IMapper DataReaderMapper = new MapperConfiguration(cfg => {
cfg.AddDataReaderMapping();
cfg.CreateMap<IDataReader, MyDTO1>();
cfg.CreateMap<IDataReader, MyDTO2>();
cfg.CreateMap<IDataReader, MyDTO3>();
}).CreateMapper();
The code is using the Automapper and Automapper.Data nuget packages to map datatables to DTOs. I know the code works fine in c#.
My best guess was the following:
Dim DataReaderMapper As IMapper = New MapperConfiguration(Function(cfg) {cfg.AddDataReaderMapping(), cfg.CreateMap(Of IDataReader, MyDTO1)()}).CreateMapper()
The above results in an "Overload resolution failure" warning as I am obviously not passing in the arguments/parameters in the correct fashion/order. I can usually muddle by with most translations that I have to deal with but this one is stumping me. Any help would be appreciated.

According to https://converter.telerik.com/
Dim DataReaderMapper As IMapper = New MapperConfiguration(Function(cfg)
cfg.AddDataReaderMapping()
cfg.CreateMap(Of IDataReader, MyDTO1)()
cfg.CreateMap(Of IDataReader, MyDTO2)()
cfg.CreateMap(Of IDataReader, MyDTO3)()
End Function).CreateMapper()

I was able to resolve by combining the responses of Nick Abbot's Telerik conversion and Craig's suggestion to swap out "Function" for "Sub" to get the following:
Dim DataReaderMapper As IMapper = New MapperConfiguration(Sub(cfg)
cfg.AddDataReaderMapping()
cfg.CreateMap(Of IDataReader, MyDTO1)()
cfg.CreateMap(Of IDataReader, MyDTO2)()
cfg.CreateMap(Of IDataReader, MyDTO3)()
End Sub).CreateMapper()

Related

How do I convert a ObservableCollection(Of T) to List(Of T) an in VB.NET?

I am working on VB.net windows8 mobile application in this app i am facing conversion issue.
I am adding the new service reference in our application and previous old service reference is changed.
old code:
Dim JobAllDetailsList As New System.Collections.Generic.List(Of JobAllDetails)
JobAllDetailsList = e.Result
JobAllDetails---->class interface.
Newcode:
new service model is System.Collections.ObjectModel.ObservableCollection.
How to convert System.Collections.ObjectModel.ObservableCollection to System.Collections.Generic.List? please give me suggestion or help.
Simply call .ToList() from your ObservableCollection(Of T), for example :
JobAllDetailsList = e.Result.ToList()

Call instance method inline after New statement

How can i convert this code to VB.net
public void SetBooks(IEnumerable<Book> books)
{
if (books == null)
throw new ArgumentNullException("books");
new System.Xml.Linq.XDocument(books).Save(_filename);
}
in http://converter.telerik.com/ it says:
Public Sub SetBooks(books As IEnumerable(Of Book))
If books Is Nothing Then
Throw New ArgumentNullException("books")
End If
New System.Xml.Linq.XDocument(books).Save(_filename)
End Sub
But visual studio says "Syntax error." because of "New"
What is the keyword for this situation, i searched on Google but no result.
Actually, you can do it in one line with the Call keyword
Call (New System.Xml.Linq.XDocument(books)).Save(_filename)
You cannot initialize an object and use it in one statement in VB.NET (as opposed to C#). You need two:
Dim doc = New System.Xml.Linq.XDocument(books)
doc.Save(_filename)
In C# the constructor returns the instance of the created object, in VB.NET not.

NullReferenceException on dll

Here is my code I get the error on:
Imports ADFactory
Public Class Salary
Inherits Salary_Datalayer
Protected _AD As New ADFactory.ADFactory
Protected Sub Page_Load(...)Handles Me.Load
_user = "username"
sDealer = _AD.GetUserCompany(_user)
It states that Protected _AD As New ADFactory.ADFactory is the line throwing the exception. I've looked online and read and changed it several times, declared 'New', am I missing something simple?
PatFromCanada was correct, my ADFactory was the problem. I didn't properly initialize a connection string within the reference, thus always throwing a nullexception, which apparently, I run into quite often in my questions. Thanks PatFromCanada!

LINQ to SQL Generic Class for Insert and Delete operation

I have been writing same code for insert, update, delete with LINQ over and over again. I want to have some sort of generic function for Insert, Update, Delete operation. I read a post here like the following :
public static void Insert<T>(T entity) where T : class
{
using (OrcasDB database = new OrcasDB())
{
database.GetTable<T>().Add(entity);
database.SubmitChanges();
}
}
public static void Delete<T>(Expression<Func<T, bool>> predicate)
where T : class
{
using (OrcasDB database = new OrcasDB())
{
T instance = (T) database.GetTable<T>().Where<T>(predicate).Single();
database.GetTable<T>().Remove(instance);
database.SubmitChanges();
}
}
How to Use
// insert
Employee will = new Employee
{
Username = "will.asrari",
EmailAddress = "me#willasrari.com",
CanCode = true
};
LinqHelper.Insert<Employee>(will);
// delete
LinqHelper.Delete(emp => emp.EmployeeId.Equals(3));
Yes, I would like to write something like in VB.NET. Is the code above good to follow? Can anyone show me any LINQ to SQL generic class for Insert, Delete, Update written in VB.NET?
Thank you.
FYI, I managed to write a simple class to do the generic CUD operantion for LINQ to SQL.
'Class GenericCUD.vb
Imports System.Linq.Expressions
Imports System.Data.Linq
Public Class GenericCUD
Public Shared Sub Insert(Of T As Class)(ByVal theEntity As T)
Using db As New DemoDataContext()
db.GetTable(Of T)().InsertOnSubmit(theEntity)
db.SubmitChanges()
End Using
End Sub
Public Shared Sub Update(Of T As Class)(ByVal originalEntity As T, ByVal newEntity As T)
Using db As New DemoDataContext()
db.GetTable(Of T)().Attach(newEntity, originalEntity)
db.Refresh(RefreshMode.KeepCurrentValues, newEntity)
db.SubmitChanges()
End Using
End Sub
Public Shared Sub Delete(Of T As Class)(ByVal theEntity As T)
Using db As New DemoDataContext()
db.GetTable(Of T)().Attach(theEntity)
db.GetTable(Of T).DeleteOnSubmit(theEntity)
db.Refresh(RefreshMode.KeepCurrentValues, theEntity)
db.SubmitChanges()
End Using
End Sub
End Class
How to use the class :
'Using Insert
Dim ta As New TestAuthor
ta.FirstName = TextBox1.Text
ta.LastName = TextBox2.Text
GenericCUD.Insert(ta)
'Using Update
Dim original As New TestAuthor
original.Id = 3
Dim newEntity As New TestAuthor
newEntity.Id = original.Id
newEntity.FirstName = TextBox1.Text
newEntity.LastName = TextBox2.Text
GenericCUD.Update(original, newEntity)
'Using Delete
Dim ta As New TestAuthor
ta.Id = 7
GenericCUD.Delete(ta)
I read a lot of post on many blogs. Here are a few that really helped me to make the GenericCUD work:
LINQ, Lambda, and Generics: Insert and Delete
LINQ to SQL CRUD
How to Make LINQ to SQL Check for Changes After Attach
So, What do you think about the GernericCUD class above? Please give me some comment because I want to improve it. Thank you.
We've taken a similar approach in our 3-tier application framework. We currently have roughly 80 entities and have used generics to create a very light-weight set of generic CRUD methods that satifsy those 80 entities and any number of entities.
The only suggestion I might make is to re-think your approach to creating a new database context for each insert, update and delete operation. The problem is that if you need to wrap multiple inserts, updates and/or deletes in a single transaction, you're going to need to use a TransactionScope object because each insert/update/delete is using it's own context object. Using TransactionScope is ok, but since you've got multiple connections, the transaction is going to get elevated to an MTC transaction, which is a hassle.
Can't help you with the VB code. IMO, learn and stick with C#.
Randy

How do I unit test object serialization/deserialization in VB.NET 1.1?

I am looking for example code that provides a unit test to serialize and deserialize an object from a memory stream. I have found examples using C# 2.0, however my current project uses VB.NET 1.1 (don't ask me why...), so the solution can not use generics. I am also using the NUnit framework for the unit tests.
Thanks!
This is the pattern I've settled upon:
<Test()> _
Public Sub SerializationTest()
Dim obj As New MySerializableObject()
'Perform additional construction as necessary
Dim obj2 As MySerializableObject
Dim formatter As New BinaryFormatter
Dim memoryStream As New MemoryStream()
'Run through serialization process
formatter.Serialize(memoryStream, obj)
memoryStream.Seek(0, SeekOrigin.Begin)
obj2 = DirectCast(formatter.Deserialize(memoryStream), MySerializableObject)
'Test for equality using Assert methods
Assert.AreEqual(obj.Property1, obj.Property1)
'etc...
End Sub
NUnit has built in support for this which makes it quite a bit easier:
Dim obj As New MySerializableObject()
Assert.That(obj, Is.BinarySerializable)
Or for xml:
Dim obj As New MySerializableObject()
Assert.That(obj, Is.XmlSerializable)
If all you want to do is to ensure that they are serializable then all you should have to do it to do a serialization of an object and make sure no XmlSerializationException was thrown
[Test]
public void ClassIsXmlSerializable()
{
bool exceptionWasThrown = false;
try
{
// .. serialize object
}
catch(XmlSerializationException ex)
{
exceptionWasThrown = true;
}
Asset.IsFalse(exceptionWasThrown, "An XmlSerializationException was thrown. The type xx is not xml serializable!");
}
Hmm...so you are trying to write a unit test for serialization? Or for streams? This is hopefully done by MS already...but if you don't trust or implement something on your own...you could just fill object with some data, save it, restore it, and check if the fields values are in place?