Roslyn VB.Net Specify Compiler Version - vb.net

I am trying to compile a VB program using the code below, the code requires VB 15.5 and even when I specify LanguageVersion.Latest or LanguageVersion.VisualBasic15_5, I still get error ERR_ExpectedNamedArgument - Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments. Some code was removed to simplify example.
Public Function CompileVisualBasicString(StringToBeCompiler As String, SeverityToReport As DiagnosticSeverity, ByRef ResultOfConversion As ConversionResult) As EmitResult
If StringToBeCompiler.IsEmptyNullOrWhitespace Then
ResultOfConversion.FilteredListOfFailures = New List(Of Diagnostic)
ResultOfConversion.Success = True
Return Nothing
End If
Dim syntaxTree As SyntaxTree = VisualBasicSyntaxTree.ParseText(StringToBeCompiler)
Dim assemblyName As String = Path.GetRandomFileName()
Dim PreprocessorSymbols As New Dictionary(Of String, Object) From {
{"NETSTANDARD2_0", Nothing}
}
Dim ParseOptions As VisualBasicParseOptions = New VisualBasicParseOptions(
languageVersion:=LanguageVersion.Latest,
documentationMode:=DocumentationMode.Diagnose,
kind:=SourceCodeKind.Regular,
preprocessorSymbols:=PreprocessorSymbols)
Dim CompilationOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(
outputKind:=OutputKind.DynamicallyLinkedLibrary,
optionExplicit:=False,
optionInfer:=True,
optionStrict:=OptionStrict.Off,
parseOptions:=ParseOptions
)
Dim compilation As VisualBasicCompilation = VisualBasicCompilation.Create(
assemblyName:=assemblyName,
syntaxTrees:={syntaxTree},
references:=References,
options:=CompilationOptions
)
Dim CompileResult As EmitResult
Using ms As MemoryStream = New MemoryStream()
CompileResult = compilation.Emit(ms)
End Using
Return CompileResult
End Function

Thank you George, you solved the problem I needed to include the VisualBasicParseOption to Parse in addition to compile.

Related

Cannot convert an object to a string-array in vb.net but I can in C#.net (core)

I cannot cast an object to a string-array (or collection) in VB.net, I am able to do it in C#.
VB.net code:
Runtime.PythonDLL = "/usr/lib/python3.9/config-3.9-x86_64-linux-gnu/libpython3.9.so"
Using Py.GIL
Dim APT As Object = Py.Import("apt")
Dim Cache As Object = APT.Cache()
Dim PyObj As Object = Cache.keys()
Dim PKGs As String() = CType(PyObj, String())
End Using
I get the exception Unable to cast object of type 'Python.Runtime.PyObject' to type 'System.String[]'.
C#.net code which work:
Runtime.PythonDLL = "/usr/lib/python3.9/config-3.9-x86_64-linux-gnu/libpython3.9.so";
using (Py.GIL())
{
dynamic APT = Py.Import("apt"); // Type: dynamic {Python.Runtime.PyModule}, <module 'apt' from '/usr/lib/python3/dist-packages/apt/__init__.py'>
dynamic Cache = APT.Cache(); // Type: dynamic {Python.Runtime.PyModule}, <apt.cache.Cache object at 0x7fa701ec6760>
dynamic PyObj = Cache.keys(); // Type: dynamic {Python.Runtime.PyModule}, ['0ad', '0ad-data',...]
String[] PKGs = (String[])PyObj;
}
I see the same in the debugger for vb.net and C#.net.
Debugger in vb.net:
Debugger in C#.net:
I'm aware I use the dynamic type in C# and Object in VB. I do use option strict=Off in VB.
As fare I know VB doesn't have dynamic but I assume you can use Object instead if strict=Off.
Maybe that's the reason and it's just not possible?
I also tried to convert to:
arraylist
List(of String)
HasetSet(of String)
Dictionary(Of String, Object)
Tried both TryCast, DirectCast and CType.
Beside the solution from #Jeroen Mostert, which I prefer as it's more universal , I did find a method in the Python.net library that do the job: pyObject.As<T>()
Runtime.PythonDLL = "/usr/lib/python3.9/config-3.9-x86_64-linux-gnu/libpython3.9.so"
Using Py.GIL
Dim APT As Object = Py.Import("apt")
Dim Cache As Object = APT.Cache()
Dim PyObj As PyObject = Cache.keys()
Dim PKGs As String() = PyObj.As(Of String())() '<==========
Console.WriteLine(PKGs(0))
End Using
PythonEngine.BeginAllowThreads() 'Must be called to release the Py.GIL thread!

Creating a PDF with an image (datastream o from file) in iTextSharp

i'm trying to follow this example to create PDF with an image
Example PDF with an Image
I'm developing with VS2013 in VB.NET (ASP.NET 3.5).
I'm getting crazy, i don't understand 2 things:
what is the name that i've to pass in the IMG tag.
The src-attribute doesn´t contain a http-Url. Instead use the prefix data:imagestream to identify the source type of the image. After the following slash the name of the resource in the manifest of the .NET library is listed.
when the END ovveride function in CustomImageTagProcessor Class is executed
I've embedded an image in the project and the manifest contains
...
}
.mresource public Test1.phone.jpg
{
// Offset: 0x00000000 Length: 0x00003E0D
}
.mresource public Test1.Resources.resources
{
// Offset: 0x00003E11 Length: 0x0000406B
}
I'm debugging step by step but never the code in the ovverride function is executed.
This is the function that produce PDF
Public Function CreateFromHtml(ByVal html As String) As Stream
Dim stream = New MemoryStream()
Using doc = New Document(PageSize.A4)
Using ms = New MemoryStream()
Using writer = PdfWriter.GetInstance(doc, ms)
writer.CloseStream = False
doc.Open()
Dim tagProcessors = CType(Tags.GetHtmlTagProcessorFactory(), DefaultTagProcessorFactory)
tagProcessors.RemoveProcessor(iTextSharp.tool.xml.html.HTML.Tag.IMG)
tagProcessors.AddProcessor(iTextSharp.tool.xml.html.HTML.Tag.IMG, New CustomImageTagProcessor())
Dim cssFiles = New CssFilesImpl()
cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS())
Dim cssResolver = New StyleAttrCSSResolver(cssFiles)
Dim charset = Encoding.UTF8
Dim context = New HtmlPipelineContext(New CssAppliersImpl(New XMLWorkerFontProvider()))
context.SetAcceptUnknown(True).AutoBookmark(True).SetTagFactory(tagProcessors)
Dim htmlPipeline = New HtmlPipeline(context, New PdfWriterPipeline(doc, writer))
Dim cssPipeline = New CssResolverPipeline(cssResolver, htmlPipeline)
Dim worker = New XMLWorker(cssPipeline, True)
Dim xmlParser = New XMLParser(True, worker, charset)
Using sr = New StringReader(html)
xmlParser.Parse(sr)
doc.Close()
ms.Position = 0
ms.CopyTo(stream)
stream.Position = 0
End Using
End Using
End Using
End Using
Return stream
End Function
And this is the Class of CustomImageTagProcessor
Imports iTextSharp.tool.xml
Imports System.Reflection
Imports iTextSharp.text
Public Class CustomImageTagProcessor
Inherits iTextSharp.tool.xml.html.Image
Public Overrides Function [End](ByVal ctx As IWorkerContext, ByVal tag As Tag, ByVal currentContent As IList(Of IElement)) As IList(Of IElement)
Dim src = String.Empty
If Not tag.Attributes.TryGetValue(iTextSharp.tool.xml.html.HTML.Attribute.SRC, src) Then Return New List(Of IElement)(1)
If String.IsNullOrEmpty(src) Then Return New List(Of IElement)(1)
If src.StartsWith("data:imagestream/", StringComparison.InvariantCultureIgnoreCase) Then
Dim name = src.Substring(src.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1)
Using stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)
Return CreateElementList(ctx, tag, Image.GetInstance(stream))
End Using
End If
Return MyBase.[End](ctx, tag, currentContent)
End Function
Protected Function CreateElementList(ByVal ctx As IWorkerContext, ByVal tag As Tag, ByVal image As Image) As IList(Of IElement)
Dim htmlPipelineContext = GetHtmlPipelineContext(ctx)
Dim result = New List(Of IElement)()
Dim element = GetCssAppliers().Apply(New Chunk(CType(GetCssAppliers().Apply(image, tag, htmlPipelineContext), Image), 0, 0, True), tag, htmlPipelineContext)
result.Add(element)
Return result
End Function
End Class
Thanks so much for any helps.
I hope in you guys.
The problem was a lost
</img>
tag
Self Closed tag is not valid.
When i put tag also code inside overrided function has been executed.
Thanks so much.

VBCodeProvider Can not cast correctly the Implicit Variable declaration on compile

I am Compiling My string Code(I read My Code from Text File) In vb and it works fine but i have a function that returns nullable double(Double?)
when i use it like this
Dim x As Double? = Myfunc(1000) 'it returns Nothing
my x variable fills with Nothing and it's ok
But When I use it like this
Dim x = Myfunc(1000) 'it returns Nothing
my x value is 0 !!!!
How can i solve this problem
i want my users write codes like first code block
i tested all Option Explicit and Option Strict but it did not gain me anything.
please let me know how can i use Just dim x not Dim x as (type)
thank you for your helps
UPDATE :this is Myfunc Code :
Function Myfunc(parameterId As Long) As Double?
If parameterId = 1000 Then
Return Nothing
Else
Return tot(parameterId) 'it is a dictionary of values
End If
End Function
And this Is my Compile Class :
Private Shared Function Compile(ByVal vbCode As String) As CompilerResults
Dim providerOptions = New Dictionary(Of String, String)
providerOptions.Add("CompilerVersion", "v4.0")
' Create the VB.NET compiler.
Dim vbProv = New VBCodeProvider(providerOptions)
' Create parameters to pass to the compiler.
Dim vbParams = New CompilerParameters()
' Add referenced assemblies.
vbParams.ReferencedAssemblies.Add("mscorlib.dll")
vbParams.ReferencedAssemblies.Add("System.Core.dll")
vbParams.ReferencedAssemblies.Add("System.dll")
vbParams.ReferencedAssemblies.Add("System.Windows.Forms.dll")
vbParams.ReferencedAssemblies.Add("System.Data.dll")
vbParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
vbParams.ReferencedAssemblies.Add("System.Xml.dll")
vbParams.ReferencedAssemblies.Add("System.Xml.Linq.dll")
vbParams.GenerateExecutable = False
' Ensure we generate an assembly in memory and not as a physical file.
vbParams.GenerateInMemory = True
' Compile the code and get the compiler results (contains errors, etc.)
Return vbProv.CompileAssemblyFromSource(vbParams, vbCode)
End Function
As discussed above, Option Infer On needs to be included to force the compiler to create the variable as the required type - in this case the Double? returned by MyFunc.

Calling System.IO.ReadAllBytes by string name

This post is related to Visual Basic .NET 2010
So, I'm wondering if there's any way to call a function from a library such as System.ReadAllBytes by string name.
I've been trying Assembly.GetExecutingAssembly().CreateInstance and System.Activator.CreateInstance followed by CallByName(), but none of them seemed to work.
Example of how I tried it:
Dim Inst As Object = Activator.CreateInstance("System.IO", False, New Object() {})
Dim Obj As Byte() = DirectCast(CallByName(Inst, "ReadAllBytes", CallType.Method, new object() {"C:\file.exe"}), Byte())
Help is (as always) much appreciated
It is System.IO.File.ReadAllBytes(), you missed the "File" part. Which is a Shared method, the CallByName statement is not flexible enough to permit calling such methods. You will need to use the more universal Reflection that's available in .NET. Which looks like this for your specific example, spelled out for clarity:
Imports System.Reflection
Module Module1
Sub Main()
Dim type = GetType(System.IO.File)
Dim method = type.GetMethod("ReadAllBytes")
Dim result = method.Invoke(Nothing, New Object() {"c:\temp\test.bin"})
Dim bytes = DirectCast(result, Byte())
End Sub
End Module

How do i unlabel a file using the TFS sdk and vb.net

I'm in the process of writing a little app for our SQL developers to allow them to create labels with TFS for easy code deployment, the trouble is the .ssmssqlproj files are being added to the label when ever i create one. I've added a sub to loop through and unlabel these file but i just will not work. code below
Public Sub UnlabelItem()
Dim returnValue As LabelResult()
Dim labelName As String = "1208-2210"
Dim labelScope As String = "$/"
Dim version As VersionSpec = New LabelVersionSpec(labelName, labelScope)
Dim path As String = "$/FEPI/Database/FEPI/000 Pre Tasks.ssmssqlproj"
Dim recursion As RecursionType = RecursionType.None
Dim itemspec As ItemSpec = New ItemSpec(path, recursion)
returnValue = sourceControl.UnlabelItem(labelName, labelScope, itemspec, version)
End Sub
this is a test Sub just to get it working and this is the error i get
Value of type 'Microsoft.TeamFoundation.VersionControl.Client.ItemSpec' cannot be converted to '1-dimensional array of Microsoft.TeamFoundation.VersionControl.Client.ItemSpec'
HAs anybody had any luck with the unlabel command?
Matt