Proper syntax for parameters in VB function call - c#

I have developed in the past in VB.net and I simply can't figure out how to properly call this function and how to get the response so I can display it on a web page response.
I translated the example c# code to VB. Here is my code behind for an aspx page that I wish to use to make the request and then display the response in my page:
Imports OffAmazonPaymentsService
Imports OffAmazonPaymentsService.Model
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write(GetOrderReferenceDetails(???service???, "asdfsadf", "asdfsadf", "asdfasdf"))
End Sub
Private Shared Function GetOrderReferenceDetails(service As IOffAmazonPaymentsService, sellerId As String, amazonOrderReferenceId As String, addressConsentToken As String) As GetOrderReferenceDetailsResponse
' Required parameters
Dim request As New GetOrderReferenceDetailsRequest()
request.SellerId = sellerId
request.AmazonOrderReferenceId = amazonOrderReferenceId
' Optional parameters
request.AddressConsentToken = addressConsentToken
Return service.GetOrderReferenceDetails(request)
End Function
End Class
I don't know how to call that function's first (service) parameter and to then display the contents of the response.
Let me know if my question is not clear enough.
here is the example they gave in c sharp format....
using OffAmazonPaymentsService;
using OffAmazonPaymentsService.Model;
public class GetOrderReferenceDetailsSample
{
/**
* Sample GetOrderReferenceDetails method that takes generic inputs, constructs a request object,
* and make a call to the service.
*/
private static GetOrderReferenceDetailsResponse GetOrderReferenceDetails(
IOffAmazonPaymentsService service,
string sellerId,
string amazonOrderReferenceId,
string addressConsentToken)
{
// Required parameters
GetOrderReferenceDetailsRequest request = new GetOrderReferenceDetailsRequest();
request.SellerId = sellerId;
request.AmazonOrderReferenceId = amazonOrderReferenceId;
// Optional parameters
request.AddressConsentToken = addressConsentToken;
return service.GetOrderReferenceDetails(request);
}
}

Disclaimer: my VB is "rusty" so debug and improve as necessary
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim props As OffAmazonPaymentsServicePropertyCollection = OffAmazonPaymentsServicePropertyCollection.getInstance()
Dim client As New OffAmazonPaymentsServiceClient(props)
Dim result as GetOrderReferenceDetailsResponse = GetAmzOrderRef(client, props, "oref", "token")
End Sub
Private Shared Function GetAmzOrderRef(service As IOffAmazonPaymentsService, props As OffAmazonPaymentsServicePropertyCollection, amazonOrderReferenceId As String, addressConsentToken As String) As GetOrderReferenceDetailsResponse
Dim request as New GetOrderReferenceDetailsRequest()
With request
.SellerId = props.MerchantID
.AmazonOrderReferenceId = amazonOrderReferenceId
.AddressConsentToken = addressConsentToken
End With
Return service.GetOrderReferenceDetails(request)
End Function
Notes:
you should have your config values set (web.config or app.config as necessary), that's where OffAmazonPaymentsServicePropertyCollection.getInstance() will obtain values
the above sample code will fail (as expected) because of dummy values for reference id and token, but that "error" is from the Amazon API (already) - e.g. response error "invalid reference id" or "invalid token" etc....
Hth....

Related

How to use Marshal.CreateWrapperOfType (the non-obsolete version) to cast from Com Object to Outlook Type

I have a piece of code that works well for me using an obsolete function. I'll strip down to minimal parts:
private dynamic pSentFolderItems; //will reference the Items of an Outlook Folder
public void WatchEmail2(object app, string emailID)
{
pApp = app; //this is actually an Outlook Application instance
//below reference to the Items object comes back as ComObject
pSentFolderItems = pApp.Session.GetDefaultFolder(5).Items;
//get the type through Reflection on the instance
Type olItemsType = pApp.GetType().Assembly.GetType("Microsoft.Office.Interop.Outlook.ItemsClass", false, true);
//pSentFolderItems = Marshal.CreateWrapperOfType(pSentFolderItems, olItemsType);
//above works every time but is marked Obsolete!!
//http://go.microsoft.com/fwlink/?LinkID=296519
//I'm struggling to implement the generic version of the CreateWrapperOfType method, as errors occur
//and I cannot input the type parameters without errors
pSentFolderItems = Marshal.CreateWrapperOfType<ShouldBeComObjectType, ShouldBeOlItemsType>(pSentFolderItems);
//.....rest of code........
}
Here is VB Code:
Public Class OVBO
Private pApp As Object
Public pMailId As String = ""
Public itemSent As Boolean = False 'change to a map?
Public itemWatching As Boolean = False
Public pSentFolderItems As Object
Public Sub WatchEmail2(app As Object, emailID As String)
pMailId = emailID
pApp = app
If Not itemWatching Then
pSentFolderItems = pApp.Session.GetDefaultFolder(5).Items
Dim olType As Type = pApp.GetType().Assembly.GetType("Microsoft.Office.Interop.Outlook.ItemsClass", False, True)
Dim myFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic
Dim evt As EventInfo = olType.GetEvent("ItemAdd", myFlags)
Dim evtHandlerType As Type = evt.EventHandlerType
Dim finalD As [Delegate] = [Delegate].CreateDelegate(evtHandlerType, Me, "MailSent2")
Dim addHandlerArgs() As Object = {finalD}
'The below works to return an Items Object(from a ComObject) that can be passed to the method handler invocation
pSentFolderItems = Marshal.CreateWrapperOfType(pSentFolderItems, olType)
'The above is obsolete, and am struggling to work with the non-obsolete method at [MSDN][1]
Dim miAddHandler As MethodInfo = evt.GetAddMethod()
miAddHandler.Invoke(pSentFolderItems, addHandlerArgs)
itemWatching = True
End If
Console.WriteLine("Watching {0}", emailID)
End Sub
'rest of class
End Class
Please note there are no references to the Outlook dll, and no Interop references.
So I am wondering if anyone can help translate the obsolete method call into the new way.

Integrating Mapinfo and .NET C#

I'm developing an app in MapBasic that calls methods in a .NET assembly library
This is how I Declare the method in my MapBasice enviroment.
Declare Method showMainWindow Class "mynamespace.AldebaranInterface" Lib "Aldebaran.dll" ()
Sub ShowWindow
Call showMainWindow()
End Sub
Sub formEventHandler
'Reacting to some button click. I need to call this Sub from somewhere in mynamespace.AldebaranInterface
End Sub
What I need is to callback some Sub or Funcion in my MapBasic application from my .NET C# code. Let's say execute some portion of MapBasic code when the user clicks some button that is in my .NET form.
Is there a way to do that? If so. How can I achieve it?
Any Help would be highly appreciated.
I'm not sure what is your .dll is supposed to do, I guess it's a form, since you need your mapbasic code to react to button click.
In order to send command to mapbasic you need to create instance of Mapinfo’s COM object.
Here is the link on how to do it. I personally use second approach.
So after you create class:
public class Mapinfo
{
private object mapinfoinstance;
public Mapinfo(object mapinfo)
{
this. mapinfoinstance = mapinfo;
}
public static Mapinfo CreateInstance()
{
Type mapinfotype = Type.GetTypeFromProgID("Mapinfo.Application");
object instance = Activator.CreateInstance(mapinfotype);
return new Mapinfo(instance);
}
public void Do(string command)
{
parameter[0] = command;
mapinfoType.InvokeMember("Do",
BindingFlags.InvokeMethod,
null, instance, parameter);
}
public string Eval(string command)
{
parameter[0] = command;
return (string)mapinfoType.InvokeMember("Eval", BindingFlags.InvokeMethod,
null,instance,parameter);
}
}
, you need to add button clicked event:
appMapInfo = Mapinfo.CreateInstance();
//It's good idea to pass this path string from your MapBasic code
//as method parameter in your .dll
string appMapInfoFilePath = #"D:\YourMBXPath\YourMBX.MBX";
//argumet you want to pass to MapBasic code
string argForMapBasic = ...;
string runCommand;
string subCommand;
subCommand = "dim i_chan_num as integer i_chan_num = DDEInitiate(\"\"MapInfo\"\",\"\"" + appMapInfoFilePath + "\"\")";
subCommand = subCommand + " DDEExecute i_chan_num, \"\"" + argForMapBasic + "\"\" DDETerminate i_chan_num";
runCommand = String.Format("Run Command \"{0}\"", subCommand);
appMapInfo.Do(runCommand);
Now on MapBasic side, you should create Sub RemoteMsgHandler (MapBasic Reference: A reserved procedure name, called when a remote application sends an execute message.)
Sub RemoteMsgHandler
Dim command as String
'command - string passed from your C# code (string argForMapBasic)
command = CommandInfo(CMD_INFO_MSG)
'pass a command to your procedure
Call yourProcedure(command)
End Sub

Use vb.net dll in C#. How to acces the objects in C# form from vb.net dll?

I cant completly converted the vb.net code to c# code so i decided to make a vb.net dll and then add it to c# form.
But im new about this dll things and i dont know how to acces the objects in C# form. I added C# application to references in dll as i did for the dll too. But i cant still access the timer and 2 labels which are in C# application.
This is my vb.net dll
Public Class Class1
Public Sub Bypass(block1 As String, block2 As String, ok1 As String, ok2 As String)
Try
Dim folderPath As String = Environment.GetFolderPath(SpecialFolder.Windows)
FileSystem.FileClose(New Integer() {1})
FileSystem.FileClose(New Integer() {2})
If My.Computer.FileSystem.FileExists((folderPath & "\xspirit.sys")) Then
FileSystem.FileOpen(1, (folderPath & "\xspirit.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
Else
File.WriteAllBytes((folderPath & "\xspirit.sys"), New Byte() {0})
FileSystem.FileOpen(1, (folderPath & "\xspirit.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
block1 = "Erişim Engellendi"
MsgBox("Erişim Engellendi xspirit")
End If
If My.Computer.FileSystem.FileExists((folderPath & "\xhunter1.sys")) Then
FileSystem.FileOpen(2, (folderPath & "\xhunter1.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
Else
File.WriteAllBytes((folderPath & "\xhunter1.sys"), New Byte() {0})
FileSystem.FileOpen(2, (folderPath & "\xhunter1.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
block2 = "Erişim Engellendi"
MsgBox("Erişim Engellendi xhunter1")
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.SetProjectError(ex)
Dim exception As Exception = ex
ProjectData.ClearProjectError()
ProjectData.ClearProjectError()
End Try
Dim p As Process()
p = Process.GetProcessesByName("Wolfteam.bin") 'set wolfteam process
If p.Count = 1 Then ' if wolfteam process detected
ok1 = "XignCode Clear Başarılı"
ok2 = "XignCode Clear Başarılı"
MsgBox("XignCode Clear Başarılı xspirit")
MsgBox("XignCode Clear Başarılı xhunter1")
End If
End Sub
End Class
I tried to convert C# but i cant do it completely so i tried to access the objects from my dll with this code but i couldn't do it (Yes i added it to references).
C#app.Form1(its okay until here but i cant continue this code.It doesn't accept the rest of it)
I wanted to write this actually:
C#app.Form1.Timer1.Enabled = False or C#app.Form1.label1.Text = "test"
I tried too:
Dim test1 As String="test"
'then acces them from C# and then:
vbnetdll.Class1 tt = new vbnetdll.Class1();
label1.Text=f.vbmethod.test1;
But i couldn't do this to. Because it doesn't accept. What is wrong?
By default when you add an item to a form it is declared as a private field in the form's class, like this:
private System.Windows.Forms.Label label1;
So it's not going to accessible from another assembly that references the form. It actually has nothing to do with C# vs vb.net.

pos for.net in windows 7 vb.net

I am using microsoft POS for .net dll and I am converting this part to vb.net from a HOL sample barcode reading tutorial written in c# found here.
EDIT:The device list shows and popup window shows (the activate button is pressed and scanner input is tested)but the txteventhistory is not update even when scanner emulator is used and i suspect the said part is the culprit. thank you for the response
{
Action<string> updateEventHistoryAction = new Action<string>(p => { txtEventHistory.Text = p; });
txtEventHistory.Invoke(updateEventHistoryAction, newEvent);
}
from this
void activeScanner_DataEvent(object sender, DataEventArgs e)
{
UpdateEventHistory("Data Event");
ASCIIEncoding encoder = new ASCIIEncoding();
try
{
// Display the ASCII encoded label text
string data = encoder.GetString(activeScanner.ScanDataLabel);
Action<string> updateScanDataLabelAction = new Action<string>(p => {txtScanDataLabel.Text = p;});
txtScanDataLabel.Invoke(updateScanDataLabelAction, data);
// Display the encoding type
string dataType = activeScanner.ScanDataType.ToString();
Action<string> updateScanDataTypeLabelAction = new Action<string>(p => { txtScanDataType.Text = p; });
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType);
// re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = true;
}
catch (PosControlException)
{
// Log any errors
UpdateEventHistory("DataEvent Operation Failed");
}
}
the conversion tool in #develop yielded the one below but i don't think it's correct
Dim updateScanDataLabelAction As New Action(Of String)(function (p)
txtScanDataLabel.Text = p
end function)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
I tried converting it to but not quite there i think, though it
Private Sub activeScanner_DataEvent(sender As Object, e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction append As New Action(Of String))
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
here is the whole code
Imports Microsoft.PointOfService
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Namespace POS
Partial Public Class ScannerLab
Inherits Form
Private explorer As PosExplorer
Private scannerList As DeviceCollection
Private scannerList1 As DeviceCollection
Private activeScanner As Scanner
Public Sub New()
InitializeComponent()
End Sub
Private Sub ScannerLab_Load(ByVal sender As Object, ByVal e As EventArgs)handles mybase.load
explorer = New PosExplorer()
scannerList1 = explorer.GetDevices()
bsdevices.DataSource = scannerList1
cboDevices.DisplayMember = scannerList1.ToString()
scannerList = explorer.GetDevices(DeviceType.Scanner)
devicesBindingSource.DataSource = scannerList
lstDevices.DisplayMember = scannerList.ToString()
End Sub
Private Sub btnActivateDevice_Click(ByVal sender As Object, ByVal e As EventArgs) handles btnActivateDevice.Click
If lstDevices.SelectedItem IsNot Nothing Then
ActivateScanner(DirectCast(lstDevices.SelectedItem, DeviceInfo))
End If
End Sub
Private Sub reportFailure()
Throw New Exception("The method or operation is not implemented.")
End Sub
Private Sub ActivateScanner(ByVal selectedScanner As DeviceInfo)
'Verifify that the selectedScanner is not null
' and that it is not the same scanner already selected
If selectedScanner IsNot Nothing AndAlso Not selectedScanner.IsDeviceInfoOf(activeScanner) Then
' Configure the new scanner
DeactivateScanner()
' Activate the new scanner
UpdateEventHistory(String.Format("Activate Scanner: {0}", selectedScanner.ServiceObjectName))
Try
activeScanner = DirectCast(explorer.CreateInstance(selectedScanner), Scanner)
activeScanner.Open()
activeScanner.Claim(1000)
activeScanner.DeviceEnabled = True
AddHandler activeScanner.DataEvent, AddressOf activeScanner_DataEvent
AddHandler activeScanner.ErrorEvent, AddressOf activeScanner_ErrorEvent
activeScanner.DecodeData = True
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log error and set the active scanner to none
UpdateEventHistory(String.Format("Activation Failed: {0}", selectedScanner.ServiceObjectName))
activeScanner = Nothing
End Try
End If
End Sub
Private Sub DeactivateScanner()
If activeScanner IsNot Nothing Then
' We have an active scanner, lets log that we are
' about to close it.
UpdateEventHistory("Deactivate Current Scanner")
Try
' Close the active scanner
activeScanner.Close()
Catch generatedExceptionName As PosControlException
' Log any error that happens
UpdateEventHistory("Close Failed")
Finally
' Don't forget to set activeScanner to null to
' indicate that we no longer have an active
' scanner configured.
activeScanner = Nothing
End Try
End If
End Sub
Private Sub activeScanner_DataEvent(ByVal sender As Object, ByVal e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction As New Action(Of String)(AddressOf p)
txtScanDataLabel.Invoke(updateScanDataLabelAction, data)
' Display the encoding type
Dim dataType As String = activeScanner.ScanDataType.ToString()
Dim updateScanDataTypeLabelAction As New Action(Of String)(AddressOf p)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub q(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub UpdateEventHistory(ByVal newEvent As String)
If txtEventHistory.InvokeRequired Then
Dim updateEventHistoryAction As New Action(Of String)(AddressOf q)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
Else
txtEventHistory.Text = (Convert.ToString(newEvent) & System.Environment.NewLine) + txtEventHistory.Text
End If
End Sub
Private Sub activeScanner_ErrorEvent(ByVal sender As Object, ByVal e As DeviceErrorEventArgs)
UpdateEventHistory("Error Event")
Try
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("ErrorEvent Operation Failed")
End Try
End Sub
EDIT: updated the code

How can I force web browser control to remember proxy credentials setting?

I'm using .net web browser control to open an url in new window through proxy with credentials. I use this code for that:
Public Function AppendHeader(ByRef OriginalHeader As String, ByVal Addition As String) As Boolean
If OriginalHeader <> "" Then
OriginalHeader = OriginalHeader + vbNewLine
End If
OriginalHeader = OriginalHeader + Addition
OriginalHeader.Trim(vbNewLine.ToCharArray)
End Function
Public Function Base64Enc(ByRef s As String) As String
Base64Enc = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(s))
End Function
Public Sub Navigate()
Dim webBrowser As WebBrowser = New WebBrowser()
Dim headers As String = ""
AppendHeader(headers, "Proxy-Authorization: Basic " & Base64Enc("user:pass"))
'AppendHeader(headers, "Authorization: Basic " & Base64Enc("user:pass"))
webBrowser.Navigate("http://stackoverflow.com", Guid.NewGuid().ToString(), Nothing, headers)
End Sub
This code helps to hide Windows Security window at the first time, but if loading web page sends requests to other urls this window shows again and again (you can see it on a screenshot below).
So what can I do to solve this problem?
(I'm using winforms and vb.net, but C# is suitable too)
Give this a try I am unable to test it :)
Private Sub webBrowser_Navigating(ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs)
Dim credentials As New System.Net.NetworkCredential("user", "pwd", "MyDomain")
Dim proxy As New System.Net.WebProxy("127.0.1.2", 80)
If proxy Is Nothing Then
e.Cancel = True
End If
End Sub

Categories