Using groovy ws with enum types? - wcf

I'm trying to use groovy ws to call a webservice. One of the properties of the generated class is it's self a class with an enum type. Although the debug messages show that the com.test.FinalActionType is created at runtime when the WSDL is read I can't create an instance of it using code like
proxy.create("com.test.FinalActionType")
When I try and assign a string to my class uin place of an instance of FinalActionType groovy is not able to do the conversion. How can I get an instance of this class to use in a webservice call? I've pasted the important part of the WSDL below.
<xsd:simpleType name="FinalActionType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="stop"/>
<xsd:enumeration value="quit"/>
<xsd:enumeration value="continue"/>
<xsd:whiteSpace value="collapse"/>
</xsd:restriction>
</xsd:simpleType>

I don't think it can easily be done yet, not using the available WSClient API.
There was a suggestion to add a "createEnum" method to the WSClient class (see test case patch and issue GMOD-82). Judging by Guillaume Alleon's comments under issue GMOD-4, there should be a way to create an enum instance when WSClient 0.5.1 is released.
UPDATE:
As of GroovyWS 0.5.2 (at least, I haven't tried 0.5.1), enums can be used with GroovyWS as follows:
...
wsProxy = new WSClient(wsdlUrl, this.class.classLoader)
wsProxy.initialize()
def anObject = wsProxy.create("some.package.AServiceInterface")
def anEnum = wsProxy.create("some.package.AnEnum")
anObject.anEnumProperty = anEnum.AN_ENUM_VALUE
...

Related

Facing issue when trying to fake helper function

I am using Nunit and FakeItEasy for my MVC Controller functions.
My Test Code:
[Test]
public async Task Search_Success()
{
if (!isFakeInitialized)
InitializeFake();
url = "/N/UserSvc/v1/Types?skip=0&take=" + Constants.MaxSearchRowNumber;
Types= A.CollectionOfFake<Type>(3);
List<Type> found=new List<Type>(Types);
A.CallTo(() => nFake.GetDataAsync<IEnumerable<Type>>(fakeHttpSession, url)).Returns(Types);
var fakeHelper = A.Fake<helperFunctions>();
A.CallTo(() => FakeHelper.GetAvailableTypes(fakeHttpSession, found, true)).Returns(foundTypes);
//Act
var actionResult = await myController.SearchView();
var viewResult = actionResult as ViewResult;
//Assert
Assert.IsNotNull(viewResult);
Assert.AreEqual("Search", viewResult.ViewName);
}
I am getting error at
A.CallTo(() => nFakeHelper.GetAvailableTypes(fakeHttpSession, found, true)).Returns(foundTypes);
Error: cannot convert lambda expression to type object because it is not a delegate type.
Here is the helper function Code:
public List GetAvailableTypes(Session session,List allTypes,bool includeAllType)
{
List results = new List();
return results;
}
How can i overcome the error.
If nothing else, your A.CallTo should fail because GetAvailableLicenseTypes isn't virtual. I'm a little surprised at the error message, though.
I've tried to reproduce, but had to trim things down quite a bit and fill in missing code, and ended up getting
The current proxy generator can not intercept the specified method for the following reason:
- Non virtual methods can not be intercepted.
Are you able to include more information, starting with the full error, including stack trace?
var nmsFakeHelper = A.Fake<NMCHelperFunctions>();
A.CallTo(() => nmsFakeHelper.GetAvailableLicenseTypes(fakeHttpSession, foundLicense, true)).Returns(foundLicensTypes);
These two lines are your issue.
The first line declares nmsFakeHelper as a fake of concrete type NMCHelperFunctions.
The second line then defines the behaviour of the fake when it's GetAvailableLicenseTypes method is called.
In the background, FakeItEasy decides what type of fake it should use (mock, stub, etc.). If the type you are asking a fake of is concrete you get a stub. However, if you want to be able to define behaviour (define return values or validate that methods were called etc.) you need a mock instead of a stub.
To get FakeItEasy to decide to return a mock instead of a stub, you need to give it an interface type instead. This is because a mock needs to be able to intercept the method calls but in .NET, methods can only be intercepted if they are virtual calls. This happens when the type you are using is an interface, but cannot happen when the type you are using is a concrete type.
So to get around this problem, you should add an interface to the NMCHelperFunctions type that includes (at the very least) the GetAvailableLicenseTypes method (as well as any other methods you may).
This means that your first line will change to the following (assuming you name your interface iNMCHelperFunctions):
var nmsFakeHelper = A.Fake<iNMCHelperFunctions>();
Your second line would remain unchanged, and your test code should now work.
You may have to refactor your application code to use the interface type instead of the concrete type. There is some benefit from doing this because it allows your components to be swappable so it's easier to add or change behaviour in the future by writing a new class that adheres to the same interface and switching to that.

REALBasic/Xojo NilObjectException When Calling Class Method From Property

I'm writing a console application used for UDP-based chat.
I have a class called App whose Super is ConsoleApplication (the "main" class) and a UDPInterface class whose Super is EasyUDPSocket. In the App class, there is a property called UDP whose type is UDPInterface (UDP As UDPInterface). In the Run event handler, there is this code:
StdOut.WriteLine(UDP.GetIP)
UDPInterface's method GetIP consists of the following code (return type is String):
return LocalAddress
LocalAddress is an EasyUDPSocket method that simply retrieves the internal IP.
The problem I'm having is that when I call UDP.GetIP, the program returns a NilObjectException. I need to use the UDPInterface class as a property so its properties work the same across all the methods inside App.
Objects must be instantiated using the New keyword prior to use. An object which hasn't been instantiated will always be Nil, and using a Nil object will always raise a NilObjectException:
UDP = New UDPInterface
StdOut.WriteLine(UDP.GetIP)

SQL User-Defined Functions in Linq to Entities

I am trying to call a user defined sql function in my linq statement using entity framework. The function is called GetXml, and takes 2 strings called "data" and "path" and returns a string. My Data Model is called XmlDataModel. I included the function definition in the edmx file as so:
<Function Name="GetXml" ReturnType="varchar(max)" Schema="dbo">
<Parameter Name="path" Type="varchar(max)" Mode="In" />
<Parameter Name="data" Type="varchar(max)" Mode="In" />
</Function>
I have the following declaration of the method in my code:
[EdmFunction("XmlDataModel.Store", "GetXml")]
public string GetXml(string path, string data)
{
throw new NotSupportedException("This method can only be used in a LINQ-toEntities query");
}
And the following linq statement:
var test = from e in this.ObjectContext.Events
where GetXml("a", "b") == "test" select e.EventSpecificData;
My problem is that when I attempt to view the result set, I get the following message:
The specified method 'System.String GetXml(System.String,
System.String)' on the type 'RIAServicesLibrary1.Web.XmlDomainService'
cannot be translated into a LINQ to Entities store expression because
the instance over which it is invoked is not the ObjectContext over
which the query in which it is used is evaluated.
It seems to be recognizing that I have the method defined, because when I take out the [EdmFunction] tag I get a different message. Any ideas?

Nhibernate lazy loading a set not working

I'm using nhibernate2.1 as part of spring.net 1.3. I have the following declaration as part of my mapping. My understanding is that this object should not load unless the getter is called. I have a break point set on the setter and also dump all nhibernate SQL statements to the logger. In part of my testing, I've actually created a brand new child object and a brand new property on my original object (hence the "2" on the names) so I'm positive that property is not being accessed anywhere. Despite this, as soon as my parent object loads, I can verify that this property is loaded. So...what am I missing here?
<set name="UserCustomer2" lazy="true">
<key column="[FK_USERS]" />
<one-to-many class="UserCustomer2" />
</set>
#A: here is my property:
private ICollection<UserCustomer2> _UserCustomer2 = new HashSet<UserCustomer2>();
public virtual ICollection<UserCustomer2> UserCustomer2
{
get { return _UserCustomer2; }
set { this._UserCustomer2 = value; }
}
and here is how I request the parent object:
IQuery query = dao.GetQuery("FROM UserImpl u WHERE u.UserName = :username AND u.Password = :password");
query.SetParameter("username", username);
query.SetParameter("password", password);
IList users = query.List();
#dotjoe, you led me down the right path. I tested out quite a few scenarios and based on breakpoints and the logged SQL statements I've determined that setting breakpoints does NOT trigger the lazy load. However, when you hover over the property to inspect it while in debug mode, it DOES in fact hydrate the object. I guess that sort of makes sense but I was assuming when I inspected the object, I would just see a proxy object instead of the fully hydrated object. I'm surprised that a debug mode action would trigger the lazy load -- I assumed that would only be triggered from actual application code. The other thing I'm curious about is if the setter is ALWAYS called and just passed a proxy object or if it was only called BECAUSE I had put a breakpoint in the setter. I would assume the former but so far my assumptions have been wrong. If anyone can provide some insights, I'm very curious how this actually works behind the scenes.

Defining and executing simple AppleScript commands in a Cocoa app

I'm trying to add some scripting functionality to a Cocoa app that I've written. I've created an sdef (Scripting Definition File) for my project. So far I have been successful in accessing object children (elements) with AppleScript but I cannot for the life of me figure out how to call methods (commands).
Here is my sdef file.
<suite name="mySuite" code="mSUI" description="My Application Suite">
<class name="application" code="capp" description="Top level scripting object.">
<cocoa class="NSApplication"/>
<!-- I can access these elements fine -->
<element description="Test children." type="child" access="r">
<cocoa key="myChildren"/>
</element>
<!-- Cannot seem to call this method :( -->
<responds-to command="testmethod">
<cocoa method="exposedMethod:"/>
</responds-to>
</class>
<class name="child" code="cHIL" description="A Child." plural="children">
<cocoa class="Child"/>
<property name="name" code="pnam" description="The child name." type="text" access="r">
<cocoa key="name"/>
</property>
</class>
<command name="testmethod" code="tEST" description="Execute the test method" />
</suite>
Here are my controller class implementations (this is the delegate of my application)
MyController.h
#import <Cocoa/Cocoa.h>
#interface MyController : NSObject {
NSMutableArray* myChildren;
}
// Some Methods
#end
MyController+Scripting.m
#import "MyController+Scripting.h"
#implementation MyController (Scripting)
// This works when I'm accessing the myChildren
- (BOOL)application:(NSApplication*)sender delegateHandlesKey:(NSString*)key {
NSLog(#"Key = %#", key);
return ([key isEqualToString:#"myChildren"]);
}
// This does NOT work...
- (void)exposedMethod:(NSScriptCommand*)command {
NSLog(#"Invoked Test Script Method %#", [command description]);
}
#end
Lastly, the AppleScript I am trying is:
tell application "MyApplication"
testmethod
end tell
which responds with "AppleScript Error - The variable testmethod is not defined."
Any ideas what I'm doing wrong here? I feel like I'm missing something simple but my Googling doesn't seem to be turning up anything helpful.
Things look mostly right, but the code for the <command/> should be a two-part code (eight characters) and not four.
I just posted a detailed solution on how to add a command with argument here: https://stackoverflow.com/a/10773994/388412
In short: I think you should subclass NSScriptCommand and override -(void)performDefaultImplementation rather than exposing a method in your controller. At least that's what I distilled from the docs:
"This command is a subclass of NSScriptCommand, containing one method, performDefaultImplementation. That method overrides the version in NSScriptCommand"
… and it works fine for me, see my linked answer for details.
(I've actually never added scriptability to a Cocoa app, so take my stab in the dark with a grain of salt.)
The first thing I would guess is that exposedMethod: takes a parameter, but I don't see where one might be specified in your sdef or AppleScript. In fact, it looks like AppleScript is treating testmethod as a variable, not a command. (Maybe it should be something like "testmethod with ..." instead?) You may need to define a <parameter> or <direct-parameter> element for the command in the sdef.
Also, wouldn't you need an object to call the method on? Since your controller is the application delegate, I'm not sure of the intricacies there, but might AppleScript try to invoke testMethod: on NSApplication instead of your delegate?
I'm guessing you've looked at Apple's sample code and other resources, but if not, here are a few links that may help:
Introduction to Cocoa Scripting Guide
TechNote 2106: Scripting Interface Guidelines
http://developer.apple.com/samplecode/SimpleScriptingObjects/
http://developer.apple.com/samplecode/SimpleScriptingPlugin/
http://www.shadowlab.org/softwares/SdefEditor/sdef-format.html
Good luck!