VB .Net BC30491: Expression does not produce a value - vb.net

This is my part of code:
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Proxies
Imports Services
Imports Settings
Imports Microsoft.Extensions.Configuration
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.Extensions.Logging
Public Class Program
Private Shared _serviceProvider As IServiceProvider
Private Shared _configuration As IConfigurationRoot
Private Shared _logger As ILogger
Private Shared Sub SetupConfiguration(ByVal environment As String)
_configuration = New ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile($"{environment}.settings.json", [optional]:=True, reloadOnChange:=True).AddEnvironmentVariables().Build()
End Sub
Private Shared Sub SetupServiceProvider()
Dim serviceCollection As IServiceCollection = New ServiceCollection()
serviceCollection.AddSingleton(_configuration)
Program.ConfigureServices(serviceCollection)
_serviceProvider = serviceCollection.BuildServiceProvider()
_logger = _serviceProvider.GetRequiredService(Of ILogger(Of Program))()
End Sub
Private Shared Sub ConfigureServices(ByVal services As IServiceCollection)
services.AddLogging(Function(opt) opt.AddConsole())
services.AddMemoryCache()
services.Configure(Of AuthorizationSettings)(Function(s) _configuration.GetSection(NameOf(AuthorizationSettings)).Bind(s))
services.Configure(Of ServicesSettings)(Function(s) _configuration.GetSection(NameOf(ServicesSettings)).Bind(s))
services.AddSingleton(Of ITokenService, TokenCacheService)()
services.AddSingleton(Of IIdentityServiceProxy, IdentityServiceProxy)()
services.AddSingleton(Of IIdentityImportService, CsvIdentityImportService)()
End Sub
End Class
I got the error in these two lines and do not let me compile:
services.Configure(Of AuthorizationSettings)(Function(s) _configuration.GetSection(NameOf(AuthorizationSettings)).Bind(s))
services.Configure(Of ServicesSettings)(Function(s) _configuration.GetSection(NameOf(ServicesSettings)).Bind(s))
The error I got is this:
BC30491: Expression does not produce a value
Any ideas on how to fix it?. I use this code to connect to an API using OAuth 2.0 and JSON Web Token (JWT) AuthorizationSettings and ServiceSettings are two classes which return configuration. This code was converted from a C# code

Related

How to upload file with Asp.net Web Api project?

i have a web API project to be consumed from mobile applications and i was trying to make a file upload controller. there are few resources in C# and i don't find anything useful for VB.NET.
i tried this code below converting from c# to VB.NET, but says "Move is not a member of MultiPartFileData".
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.Web
Imports System.Web.Http
Namespace HelloWorld.Controller
Public Class FileUploadingController
Inherits ApiController
<HttpPost>
<Route("api/FileUploading/UploadFile")>
Public Async Function UploadFile() As Task(Of String)
Dim ctx = HttpContext.Current
Dim root = ctx.Server.MapPath("~/App_Data")
Dim provider = New MultipartFormDataStreamProvider(root)
Try
Await Request.Content.ReadAsMultipartAsync(provider)
For Each file In provider.FileData
Dim name = file.Headers.ContentDisposition.FileName
name = name.Trim(""""c)
Dim localFileName = file.LocalFileName
Dim filePath = Path.Combine(root, name)
File.Move(localFileName, filePath)
Next
Catch e As Exception
Return $"Error: {e.Message}"
End Try
Return "File uploaded!"
End Function
End Class
End Namespace
That error message means the compiler think that you are trying to call a method from the MultiPartFileData class. The variable of type MultiPartFileData is the one called file (notice the lowercase) initialized in the For Each loop.
Instead you want to call the Move method from the System.IO.File class (notice the uppercase).
VB.NET services (always running in background looking to catch errors while you type) is case insensitive so, for it, the two names are the same and here arises the error emitted when you code that line.
The best solution is to avoid names like file for your variables when you plan to use the class System.IO.File. Otherwise you could simply add the full qualified method's name in this way
System.IO.File.Move(localFileName, filePath)

DbContext type is not defined

Working with EF 6.1. I've created two table class files:
Public Class Student
Public Property StudentID() As Integer
Public Property StudentName() As String
Public Property DateOfBirth() As DateTime
End Class
Public Class Standard
Public Property StandardID() As Integer
Public Property StandardName() As String
End Class
Also created one DbContext file (SchoolContext.vb):
Imports System.Data.Entity
Namespace TestDataAccess
Public Class SchoolContext
Inherits DbContext
Public Sub New()
MyBase.New(ConfigurationManager.ConnectionStrings("dbConnString").ConnectionString)
End Sub
Private _Students As DbSet(Of Student)
Private _Standards As DbSet(Of Standard)
End Class
End Namespace
In my test page, I'm making reference to the DbContext file by using the following:
Dim context As SchoolContext = New SchoolContext
but it keeps giving the error "Type 'SchoolContext' is not defined." Even tried importing the namespace 'TestDataAccess' but still received the error. I did install EF into my project via NuGet, and it show in my packages.config file, so I know that's not the issue.
<package id="EntityFramework" version="6.1.2" targetFramework="net451" />
Any ideas what could be wrong?
I am nog very familiare with vb, but what is the scope of your DbContext.
Shouldn't _standards and _studente be public instead of private?
You need the EntityFramework.dll reference (and not System.Data.Entity).

How to Inject a parameter to constructor using unity

Hi I am using unity in WebAPI 1.0 and registered it under Global.asax.vb file as below
Dim container As IUnityContainer = New UnityContainer()
container.RegisterType(Of Car)(New InjectionConstructor(GetType(Integer)))
Now how do i pass integer value which is passed by the client application into car type using
Public Sub New(ByVal intUserId As Int32)
objCar = DependencyResolver.Current.GetService(Of car)()
End Sub
Can't find anything to use (ParameterOverride("intUserId", intUserId) within DependencyResolver
It is very similar as registering unity container with ASP.NET MVC. Though web api has a different execution pipe line. Follow these steps.
NB: I have converted this code from C# to VB using a converter. So I hope it is syntactically correct. Though it is accurate in c#.
1) Implement IDependencyResolver (Make sure you are resolving correct namespace here. IDependencyResolver should come from System.Web.Http.Dependencies. Make note of Imported namespaces.
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports Microsoft.Practices.Unity
Imports System.Web.Http.Dependencies
Namespace YourNamespace.Framework
Public Class UnityApiDependencyResolver
Implements IDependencyResolver
Private _container As IUnityContainer = Nothing
Public Sub New(container As IUnityContainer)
Me._container = container
End Sub
Public Function GetService(serviceType As Type) As Object
Try
Return _container.Resolve(serviceType)
Catch generatedExceptionName As Exception
Return Nothing
End Try
End Function
Public Function GetServices(serviceType As Type) As IEnumerable(Of Object)
Try
Return _container.ResolveAll(serviceType)
Catch generatedExceptionName As Exception
Return Nothing
End Try
End Function
Public Function BeginScope() As IDependencyScope
Return Me
End Function
Public Sub Dispose()
'
End Sub
End Class
End Namespace
'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: #telerik
'Facebook: facebook.com/telerik
'=======================================================
2) Configure your container either thgough config or through code.
3) Register your container in Global.asax.vb file
Dim container = New UnityContainer()
Dim section As UnityConfigurationSection = TryCast(ConfigurationManager.GetSection("unity"), UnityConfigurationSection)
section.Configure(container, "UnitySection")
'api dependency resolver
GlobalConfiguration.Configuration.DependencyResolver = New UnityApiDependencyResolver(container)
'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: #telerik
'Facebook: facebook.com/telerik
'=======================================================
Thats it.
Now you can declare your dependency in any of your API controller and it will be injected by Unity
Public Sub New(repositoryFactory As IRepositoryFactory, serviceFactory As IServiceFactory)
Me.repositoryFactory = repositoryFactory
Me.serviceFactory = serviceFactory
End Sub
'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: #telerik
'Facebook: facebook.com/telerik
'=======================================================
Your type registration is wrong as well. you have to specify either an interface or an abstract class as dependency and its concrete implementation as its mapping.
e.g
container.RegisterType(Of IContext, Context)()
I don't understand what are trying to achieve by mapping an integer value to car. Do you want car object to be loaded based on integer value in your parameter?

Fluent Nhibernate configuration method wont compile - expression does not produce value

Code below will not compile. Line with New SchemaExport(cfg).Create(True, True) - expression does not produce a value.
I'm new to Nhibernate. Am I missing something? This is a conversion of a code from C# which complies fine.
Imports System.Configuration
Imports FluentNHibernate.Cfg
Imports FluentNHibernate.Cfg.Db
Imports NHibernate
Imports NHibernate.Tool.hbm2ddl
Imports Ninject.Activation
Imports Ninject.Modules
Imports OSIM.Core
Imports Configuration = NHibernate.Cfg.Configuration
Public Class IntegrationTestsModule
Inherits NinjectModule
Public Overrides Sub Load()
Bind(Of IItemTypeRepository).To(Of ItemTypeRepository)()
Bind(Of ISessionFactory).ToProvider(New ntegrationTestSessionFactoryProvider)
End Sub
End Class
Class IntegrationTestSessionFactoryProvider
Inherits Provider(Of ISessionFactory)
Protected Overrides Function CreateInstance(context As IContext) As ISessionFactory
Dim sessionFactory = Fluently.Configure().
Database(MsSqlConfiguration.MsSql2008.ConnectionString(Function(c) c.Is(ConfigurationManager.AppSettings("localDb"))).ShowSql()). _
Mappings(Function(m) m.FluentMappings.AddFromAssemblyOf(Of ItemTypeMap)().ExportTo("C:\Temp")). _
ExposeConfiguration(Function(cfg) New SchemaExport(cfg).Create(True, True)).BuildSessionFactory()
Return sessionFactory
End Function
End Class
The ExposeConfiguration method is defined as follows (vb):
Public Function ExposeConfiguration(config As Action(Of Configuration)) As FluentConfiguration
It takes an instance of Action(Of Configuration). You must change Function to Sub like this:
ExposeConfiguration(Sub(cfg) New SchemaExport(cfg).Create(True, True)).BuildSessionFactory()
Came here with same question, but inline code above not working -- possibly because of NHIbernate updates.
Error was: "Expression does not produce a value".
I reckon NHibernate modified the SchemaExport tool in the meantime?
Anyways, here's a working code with NHibernate 5.2.0.0
For those new to lambda functions, please note the newlines
Dim fluentConfig = Fluently.Configure() _
.Database(SQLiteConfiguration.Standard.UsingFile("hibernatetest.db")) _
.Mappings(Function(m) m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) _
.ExposeConfiguration(Sub(cfg)
Dim se = New SchemaExport(cfg)
se.Execute(True, True, False)
End Sub) _
.BuildSessionFactory()
Hope it helps.

WCF/Entity Framework - How To Get a Nice DataContract?

Is there a clean way of using the auto-generated EF classes with WCF instead of having to hand-make classes for WCF DataContracts?
The classes are located in the LAIT.Entities.dll
ProductService.vb
Public Class ProductService
Implements IProductService
Public Function GetWorkOrder(ByVal WorkOrderID As Integer) As
WorkOrder Implements IProductService.GetWorkOrder
Using dc As New LAIT.Model.LAITEntities
Try
Dim _Order = (From o In dc.WorkOrder
Where o.WorkOrderID = WorkOrderID
Select o).SingleOrDefault
Return _Order
Catch ex As Exception
Return Nothing
End Try
End Using
End Function
End Class
IProductService.vb
Public Interface IProductService
<OperationContract()>
Function GetWorkOrder(ByVal WorkOrderID As Integer) As
LAIT.Entities.WorkOrder
End Interface
Yes. For that you need to edit the T4 file that VS uses to auto generate your entities. All you need to do is to make sure that all your classes are decorated with <DataContract> attribute and your properties are marked with <DataMember> attribute. I assume that you are using POCO entities because both Entity Objects and STEs are already marked as DataContract and you don't need to do anything in order to use them in your WCF services.
Having said that, I strongly discourage you from using Entity Objects across the wire with WCF. You should use either STEs or POCOs in this scenaio.
The POCO proxy type cannot be directly serialized or deserialized by the Windows Communication Foundation (WCF), because the DataContractSerializer serialization engine can only serialize and deserialize known types. The proxy type is not a known type.
If your POCO entities don't have any "Navigation Properties" you can have serialized objects of your entities through WCF Services by adding <DataContract> and <DataMember> properties in your class.
But for Entities with "Navigation Properties" In addition of adding <DataContract> and <DataMember> properties in your class you need to have some changes in your WCF Service as follows. Add the following calss in your WCF Service project.
1.
Imports System.Data.Objects
Imports System.ServiceModel.Description
Imports System.ServiceModel.Channels
Public Class ApplyDataContractResolverAttribute
Inherits Attribute
Implements IOperationBehavior
Public Sub New()
End Sub
Public Sub AddBindingParameters(ByVal operationDescription As OperationDescription, ByVal parameters As BindingParameterCollection) Implements IOperationBehavior.AddBindingParameters
End Sub
Public Sub ApplyClientBehavior(ByVal operationDescription As OperationDescription, ByVal proxy As System.ServiceModel.Dispatcher.ClientOperation) Implements IOperationBehavior.ApplyClientBehavior
Dim dataContractSerializerOperationBehavior As DataContractSerializerOperationBehavior = operationDescription.Behaviors.Find(Of DataContractSerializerOperationBehavior)()
dataContractSerializerOperationBehavior.DataContractResolver = New ProxyDataContractResolver()
End Sub
Public Sub ApplyDispatchBehavior(ByVal operationDescription As OperationDescription, ByVal dispatch As System.ServiceModel.Dispatcher.DispatchOperation) Implements IOperationBehavior.ApplyDispatchBehavior
Dim dataContractSerializerOperationBehavior As DataContractSerializerOperationBehavior = operationDescription.Behaviors.Find(Of DataContractSerializerOperationBehavior)()
dataContractSerializerOperationBehavior.DataContractResolver = New ProxyDataContractResolver()
End Sub
Public Sub Validate(ByVal operationDescription As OperationDescription) Implements IOperationBehavior.Validate
' Do validation.
End Sub
End Class
2.Open the service interface file. By default, it is called IService1.
3.Replace the code that defines the service interface file with the following code:
C#
[ServiceContract]
public interface IService1
{
[OperationContract]
[ApplyDataContractResolver]
void UpdateOrder(Order updated);
[OperationContract]
[ApplyDataContractResolver]
Order GetOrder(int OrderID);
}
VB
<ServiceContract> _
Public Interface IService1
<OperationContract> _
<ApplyDataContractResolver> _
Sub UpdateOrder(updated As Order)
<OperationContract> _
<ApplyDataContractResolver> _
Function GetOrder(OrderID As Integer) As Order
End Interface
And you are ready to go.