WCF Generated Classes - c#

I'm converting a sample VB Client (from a 3rd party SDK which consumes its WCF Services) to C#. The client in VB when executed, works correctly.
I'm writing a small wrapper in C# Windows Form in vs2015 to consume the same WCF Services. I was able to add the service references in VS2015.
I am having a problem making an equivalent call in VB which works but for some reason in C#, it does not work, as if the generated C# classes is incorrect.
in the working sample VB,
I have a call ContinueGetList
Dim siteList() As SRAdminSys.MW_DataContractCommon
Dim iRecCount As Integer = 20
Dim Status As SRAdminSys.MW_ContinueStatusEnum
Status = m_wcfSysDB.ContinueGetList(iRecCount, siteList)
The call returns a list in siteList which is an array of SRAdminSys.MW_DataContractCommon
note: I think* the actual The array returned by the webservice , is of type MW_Site which inherits DataContractCommon - (* when I made the same call in a C# equivalent call, I get an error and when I checked the error , it mentioned that it is casting MW_Site to MW_DataContractCommon )- See further test below.
Partial Public Class MW_Site
Inherits SRAdminSys.MW_DataContractCommon
The Reference.vb from the Generated Proxy Class:
Public Function ContinueGetList(ByVal iCount As Integer, ByRef list() As SRAdminSys.MW_DataContractCommon) As Integer Implements SRAdminSys.IMW_KWSAdminSysDatabase.ContinueGetList
Return MyBase.Channel.ContinueGetList(iCount, list)
End Function
Now in the Non-Working prototype in C# ( it does compile though ) ,
int[] lst_SiteIds = new int[] { };
int iRecCount = 20;
SRAdminSys.MW_ContinueStatusEnum status;
status = (SRAdminSys.MW_ContinueStatusEnum)adminSysClient.ContinueGetList(iRecCount,ref siteList);
The return value status indicated that the call failed and when I check the error - a WCF method GetLastError(), I get
Unable to cast object of type 'MW_DataContractCommon[]' to type 'MW_Site[]'.
When I check the MW_Site Partial class generated by C# Service Reference, I notice it inherits DataContractCommon, so I expected it to work:
public partial class MW_Site : SRAdminSys.MW_DataContractCommon {
Reference.cs
public int ContinueGetList(int iCount, ref TestUtil.SRAdminSys.MW_DataContractCommon[] list) {
TestUtil.SRAdminSys.ContinueGetListRequest inValue = new TestUtil.SRAdminSys.ContinueGetListRequest();
inValue.iCount = iCount;
inValue.list = list;
TestUtil.SRAdminSys.ContinueGetListResponse retVal = ((TestUtil.SRAdminSys.IMW_KWSAdminSysDatabase)(this)).ContinueGetList(inValue);
list = retVal.list;
return retVal.ContinueGetListResult;
}
CWUtility.SRAdminSys.ContinueGetListResponse retVal = ((CWUtility.SRAdminSys.IMW_KWSAdminSysDatabase)(this)).ContinueGetList(inValue);
list = retVal.list;
return retVal.ContinueGetListResult;
}
In relation to the partial class and inheritance of DataContractCommon - On another sample code which works in VB but not in C# when both is pointing to the same WCF service. The only difference is a VB App vs a C# App which points to their respective generated proxy classes from VS Service Reference.
Dim sitekey__ As New SRAdminSite.MW_Key
bRet = m_wcfSiteDB.Add(1, eKEY_COLLECTION, sitekey__)
VB, Reference.vb
Public Function Add(ByVal iSiteID As Integer, ByVal iCollectionType As Integer, ByRef iRecord As SRAdminSite.MW_DataContractCommon) As Boolean Implements SRAdminSite.IMW_KWSAdminSiteDatabase.Add
Return MyBase.Channel.Add(iSiteID, iCollectionType, iRecord)
End Function
SRAdminSite.MW_Key sitekey__ = new SRAdminSite.MW_Key();
//COMPILE ERROR on sitekey__ although MW_Key is a partial class which inherits MW_DataContractCommon
bRet = adminSiteClient.Add(1, (int)SRAdminSite.MW_SiteCollectionTypesEnum.eKEY_COLLECTION, ref sitekey__);
C#, Reference.cs
public bool Add(int iSiteID, int iCollectionType, ref SRAdminSite.MW_DataContractCommon iRecord)
{
SRAdminSite.AddRequest inValue = new SRAdminSite.AddRequest();
inValue.iSiteID = iSiteID;
inValue.iCollectionType = iCollectionType;
inValue.iRecord = iRecord;
SRAdminSite.AddResponse retVal = ((SRAdminSite.IMW_KWSAdminSiteDatabase)(this)).Add(inValue);
iRecord = retVal.iRecord;
return retVal.AddResult;
}
So both these examples seems to be related to the way the proxy classes the WCF Service was generated and inheriting other classes but unable to work. In the 2nd sample the error was at compile time...
Can anyone shed some light, why in VB the default generated class works when called, but in c#, the same equivalent call to the same method does not work?
I've consumed other 3rd party WCF services and normally, importing the Service Reference and consuming the methods were a breeze...
For some reason, this one, I cant wrap my head around why it will not work. Is there something I'm missing or need to modify in the way the Reference.cs is generated before I consume them?

Related

WinRT C++ IMap returning Windows Runtime Object instead of IDictionary into C#

We have a problem with a C++ Backend Library for our C# Windows Store Application.
On the C++ side we have a property that is defined like this:
property IMap<String^, IMap<String^, String^>^ >^ myVariable;
On the C# side the property is correctly transformed to:
public IDictionary<string, IDictionary<string, string>> myVariable { get; set; }
The situation: while in debug (with a breakpoint set), you can see that the returned object from C++ is a Windows Runtime Object, instead of the expected Dictionary. I can iterate through the returned object and the code in the foreach loop executes successfully.
The problem: if I remove the breakpoint (but I am still in debug), the returned object does not have any information. It is not null, as I get no exception, but it is empty (the foreach loop does not execute -- the inner breakpoint is not reached).
More information:
the Dictionary itself is part of a larger object;
the rest of the properties contain information;
in a C++ Windows Store Application the Dictionary (IMap) is correctly displayed (so the problem may be from the linking between C++ and C#);
I get the backend object using async Tasks:
BiggerObject myObject = await Task.Factory.StartNew(() =>
{
return _clientInstance.GetMyObject(key);
});
Do you have any ideas why the Dictionary is not correctly recognized while in Debug and why it is empty while not in Debug?
Thank you for your answers!
Regards,
Ionut
This works fine for me.
Simple C++ code:
Header
public ref class MapOfMapsTest sealed
{
public:
MapOfMapsTest();
property IMap<String^, IMap<String^, String^>^>^ Stuff;
};
Implementation
MapOfMapsTest::MapOfMapsTest()
{
auto outerMap = ref new Platform::Collections::Map<String^, IMap<String^, String^>^>();
auto innerMap = ref new Platform::Collections::Map<String^, String^>();
innerMap->Insert(L"1", L"one");
innerMap->Insert(L"3", L"three");
outerMap->Insert(L"odd", innerMap);
innerMap = ref new Platform::Collections::Map<String^, String^>();
innerMap->Insert(L"2", L"two");
innerMap->Insert(L"4", L"four");
outerMap->Insert(L"even", innerMap);
Stuff = outerMap;
}
Simple C# code (where lv is a ListView declared in the XAML)
private void DoMapThing()
{
var test = new MapOfMapsTest();
foreach (var k in test.Stuff.Keys)
{
var innerDict = test.Stuff[k];
foreach (var k2 in innerDict.Keys)
lv.Items.Add(String.Format("{0} -> {1} : {2}", k, k2, innerDict[k2]));
}
}

Passing Structures to unmanaged code from C# DLL to VB6

I have some customers that uses apps using VB6 and some others languages. The code works fine using OLE (COM), but customers prefers to use native DLL to avoid to register the libraries and deploy them in the field.
When I register the DLL and test in VB6 (OLE), it works fine. When I call a method that return a Strutc, it works fine with OLE, but, if I access in VB6 using Declare, I got fatal error in method that should return the same kind of struct (method 'EchoTestData' see bellow).
The code is compile in C# to use in unmanaged code with OLE or by entry points> I had tested with VB6.
namespace TestLib
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("TestClass")]
public class TestClass : System.EnterpriseServices.ServicedComponent
{
/*
* NOTE:
* ExportDllAttribut: a library that I have used to publish the Entry Points,
* I had modified that project and it works fine. After complile, the libray
* make the entry points...
* http://www.codeproject.com/Articles/16310/How-to-Automate-Exporting-NET-Function-to-Unmanage
*/
/*
* System.String: Converts to a string terminating in a null
* reference or to a BSTR
*/
StructLayout(LayoutKind.Sequential)]
public struct StructEchoData
{
[MarshalAs(UnmanagedType.BStr)]
public string Str1;
[MarshalAs(UnmanagedType.BStr)]
public string Str2;
}
/*
* Method static: when I use this method, the Vb6 CRASH and the EVENT VIEWER
* show only: System.Runtime.InteropServices.MarshalDirectiveException
* HERE IS THE PROBLEM in VB6 with declare...
* Return: struct of StructEchoData type
*/
[ExportDllAttribute.ExportDll("EchoTestStructure", CallingConvention.StdCall)]
public static StructEchoData EchoTestStructure(string echo1, string echo2)
{
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoTestData] Retorno String[1]: ", echo1),
Str2 = String.Concat("[EchoTestData] Retorno String[1]: ", echo2)
};
return ws;
}
/*
* Method NOT static: it is used as COM (OLE) in VB6
* In VB6 it returns very nice using with COM.
* Note that returns the StructEchoData without problems...
* Return: struct of StructEchoData
*/
[ExportDllAttribute.ExportDll("EchoTestStructureOle", CallingConvention.StdCall)]
public StructEchoData EchoTestStructureOle(string echo1, string echo2)
{
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoOle] Return StringOle[1]: ", echo1),
Str2 = String.Concat("[EchoOle] Return StringOle[2]: ", echo2),
};
return ws;
}
/*
* Method static: It works very nice using 'Declare in VB6'
* Return: single string
*/
[ExportDllAttribute.ExportDll("EchoS", CallingConvention.StdCall)]
// [return: MarshalAs(UnmanagedType.LPStr)]
public static string EchoS(string echo)
{
return "[TestClass::EchoS from TestLib.dll]" + echo;
}
/*
* Method NOT static: it is used as COM (OLE) in VB6
* In VB6 it returns very nice
* Return: single string
*/
[ExportDllAttribute.ExportDll("EchoSOle", CallingConvention.StdCall)]
// [return: MarshalAs(UnmanagedType.LPStr)]
public string EchoSOle(string echo)
{
return "[TestClass::EchoS from TestLib.dll]: " + echo;
}
}
}
Now, in VB6 I cant test using Declare or register the TestLib.Dll as COM
USING DECLARE in VB6:
Private Declare Function EchoS Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll"_
(ByVal echo As String) As String
Private Type StructEchoData
Str1 As String
Str2 As String
End Type
Private Declare Function EchoTestStructure Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll"_
(ByVal echo1 As String, ByVal echo2 As String) As StructEchoData
// ERROR - CRASH VB6
Private Sub EchoData_Click()
Dim ret As StructEchoData
ret = EchoTestStructure("echo1 Vb6", "echo2 vb6")
TextBox.Text = ret.Str1
End Sub
// WORKS Fine, returns a string
Private Sub btRunEchoTestLib_Click()
TextBox.Text = EchoS("{Run from VB6}")
End Sub
And using VB6 wiht OLE:
1St. Registering the DLL: C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe TestLib.dll /tlb:Test.tlb
2nd. Add the reference in project. The program runs and I got the response with one string and receive the response when has a structure too.
Private Sub Echo_Click()
Dim ResStr As String
Dim obj As TestLib.TestClass
Set obj = New TestClass
ResStr = obj.EchoSOle(" Test message")
MsgBox "Msg Echo: " & ResStr, vbInformation, "ResStr"
Beep
End Sub
Private Sub EchoDataOle_Click()
Dim obj As TestLib.TestClass
Set obj = New TestClass
// Here I define the struct and works fine!!
Dim ret As TestLib.StructEchoData
ret = obj.EchoTestStructureOle("test msg1", "test msg2")
TextStr1.Text = ret.Str1
TextStr2.Text = ret.Str2
Debug.Print ret.Str1
Debug.Print ret.Str2
Beep
End Sub
So, the StructEchoData is wrapped fine using COM, but if I want to use Declare and got the access by entry point, not work. Could anybody suggest anything, please?
The VB6 Declare Lib only works for unmanged DLL exported functions. C# does not expose it's functions as unmanged functions, since it's managed code. The only supported way to exporting classes from C# is to use COM. So you can't use Declare Lib to access C# methods from VB6.
There is a library that is supposed to create unmanged exports from your C# code; Robert Giesecke's Unmanaged Exports. I've personally never used it; I've only seen it mentioned on Stack Overflow.
There is a supported way to export unmanged functions from a .Net assembly and that is using C++/CLR since it allows the mixing of managed and unmanged code. You could create a C++/CLR wrapper that exported unmanged functions that call your C# DLL. That is the way I would go.
You cannot create Dynamic Link Libraries with c#.
However, with a little bit of C++ you can create a bootstrapper for .Net dll's by leveraging the CLR hosting API.
CLR Hosting API
You can create a Dynamic Link Library in C++ with a method called something like "LoadPlugins".
Write LoadPlugins to load the CLR (or a specific version of the CLR), then use reflection to load some .net DLL's.
Also with the same C++ code, you can expose .net methods in the C++ dll as exported native functions in c++ that will work with VB6's declare...
Each function in c++ would have to check to make sure the CLR is loaded, and that the .net code being called is loaded, then use reflection to call it.
Thanks for replies,
The C# only will work with unmanaged DLL if there are Entry Points into the code. The declarations that were used into the code with the statement 'ExportDllAttribut' generate the respectives Entry Points that are necessary to be used by unmanagement code.
The problem is to use export with "Data Structure", that is my question.
I had used without problems the methods that return string or integer values, like EchoS in this post. I used this example (TestLib.DLL) with VB6 and it works fine with "Declare" in VB6:
Private Declare Function EchoS Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll"_
(ByVal echo As String) As String
// WORKS Fine, returns a string
Private Sub btRunEchoTestLib_Click()
TextBox.Text = EchoS("{Run from VB6}")
End Sub
I wrote a note at the begining the C# code, but could not be clear, sorry. Explained a bit more. After I compile the library, I use in "Project properties", "Build events" the following command:
"$(ProjectDir)libs\ExportDll.exe" "$(TargetPath)" /Debug
This directive [ExportDllAttribute.ExportDll("NameOfEntryPoint"] disasembly the DLL (using ilasm.exe and ildasm.exe) and write the exports directives to create Entry Points, compiling and generating the DLL again. I used few years and works fine.
If I apply the dumpbin command in DLL, the results are the Entry Points published, so, it is possible to use with unmanaged code like VB6, but using the correct Marshalling type or statement in Vb6. Example:
dumpbin.exe /exports TestLib.dll
ordinal hint RVA name
2 0 0000A70E EchoC
5 1 0000A73E EchoSOle
3 2 0000A71E EchoTestStructure
6 3 0000A74E EchoTestStructureOle
This code was tested using the method EchoS (with Declare) or EchoSOle (COM) and in both cases are fine. When the DLL is used as OLE in app, the structure can be see as Type and the run fine, but, in VB6 with declare, I got error MarshalDirectiveException only with Structure returns, singles types like string C# or integer, I don't have problem.
I think thet the problem is how to the Structure was marshalling by the static method EchoTestStructure or how to was declared in VB6. Maybe could be a wrong way used in VB6 (that I am not any expert) or any marshalling parameter in Static Method 'EchoTestStructure', that is the real question and help.
PS: I will see the links in the replies to try another approaches if I can´t solve it.
Thanks again, Any other idea?
It was Solved, but by another way... this can be not the state of the art, but it works.
First thing, it was needed to change the Marshaling type in struct, from BStr to LPStr.
I don't know what was exactly the motive because some Microsoft helps and others links, they said: "System.String : Converts to a string terminating in a null reference or to a BSTR".
If I set "Hello" into the Str1 in the Structure, I receive "效汬㉯映潲䉖⸶⸮" into the DLL. If I return a fixed string "Hello" form DLL, the VB6 shows only the first char "H", so, I change to ANSI (LPStr) and solve it. Using OLE, the BSTR Works fine, but native DLL does not. The code was changed to:
StructLayout(LayoutKind.Sequential)]
public struct StructEchoData
{
[MarshalAs(UnmanagedType.BStr)]
public string Str1;
[MarshalAs(UnmanagedType.BStr)]
public string Str2;
}
In the method 'EchoTestStructureOle' declaration, it was change to use reference and passing the address of structure intead return a structure. Before the code was:
public StructEchoData EchoTestStructure(string echo1, string echo2)
{
// It Works only wtih OLE the return of the type StructEchoData
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoTestData] Return from DLL String[1]: ", echo1),
Str2 = String.Concat("[EchoTestData] Return from DLL String[2]: ", echo2)
};
return ws;
}
And now I am using interger to return the status (1 ok, -1 error) and the parameter structure type by reference, the method was change to:
public static int EchoTestStructure(ref StructEchoData inOutString)
{
// used to test the return of values only, data 'in' not used
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoTestData] Return from DLL String[1]: ", inOutString.Str1),
Str2 = String.Concat("[EchoTestData] Return from DLL String[2]: ", inOutString.Str2)
};
inOutString = ws;
return 1;
}
With reference, I can receive the values from VB6 and return to VB6 without no problems. I think that must have a way to return a structure, but, this approach solve it for this time.
In VB6 side: the code was changed to:
Private Type StructEchoData // Same type, do not change...
Str1 As String
Str2 As String
End Type
Private Declare Function EchoTestData Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll" (ByRef strcData As StructEchoData) As Long
Private Sub ShowMessage_Click()
Dim res As Long
Dim strcData As StructEchoData
strcData.Str1 = "Str1 from VB6..."
strcData.Str2 = "Str2 from VB6..."
res = EchoTestData(strcData)
/*
strcData.Str1 --> Data Received from DLL:
[EchoTestData] Return from DLL String[1]: Str1 from VB6...
strcData.Str2 --> Data Received from DLL
[EchoTestData] Return from DLL String[2]: Str2 from VB6...
*/
...
End Sub
Thanks for the tips for while. If you have any suggest, it will be welcome.

Webservice.asmx not receiving parameters with POST/SOAP requests

I am trying to send data to a C# (actually Mono) webservice from a PHP environment. Oddly, the webservice works correctly when I call it with a browser URL (i.e. with the GET method).
However, calling it from my PHP script shows that no parameter is received on Mono's side.
Here is my PHP call:
$domoWSHeader->setAuthenticatedToken($resultAuthentification->AuthentificationResult);
$inputHeaders = new SoapHeader("http://tempuri.org/domo", "DomoWSHeader", $domoWSHeader, false);
$result = $soapClient->__soapCall("MyWebServiceMethod", array("idLight"=>$uuid), NULL, $inputHeaders);
And the Webservices.asmx looks like:
namespace domo
{
public class DomoWSHeader : System.Web.Services.Protocols.SoapHeader
{
public string username;
public string password;
public string authenticatedToken;
}
[WebMethod]
public bool MyWebServiceMethod(int idLight)
{
bool success = false;
//Snip
return success;
}
}
What have I tried?
Trying to declare [System.Web.Services.Protocols.SoapHeader("DomoWSHeader")] before the method didn't change the behaviour.
I also tried to edit the web.config file to add protocols in it. I am totally new to the C# world, and I am not sure where to find answers to this problem. I hope one of you can help me understand what happens here.
Found the origin of the problem from PHP.NET : http://php.net/manual/fr/soapclient.soapcall.php#110390
In the PHP code, the parameters in the "__soapCall()" method were :
$parameters = array("idLight" => $uuid);
but it's correct when you use them to call the webservice method directly as :
$soapClient->NameOfTheMethod($parameters);
In my case, i'd need to call the webservice method with "__soapCall()" because i use headers for authentication, and the PHP.NET documentation says that we must encapsulate the array of parameters into another array like this :
$soapClient->__soapCall("NameOfTheMethod", array($parameters), NULL, $inputHeaders);
(Note that the 3rd and the 4th parameters in the "__soapCall()" method are optionals but i use them)
Hope this help :)

Assigning value to class method with parameters in C#

I'm working in an assembly in C# that will replace an old DLL registered as COM. That old DLL allowed COM enabled applications (like VB or Perl) or do things like in the following VBS example:
dim All_Domains
set All_Domains = WScript.CreateObject("MailServerX.LocalDomains")
dim Specific_Domain
set Specific_Domain = All_Domains.Items(3)
dim Domain_Aliases
set Domain_Aliases = WScript.CreateObject("MailServerX.Lines")
Domain_Aliases.Add "one.com"
Domain_Aliases.Add "two.com"
Specific_Domain.Domain_Aliases = Domain_Aliases
All_Domains.Items(3) = Specific_Domain
As you can see in the last line, the property/method LocalDomains.Items is being assigned while passing the parameter "3".
I need to maintain the same interface in the new assembly in order to keep compatibility with all existing scripts that access the old DLL. I have this (very summarized) C# class:
public class LocalDomains
{
private List<LocalDomain> itemsList = new List<LocalDomain>();
# Assume the list is now loaded
public LocalDomain Items(int index)
{
return itemsList[index];
}
}
How can I write the method Items in the class LocalDomains so it can not only return a value from the list, but also receive a value assignment so it can do some processing with itemsList[index] including assigning the new value to it?
By that I mean, keeping the last line of my first code block valid with the new code.
Thanks in advance for any advice!

Array of Objects/Classes fails for user defined Class

I am hoping someone with some more C++ knowledge might be able to help me. I am trying to create an array of objects in C# from a Class I've created in a Managed C++ DLL. I haven't any clue what is going on. I am able to run the application and build it setting up the array of classes appears to work perfectly fine but when I call a function from the array it never researches the Managed DLL. I've traced it and it simply doesn't work. The application doesn't fail with any errors either. Interestingly enough when I removed the array of classes and only initiated the class once it works all fine and dandy. Please help me figure out how to fix this.
//C#
public ClientBridge[] netlobby;
private void connectToLobby(int lobbyIndex)
{
//lobbyIndex = 0
netlobby[lobbyIndex] = new ClientBridge();
connectLobby[lobbyIndex] = netlobby[lobbyIndex].MMK_Connect(host, lobbyport);
}
//C++ DLL
// This class is the managed reference class
public ref class ClientBridge
{
public:
ClientBridge();
virtual ~ClientBridge();
bool MMK_Connect(String^ hostpass, UInt16 port);
};
doesn't look like you ever initialize the array
public ClientBridge[] netlobby = new ClientBridge[MAX_BRIDGES]; // <- gotta initialize
private void connectToLobby(int lobbyIndex)
{
netlobby[lobbyIndex] = new ClientBridge();
connectLobby[lobbyIndex] = netlobby[lobbyIndex].MMK_Connect(host, lobbyport);
}

Categories

Resources