VB.NET: Add DBContext with Dependecy Injection - oracle

I'm trying to consume in VB.NET some classes using Dependency Injection.
In the Global.asax.vb, I have:
.....
Dim hostBuilder As HostBuilder = New HostBuilder() _
.ConfigureServices(Function(hostContext, services)
services.AddLogging(Function(lb)
lb.ClearProviders()
lb.AddLog4Net("log4net.config")
Return lb
End Function)
services.AddHttpClient(Of IService1, Service1)
services.AddDbContext(Of MyDbContext)(Function(options)
' Not Working -> Return options.UseOracle(connString)
End Function)
services.AddScoped(Of IMyRepository, MyRepository)
services.AddMediatR(GetType(SomeClass).GetTypeInfo().Assembly)
services.AddScoped(Of IOtherClass, OtherClass)
Return services
End Function) _
.ConfigureAppConfiguration(Function(hostContext, confBuilder)
confBuilder.AddJsonFile("appsettings.json", False)
Return confBuilder
End Function)
Dim host = hostBuilder.Build()
ServiceProvider = host.Services
I'm having problem in adding the DBContext.
I want to use an Oracle connection, but when i try options.UseOracle(connString), there isn't the UseOracle extension method, but I have added the Oracle.EntityFrameworkCore nuget package
By using C# I simply use:
services.AddDbContext<MyDbContext>
(options => options.UseOracle(connString));
What is wrong?
Thanks in advance.

Side note (so just community wiki), but recent VB.Net has implicit line continuation.
So if you have this:
functionCall() _
.ContinueExprssionOnNextLine
You can remove the _ if you move the . to the end of the first line, so there is a binary operator at the end of the line:
functionCall().
ContinueExprssionOnNextLine

I've resolved restarting Visual Studio (2022).
After the restart the extension method UseOracle was avaiable.

Related

How do I add global properties to generated Visual Studio projects and solutions via premake5?

I would like to add two conditional properties to my project configuration to target a non-default vcpkg triplet: https://github.com/microsoft/vcpkg/blob/master/docs/users/integration.md#with-msbuild
My project files are generated by premake. How would I go about this?
you could try to override the global function from the visual studio generator some thing like this ... not tested ...
local vs2010 = premake.vstudio.vs2010
function vcPkgOverride(prj)
-- go trough the configs and platforms and figure out which conditions to put
for _, cfg in pairs(prj.cfgs) do
local condition = vs2010.condition(cfg)
if cfg.platform == "Win32" then
vs2010.vc2010.element("VcpkgTriplet ", condition, "x86-windows-static")
else if cfg.platform == "x64" then
vs2010.vc2010.element("VcpkgTriplet ", condition, "x64-windows-static")
end
end
end
premake.override(vc2010.elements, "globals", function (oldfn, prj)
local elements = oldfn(prj)
elements = table.join(elements, {
vcPkgOverride
})
end
return elements
end)
UPDATE
The code above doesn't seem to work for premake5.0.0-alpha14 so I tweaked it based on the docs and here you have a less general, but working version:
require('vstudio')
local vs = premake.vstudio.vc2010
local function premakeVersionComment(prj)
premake.w('<!-- Generated by Premake ' .. _PREMAKE_VERSION .. ' -->')
end
local function vcpkg(prj)
premake.w('<VcpkgTriplet>x64-windows-static</VcpkgTriplet>')
premake.w('<VcpkgEnabled>true</VcpkgEnabled>')
end
premake.override(premake.vstudio.vc2010.elements, "project", function(base, prj)
local calls = base(prj)
table.insertafter(calls, vs.xmlDeclaration, premakeVersionComment)
return calls
end)
premake.override(premake.vstudio.vc2010.elements, "globals", function(base, prj)
local calls = base(prj)
table.insertafter(calls, vs.globals, vcpkg)
return calls
end)
Add this at the start of your main premake5.lua script, or find a way to include it from somewhere else (I don't know much about lua or premake I just needed to fix this and wanted to show it to the community)
Have you tried using CMake instead? It's a far more sophisticated build system that should handle this trivially.

Google Spreadsheet to SSIS VB Code issue

Requirement:
Convert Google Spreadsheet data to SQL Server through SSIS.
Method:
With help from this website, I'm doing coding in Visual Studio 2015 Community edition. I have prepared Variables, Control Flow, Data Flow and added Script component and the required Google References.
Code pasted in VS as Visual Basic 2015:
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.GData.Spreadsheets
<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute> 'Line 15 Error here
<CLSCompliant(False)> 'Line 17 Error here
Public Class ScriptMain
Inherits UserComponent
Dim objListFeed As ListFeed
Public Overrides Sub PreExecute()
MyBase.PreExecute()
Dim objService As SpreadsheetsService
Dim objWorkSheetQuery As WorksheetQuery
Dim objWorkSheetFeed As WorksheetFeed
Dim objWorkSheet As WorksheetEntry
Dim objListFeedLink As AtomLink
Dim objListQuery As ListQuery
Dim bt(0) As Byte
'Create a connection to the google account
objService = New SpreadsheetsService("exampleCo-exampleApp-1")
Me.Log(Variables.strPassword, 0, bt)
Me.Log(Variables.strUserName, 0, bt)
objService.setUserCredentials(Variables.strUserName, Variables.strPassword)
Me.Log("Service: " + Variables.strUserName, 0, bt)
'Connect to a specific spreadsheet
objWorkSheetQuery = New WorksheetQuery(Variables.strKey, "private", "full")
objWorkSheetFeed = objService.Query(objWorkSheetQuery)
objWorkSheet = objWorkSheetFeed.Entries(0)
Me.Log("Spreadsheet: " + objWorkSheet.Title.Text.ToString, 0, bt)
'Get a list feed of all the rows in the spreadsheet
objListFeedLink = objWorkSheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, Nothing)
objListQuery = New ListQuery(objListFeedLink.HRef.ToString())
objListFeed = objService.Query(objListQuery)
Me.Log("ListFeed: " + objListFeed.Feed.ToString, 0, bt)
End Sub
Public Overrides Sub PostExecute()
MyBase.PostExecute()
End Sub
Public Overrides Sub CreateNewOutputRows()
Dim objRow As ListEntry
For Each objRow In objListFeed.Entries
With Output0Buffer
.AddRow()
.Product = objRow.Elements.Item(0).Value
.Qty = objRow.Elements.Item(1).Value
End With
Next
Output0Buffer.EndOfRowset()
End Sub
End Class
Problem:
Upon pressing Build, I get the following error on Line 15 and 17.
BC32035 VB.NET Attribute specifier is not a complete statement. Use a
line continuation to apply the attribute to the following statement.
Here it says to add a space and underscore following the attribute, however, when I add them they are just automatically removed.
I just created a new script component in a new SSIS package dataflow, and here are the lines between the import block and the Class declaration:
' This is the class to which to add your code. Do not change the name, attributes, or parent
' of this class.
<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute> _
<CLSCompliant(False)> _
Public Class ScriptMain
Inherits UserComponent
I have never heard of the situation you describe where the underscores just "disappear", but maybe if you paste these lines over your lines it will work.
If not, you may need to copy your code to the clipboard, and then destroy the script component and create a new one, and paste your code into it.

Getting Error as 'User defined type not defined' in the code

Greetings for the day,
Hi, I am a beginner using vb 6.0. I am using the following code and getting 'user defined type not defined'.the code is below.the line where i get error is highlighted.Kindly help.should i add some references or components?if so,what it would be. your timely and kindly help will be much more helpful for me
Public Sub LoadDocument()
Dim xDoc As MSXML2.DOMDocument
Set xDoc = New MSXML2.DOMDocument
xDoc.async = False
xDoc.validateOnParse = False
If xDoc.Load("C:\Users\284582\Desktop\XML1.xml") Then
DisplayNode xDoc.ChildNodes, 0
End If
End Sub
' Error on this line'
Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
ByVal Indent As Integer)
Dim xNode As MSXML.IXMLDOMNode
Indent = Indent + 2
For Each xNode In Nodes
If xNode.NodeType = NODE_TEXT Then
Debug.Print Space$(Indent) & xNode.ParentNode.nodeName & _
":" & xNode.NodeValue
End If
If xNode.HasChildNodes Then
DisplayNode xNode.ChildNodes, Indent
End If
Next xNode
End sub
It's MSXML2.IXMLDOMNodeList, not MSXML.IXMLDOMNodeList.
The library may be missing from your references. Try this.
Manually adding MSXML2
1. Open MS Access.
2. Database Tools ribbon
3. Visual Basic ribbon item (icon)
4. Double-click on any module to open it.
5. Tools menu
6. References…
7. Find Microsoft XML, v6.0. is in the list
a. If in list but not checked, check it and click [OK].
b. If not in the list:
i. click [Browse…] and add "c:\windows\system32\msxml6.dll"
8. [OK] your way back to the Visual Basic window.
9. Close the Visual Basic Window. You should be good to go.
Programmatically adding MSXML2
Add the following sub and function. Run the sub. Edit the sub to include a path if necessary.
Check for broken references in the library
Adapted from Add references programatically
Sub CheckXmlLibrary()
' This refers to your VBA project.
Dim chkRef As Reference, RetVal As Integer ' A reference.
Dim foundWord As Boolean, foundExcel As Boolean, foundXml As Boolean
foundWord = False
foundExcel = False
foundXml = False
' Check through the selected references in the References dialog box.
For Each chkRef In References
' If the reference is broken, send the name to the Immediate Window.
If chkRef.IsBroken Then
Debug.Print chkRef.Name
End If
'copy and repeat the next 2 if statements as needed for additional libraries.
If InStr(UCase(chkRef.FullPath), UCase("msxml6.dll")) <> 0 Then
foundXml = True
End If
Next
If (foundXml = False) Then
'References.AddFromFile ("C:\Windows\System32\msxml6.dll") <-- For other than XML, modify this line and comment out line below.
RetVal = AddMsXmlLibrary
If RetVal = 0 Then MsgBox "Failed to load XML Library (msxml6.dll). XML upload/download will not work."
End If
End Sub
Add XML reference to the library
Developed by Chris Advena. Thanks to http://allenbrowne.com/ser-38.html for the insight.
Public Function AddMsXmlLibrary(Optional PathFileExtStr As String = "C:\Windows\System32\msxml6.dll") As Integer
On Error GoTo FoundError
AddMsXmlLibrary = 1
References.AddFromFile (PathFileExtStr)
AllDone:
Exit Function
FoundError:
On Error Resume Next
AddMsXmlLibrary = 0
On Error GoTo 0
End Function

Events not being raised by FileSystemWatcher in an integration test?

I'm trying to run an integration test on my class to make sure an event i expect to be raised is raised:
'integration test not unit test
<TestMethod()>
Public Sub Change_Network_File_Causes_Event_To_Be_Raised()
Dim EventCalled As Boolean
Dim deployChk = New TRSDeploymentCheck("foo")
deployChk._localFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameLocalGUIDFile.txt")
AddHandler deployChk.DeploymentNeeded, Sub() EventCalled = True
deployChk.NetworkFileLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt")
ChangeNetworkFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt"))
Assert.IsTrue(EventCalled)
End Sub
Here is how i setup the FileSystemWatcher Object in my class:
Friend Property NetworkFileLocation As String
Set(value As String)
_netFileLoc = value
If File.Exists(value) Then
_watcher = New FileSystemWatcher(value.Replace(Path.GetFileName(value), String.Empty))
_watcher.EnableRaisingEvents = True
AddHandler _watcher.Changed, AddressOf OnNetworkFileChanged
End If
End Set
Get
Return _netFileLoc
End Get
End Property
Private Sub OnNetworkFileChanged(source As Object, e As FileSystemEventArgs)
If IsDeploymentNeeded() Then RaiseEvent DeploymentNeeded()
End Sub
I put a breakpoint in the OneNetworkFileChange sub. The breakpoint is never hit. I have verified the file is actually being changed in ChangeNetworkFile I even copied the code (except for hard coding the path) and copied it into a windows app which i ran during my unit test. It worked in my windows app. What am i missing here?
Finally figured it out after some testing. Well the reason EventCalled is never true above is because the "windows message pump" for the test is blocked. The event will be fired but only after the test completes (which of course is to late). So how do you fix it? Its kind of messy and i don't like it but i referenced System.Windows.Forms.dll & called Application.DoEvents()
'integration test not unit test
<TestMethod()>
Public Sub Change_Network_File_Causes_Event_To_Be_Raised()
Dim EventCalled As Boolean
Dim deployChk = New TRSDeploymentCheck("foo")
deployChk._localFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameLocalGUIDFile.txt")
AddHandler deployChk.DeploymentNeeded, Sub() EventCalled = True
deployChk.NetworkFileLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt")
ChangeNetworkFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles\SameNetGUIDFile.txt"))
Application.DoEvents()
Assert.IsTrue(EventCalled)
End Sub
Until some tells me a better way this appears to be the solution.
Probably its the filter (string.Empty) which apparently only looks at files without an extension (that's an assumption).
Try "*.*" or something like this:
_watcher = New FileSystemWatcher(value.Replace(Path.GetFileName(value), string.Concat("*.", Path.GetExtension(value))))

Setting a VCProject property to default

I'm trying some VS2005 IDE macros to modify a large amount of projects (~80) within a solution. Some of the properties I wish to set do expose a programmatic interface to 'default', but many others do not. Is there a generic way to set such properties to their default? (eventually meaning erasing them from the .vcproj file)
Simplified example, setting some random properties:
Sub SetSomeProps()
Dim prj As VCProject
Dim cfg As VCConfiguration
Dim toolCompiler As VCCLCompilerTool
Dim toolLinker As VCLinkerTool
Dim EnvPrj As EnvDTE.Project
For Each EnvPrj In DTE.Solution.Projects
prj = EnvPrj.Object
cfg = prj.Configurations.Item(1)
toolLinker = cfg.Tools("VCLinkerTool")
If toolLinker IsNot Nothing Then
' Some tool props that expose a *default* interface'
toolLinker.EnableCOMDATFolding = optFoldingType.optFoldingDefault
toolLinker.OptimizeReferences = optRefType.optReferencesDefault
toolLinker.OptimizeForWindows98 = optWin98Type.optWin98Default
End If
toolCompiler = cfg.Tools("VCCLCompilerTool")
If toolCompiler IsNot Nothing Then
' How to set it to default? (*erase* the property from the .vcproj)'
toolCompiler.CallingConvention = callingConventionOption.callConventionCDecl
toolCompiler.WholeProgramOptimization = False
toolCompiler.Detect64BitPortabilityProblems = False
End If
Next
End Sub
Any advice would be appreciated.
For VS 2005, I believe you can use the ClearToolProperty method on VCConfiguration. The following code would accomplish this for CallingConvention (this is C#, but I'm sure something similar works for VB):
cfg.ClearToolProperty( toolCompiler, "CallingConvention" );
This would have the same effect as going into the GUI and choosing "<inherit from parent or project defaults>" for this option.
Unfortunately this seems to be deprecated in VS 2010, and I'm not sure what the new supported method is.

Resources