How do I get the Kind of Elements in an Array using Roslyn - vb.net

I am trying to get the Type that is iterated through using Roslyn. I can get the fact that the object is defined as String() using
Dim ElementTypeInfo As TypeInfo = SemanticModel.GetTypeInfo(ForEachStatement.Expression)
Dim expressionType As ITypeSymbol = ElementTypeInfo.Type
and in the Visual Studio debugger I can look at expressionType.ElementType and find out it is a String. But when I try to access ElementType in code I get an error saying the ElementType is not a member of ITypeSymbol.

If you know that expressionType is going to be an array, you can cast it to IArrayTypeSymbol. After that, you will be able to access its ElementType:
Dim expressionType = DirectCast(elementTypeInfo.Type, IArrayTypeSymbol)
Dim elementType As ITypeSymbol = expressionType.ElementType

Related

VB.net Unable to cast object of type System.Collections.Generic.list to type string

Please forgive me in advanced for my lack of coding knowledge.
I'm using a NuGet package called KuCoin.Net and have everything setup and connected. I can run the command and Place a Buy order so I know my Api settings are correct. The issue I'm having is when I run the following code:
Public Async Function GetBalancesAsync() As Task
Dim kucoinClient = New KucoinClient(New KucoinClientOptions() With {
.ApiCredentials = New KucoinApiCredentials("xxx", "xxx", "xxx"),
.LogLevel = LogLevel.Debug,
.RequestTimeout = TimeSpan.FromSeconds(60),
.FuturesApiOptions = New KucoinRestApiClientOptions With {
.ApiCredentials = New KucoinApiCredentials("xxx", "xxx", "xxx"),
.AutoTimestamp = False
}})
Dim accountData = Await kucoinClient.SpotApi.Account.GetAccountsAsync()
MessageBox.show(accountData.data)
End Function
I guess I'm needing to convert the list to a string so I can display it into a Messagebox.
The Error I recieve is as follows:
Unable to cast object of type 'System.Collections.Generic.List`1[Kucoin.Net.Objects.Models.Spot.KucoinAccount]' to type 'System.String'
Here is some additional info if this helps
Error
accountData
Any help is much appreciated
You can generate your String yourself using a StringBuilder while enumerating through accountData.Data:
Dim sb As New System.Text.StringBuilder
For Each account As Kucoin.Net.Objects.Models.Spot.KucoinAccount In accountData.data
sb.AppendLine(account.ToString)
Next
MessageBox(sb.ToString())
You can change account.ToString to something more appropriate like accout.Number perhaps (see the properties the KucoinAccount object has).

Disable an Exchange 2010 mailbox using VB.Net

I'm trying to disable a mailbox in Exchange 2010 using VB.Net.
Dim rsConfig As RunspaceConfiguration
rsConfig = RunspaceConfiguration.Create()
Dim snapInException As PSSnapInException = Nothing
Dim info As PSSnapInInfo = rsConfig.AddPSSnapIn("microsoft.exchange.management.powershell.e2010", snapInException)
Dim myRunSpace As Runspace
myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)
myRunSpace.Open()
Dim pipeLine As Pipeline
pipeLine = myRunSpace.CreatePipeline()
Dim sScript As String = "disable-mailbox -Identity 'Bill Smith' -Confirm:$false"
pipeLine.Commands.AddScript(sScript)
pipeLine.Invoke()
pipeLine.Dispose()
I get this error:
System.Management.Automation.CmdletInvocationException was unhandled
Message=Value cannot be null.
Parameter name: serverSettings
Source=System.Management.Automation
WasThrownFromThrowStatement=False
StackTrace:
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumerate)
at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
InnerException: System.ArgumentNullException
Message=Value cannot be null.
Parameter name: serverSettings
ParamName=serverSettings
Source=Microsoft.Exchange.Configuration.ObjectModel
StackTrace:
at Microsoft.Exchange.Configuration.Tasks.TaskVerboseStringHelper.GetADServerSettings(String cmdletName, ADServerSettings serverSettings)
at Microsoft.Exchange.Configuration.Tasks.TaskVerboseStringHelper.GetADServerSettings(ADServerSettings serverSettings)
at Microsoft.Exchange.Configuration.Tasks.Task.LogCmdletIterationEvent()
at Microsoft.Exchange.Configuration.Tasks.Task.BeginProcessing()
at System.Management.Automation.Cmdlet.DoBeginProcessing()
at System.Management.Automation.CommandProcessorBase.DoBegin()
InnerException:
Can anyone help?
Thanks in Advance.
This is the important part of the error:
Message=Value cannot be null. Parameter name: serverSetting
Stack traces can be tricky to read, but the first impression is that you're passing a null/Nothing value to a function that wants an instance of something.
I'm not familiar with the Exchange objects and you didn't share which line throws the error, but my best guess reading through the code is this line throws the error:
myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)
And you can fix it by changing this line near the top:
Dim rsConfig As RunspaceConfiguration
to this:
Dim rsConfig As New RunspaceConfiguration
Unfortunately, I suspect that this will only help you spot the next error. I expect there is a reason you need to pass a configuration object to that method, and the default instance may not be good enough.

Vb.Net Moq: Intercepting parameter and set to variable

I have a mocked object and i want to assign a variable with the parameter i'm calling it with:
Dim myMockedObject = new Mock(Of MyObject)()
Dim catchedVariable As MyEventArgs
myMockedObject.Setup(Sub(x) x.MyMethod(Of MyEventArgs)(It.IsAny(Of MyEventArgs)))
I need to find a way to fill the catchedVariable
Was not able to figure out a way to use an out parameter(Method is ByVal and don't want to change it just for testing).
Tried Moq method like CallBack but no succes there.
Got it working with the Callback:
_args As MyEventArgs
myMockedObject.Setup(Sub(x) x.MyMethod(Of MyEventArgs)(It.IsAny(Of MyEventArgs)())).Callback(Sub(x As MyEventArgs) _args = x)

VB.NET Deserialize JSON to anonymous object using newtonsoft returned error

I would like to deserialize the returned JSON from a service call in VB.NET to an anonymous type but I was having error. It works in C# using dynamic type but i dont know how to do it in VB.
Here is my JSON returned from a web service call:
{"format":"png","height":564,"width":864}
Here is my VB code json above assigned to param text:
Dim testObj = Newtonsoft.Json.JsonConvert.DeserializeObject(text)
But when i tried to access testObj.format, an exception was thrown with message
{"Public member 'format' on type 'JObject' not found."}
I already have added Option Strict Off. I dont want to use an Object/Class to deserialize the JSON. If its in C# assigning this to dynamic type will be working fine.
Can anyone please help? I am not expert in VB but I need to have this running on VB. TIA
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim testObj = js.Deserialize(source, New Object().GetType())
Then you can access the key(attribute name)/values via:
value=testobj(key)
One more thing, you can access your Newtonsoft key(attribute name)/values through:
value=testObj.item(key)
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim DeSerialObjEventData = New With {.Prop1 = String.Empty, .Prop2 = String.Empty, .Prop3 = String.Empty}...
Dim testObj = js.DeserializeAnnonomusType(source, DeSerialObjEventData)

convert vb.net data to json string and send it to a specific URL

this is the JSON string the data is required in to be sent using a given URL.
$jsonstr = '{"data":
[{
"id":"5",
"owner_id":"0",
"status":"unassigned",
"first_name":"Test",
"last_name":"IS",
"tobacco_user":"",
"date_of_birth":"",
"age":"",
"gender":"",
"email":"lb#you.com",
"zip":"",
"phone":"(210)629-2560",
"phone_type":"cell",
"phone_alt":"",
"phone_alt_type":"",
"product_msip":"",
"product_pdp":"",
"product_sdhv":""
},
I am using VB.net and i need to create this string using VB.net. I tried using namevaluecollection and doing a POST. I also tried making a string and send data using GET. Both failed. how can i do this?
Create an object with property names that are identical to those in your example, use the DataContract and DataMember attributes to mark serialization.
Then use the JavaScriptSerializer to serialize the object into JSON.
you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
If you don't want to build an actual class as #Oded recommended you can just hack it together as a string. I usually use a NameValueCollection as you said you tried.
''//Setup some values
Dim NVC As New NameValueCollection()
NVC.Add("id", "5")
NVC.Add("owner_id", "0")
NVC.Add("status", "unassigned")
''//Convert to string
Dim Pairs As New List(Of String)
For Each N As String In NVC.Keys
Pairs.Add(String.Format("""{0}"":""{1}""", N.Replace("""", "\"""), NVC(N).Replace("""", "\""")))
Next
Dim S = Join(Pairs.ToArray(), ",")
S now holds "id":"5","owner_id":"0","status":"unassigned" which you should be able to concat into your bigger JSON string.