Rhino Mocks: Fill array argument in stub without "ref" keyword - rhino-mocks

I have a problem filling an array argument without the ref keyword.
For this signature:
int ReceiveData(ref byte[] data)
this works:
byte[] dataParameter = new byte[8];
byte[] testData = new byte[] { 1, 2, 3, 4 };
this.mockObject.Stub(t => t.ReceiveData(ref dataParameter)).OutRef(testData).Return(4);
After calling "ReceiveData" the "data" argument has the value { 1, 2, 3, 4 }.
What should I do to fill the data argument for this signature:
int ReceiveData(byte[] data)
OutRef() doesn't work for this. Any idea?
Thanks...

I was just having a similar problem and found my solution with the 'Callback' method. In my case, the input buffer argument is not declared 'ref', so might not be quite right for you, but I think it should work.
For example;
mockObject.Expect(x => x.ReceiveData(Arg<byte[]>.Is.NotNull)).Callback((byte[] buffer) =>
{
Array.Copy(outBytes, 0, buffer, 0, outBytes.Length);
return true;
}).Return(10); // return some number of bytes received, and set the bytes in the callback

Related

How to make api call of string in flutter?

I am learning Flutter. This is the string that I need to call and I don't know how to call this type of string.
{
"Info":[
{
"c_type_id":"1",
"cleaning type":"Washroom Cleaning"
},
{
"c_type_id":"2",
"cleaning type":"Garden\/Lawn Cleaning"
}
]
}
My code
class Album {
final String title;
Album({
this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
title: json['title'],
);
}
}
As I am following my code like this https://flutter.dev/docs/cookbook/networking/fetch-data
and got this error "A non-null String must be provided to a Text widget." because they are following this type of string and my string type is different. Help!
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
}
Your given data (API response) seems to have a list of maps, so you should get the data first (use async function):
var response = await http.get("Your Url")
then you should extract the given map list as follow:
var temp = json.decode(response);
List<dynamic> result = temp['Info']); // it is the described list
now, you can use your data (extract each parameter):
String c_type_id = result[0]['c_type_id'];
// and so on...
Your question is not clear at all but I can show you an example how to reach an element in a json.
Your json consists a list that contains string keys. To reach first element of list;
json["Info"][0]
Then pass the key you want to get its value;
json["Info"][0]["c_type_id"]
http_requests All type of http requests are mentioned in this post. If you have any further problem kindly make comment.

type 'String' is not a subtype of type 'Null' in get method flutter

I got this error: type 'String' is not a subtype of type 'Null' in get method flutter
this is the get api function that i use
Future<Stream<ServiceTypes>> getServiceTypesa() async {
final String url = 'https://test.com';
final client = new http.Client();
final streamedRest = await client.send(
http.Request('get', Uri.parse(url))
);
return streamedRest.stream
.transform(utf8.decoder)
.transform(json.decoder)
.expand((data) => (data as List))
.map((data) => ServiceTypes.fromJson(data));
}
you can see here the function detect the data
i saw also this error
StateError (Bad state: Stream has already been listened to.)
and this error
this is my listen function
#override
void initState() {
_serviceTypes = new List<ServiceTypes>();
listenForServiceTypes();
super.initState();
}
void listenForServiceTypes() async {
setState(() {
this._show_serviceTypesProgress = true;
});
final Stream<ServiceTypes> stream = await getServiceTypesa();
stream.listen((ServiceTypes serviceTypes) =>
setState(() => _serviceTypes.add(serviceTypes)));
setState(() {
this._show_serviceTypesProgress = false;
});
print(_serviceTypes);
}
this is the model that i made
I don't know what is the problem because the print function return : []
When you create model, the image type value is null so, the model is create with Null type of image but when images are not null type from server then it gives you an error
type 'String' is not a subtype of type 'Null' in get method flutter
because your image type is String from server and you get value by Null Object, So use String type object for getting string value or images.
Use this
Class ServiceTypes{
String image;
instead of
Class ServiceTypes{
Null image;
As extra information, you can check the keys name. I faced the same problem just because I tried to fetch a key not found.
In the first time I wrote content instead of details and in my API I have details not content.
have a good day :)
The issue is clear, you define image type as Null then trying to pass string to it, try to change definition.. like so:
Class ServiceTypes{
int id;
String name;
String image;
...
use ? this for nullable key. For example :
final String? title;
final String? category;
here is the complete solution :
Is it possible to parse json in Flutter/Dart with missing attributes (keys of json data)?

DataProvider sequence in TestNG

Do we need to follow the same sequence in array object while using the dataObject
Eg: Code
#DataProvider(name = "test1")
public static Object[][] primeNumbers() {
return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}};
}
// This test will run 4 times since we have 5 parameters defined
#Test(dataProvider = "test1")
public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) {
System.out.println(inputNumber + " " + expectedResult);
Assert.assertEquals(expectedResult,
primeNumberChecker.validate(inputNumber));
}
In DataProvider Integer and Boolean are used and same sequence is used in testPrimeNumberChecker. Can I use only Boolean record in any of the function if I need.
Type, number and order/sequence of input parameters of #Test method must be same as passed by #DataProvider method.
Do we need to follow the same sequence in array object while using the dataObject
Here I assume by using you mean to passing the arguments in the #Test method. Answer of this is - Yes we need to follow the same sequence in array object while using the dataObject.
Example:
#Test(dataProvider = "test1")
public void testPrimeNumberChecker(Boolean expectedResult, Integer inputNumber) {
// your test method stuff
}
If you do not follow this you will get below exception:
java.lang.IllegalArgumentException: argument type mismatch
Can I use only Boolean record in any of the function if I need.
Here also I am assuming by use you mean to passing the arguments in the #Test method. Answer is - No, number of arguments matters.
Example:
#Test(dataProvider = "test1")
public void testPrimeNumberChecker(Boolean expectedResult) {
// your test method stuff
}
So if your #Test method has less or more number of input parameter(s) what your #DataProvider method passes, you will get below exception:
org.testng.TestNGException:
The data provider is trying to pass 2 parameters but the method yourpackage.YourTestClass#testPrimeNumberChecker takes 1

GWT-RPC Unexplained 500status error when retrieving an ArrayList

I am developing a GWT client-server webapp using GWT-RPC; mostly it seems to work fine but I am stuck with an error retrieving an ArrayList of an IsSerializable type.
Here is the code for the server-side method:
public GWTInvoiceList listInvoices(String enterpriseID, int selection) {
try{
logger.log("ISI getting a listy of invoices "+selection);
PlataccsUser pxuser = (PlataccsUser) getSession().getAttribute(PlataccsConstants.USER);
Enterprise enterprise= pxuser.getEnterprise(enterpriseID);
Clerk clerk= pxuser.getClerk(enterprise);
int i=0;
List<Invoice> invoices =Invoice.getInvoices(enterprise, clerk, selection);
GWTInvoiceList gwinvoices = new GWTInvoiceList();
Iterator<Invoice> it = invoices.iterator();
while (it.hasNext()){
Invoice invoice = it.next();
logger.log("ISI-listInvoices converting invoice "+invoice.getSystemInvoiceNumber());
gwinvoices.add(convert(invoice, clerk));
}
logger.log("ISI-lI, the invoice list is now ready and it lists "+gwinvoices.size()+" invoices");
return gwinvoices;
}catch(Exception px){
logger.log("ISI propblem getting invoice list", px);
return null;
}
}
This code executes without throwing any exception. The GWTInvoiceList return type is a simple wrapper for ArrayList and the GWTInvoice type is known to serialize successfully in other calls. The client side code is:
public InvoiceList(PlataxTabPanel parent, GWTEnterprise gwtEnterprise, int list_selection_type) {
super(parent, gwtEnterprise.getName());
topLabel.setText("List of Invoices");
subHeader.setText("blah blah");
invoiceService.listInvoices(gwtEnterprise.getEnterpriseID(), list_selection_type, invoiceListCallBack);
//table headers:
table.setWidget(0, 0, new ColumnHeaderLabel(LabelText.LIST_INVOICE_NUMBER_HEADER));
table.setWidget(0, 1, new ColumnHeaderLabel(LabelText.LIST_INVOICE_CUSTOMER_HEADER));
table.setWidget(0, 2, new ColumnHeaderLabel(LabelText.LIST_INVOICE_VALUE_DATE_HEADER));
table.setWidget(0, 3, new ColumnHeaderLabel(LabelText.LIST_INVOICE_DUE_DATE_HEADER));
table.setWidget(0, 4, new ColumnHeaderLabel(LabelText.LIST_INVOICE_STATUS_HEADER));
table.setWidget(0, 5, new MoneyColumnHeaderLabel(LabelText.LIST_INVOICE_NET_HEADER));
table.setWidget(0, 6, new MoneyColumnHeaderLabel(LabelText.LIST_INVOICE_TAX_HEADER));
table.setWidget(0, 7, new MoneyColumnHeaderLabel(LabelText.LIST_INVOICE_TOTAL_HEADER));
}
final AsyncCallback<GWTInvoiceList> invoiceListCallBack= new AsyncCallback<GWTInvoiceList>(){
#Override
public void onSuccess(GWTInvoiceList invoices){
Iterator<GWTInvoice> gwit = invoices.iterator();
int row = 1;
while(gwit.hasNext()){
GWTInvoice gwinvoice = gwit.next();
table.setWidget(row, 0, new Label(gwinvoice.getUserno()));
table.setWidget(row, 1, new Label(gwinvoice.getCustomer().getName()));
table.setWidget(row, 2, new Label(DateTimeFormat.getFormat(DateFormats.SHORT_DATE_FORMAT).format(gwinvoice.getValueDate())));
table.setWidget(row, 3, new Label(DateTimeFormat.getFormat(DateFormats.SHORT_DATE_FORMAT).format(gwinvoice.getDueDate())));
table.setWidget(row, 4, new Label(gwinvoice.getStatus()));
table.setWidget(row, 5, new MoneyLabel(gwinvoice.getNet()));
table.setWidget(row, 6, new MoneyLabel(gwinvoice.getTax()));
table.setWidget(row, 7, new MoneyLabel(gwinvoice.getGross()));
row++;
}
}
#Override
public void onFailure(Throwable cause) {
//Debugging code
StackTraceElement[] st = cause.getStackTrace();
String error = "get invoice list failed\n";
error = error+cause.getClass().getName()+"\n";
if (cause instanceof StatusCodeException){
StatusCodeException sce=(StatusCodeException) cause;
int sc = sce.getStatusCode();
error=error+"Status Code:"+ sc+"\n";
}
for (int i=0; i<st.length; i++){
error = error + st[i].toString()+ "\n";
}
Window.alert(error);
}
};
The call always fails with a 500 status code and therefore triggers the OnFailure method of the AsyncCallback inner class.
I am somewhat at a loss to work out why because there is no server-side error.
The problem is one of serialization on the server side, but I can't see where it's coming from. I have overridden OnAfterResponseSerialized to probe things and it isn't called - (it is called by other methods in the same service implementation class, so the probe is working).
From the javadocs, processCall() should be throwing a SerializationException. I need to catch it and see what's going on.
What does the GWTInviceList code look like?
I'm guessing you don't have a no-parameter constructor for the GWTInvoiceList class.
This code:
/**
* catches the SerializationException for forensic examination.
*/
#Override
public String processCall(String payload) throws SerializationException{
try{
return super.processCall(payload);
}catch(SerializationException se){
logger.log("Xservlet serialisation excption", se);
throw se;
}
}
added to the service implementation class catches the SerializationException so I can trace the aberrant object.

Generate parameter list with userdefined types at runtime (using C#)

As part of my project, I am trying to build a web UI where user will select a method and pass the values. My program should be able to call the method dynamically and build a parameter list on runtime to pass it to the method.
I have created a comma separated list (string) of key and value pairs. This key/value pair is nothing but the parameter name and value of my method (methodname stored in a variable). Example: string params = "ID:123;Name:Garry;Address:addressObject;AddressLine:108 Plaza Lane;City:Avenel;State:NJ;Zip:07001;". Where ID and Name are simple string varaibles while Address is user defined type. What follows after Address i.e. AddressLine, City, State and Zip is elements of Address object. And my method definition is
public string GetInfo(string ID, string Name, Address addressObject)
{
//return something;
}
I am dynamically calling the method (GetInfo) that is stored in sMethodName variable using DynamicProxy like :
string sMethodName = "GetInfo";
object result = (object) proxy.CallMethod(sMethodName, arguments);
Challenge is how to pass the argument list dynamically? Till now I am just able to extract the values from the csv variable into NamedValueCollection. Here is the code:
public static void StoreParameterValues(string param)
{
nvc = new NameValueCollection();
param = param.TrimEnd(';');
string[] parameters = param.Split(new char[] { ';' });
foreach (string val in parameters)
{
string[] keyValue = val.Split(new char[] { ':' });
nvc.Add(keyValue[0], keyValue[1]);
}
}
..and here is the code that tries to build the parameter:
string methodName = "GetInfo";
DynamicProxyFactory factory = new DynamicProxyFactory("http://../myservice.svc");
string sContract = "";
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
sContract = endpoint.Contract.Name;
}
DynamicProxy proxy = factory.CreateProxy(sContract);
string[] values = null;
// Create the parameter list
object[] arguments = new object[nvc.Count];
int i = -1;
foreach (string key in nvc.Keys)
{
values = nvc.GetValues(key);
foreach (string value in values)
{
arguments[++i] = value;
}
}
object result = (object) proxy.CallMethod(methodName, arguments);
The above code works if I have simple primitive types but not sure how can I build the logic for any other userdefined types. How can I create a object dynamically of type stored in a variable? Not sure if I was able to put my question correctly. I hope so :)
Edit: 01/19/2011: Applied the suggestion from Chris - using Reflection instead of ComponentModel.
I have converted the code to make it more generic. This works now for all primitive and custom types (resursion). Code snippet below:
private object BuildParameterList(Type type)
{
object item = new object();
item = Activator.CreateInstance(type);
PropertyInfo[] propArray = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);
for (int i = 0; i < propArray.Length; i++)
{
PropertyInfo pi = (PropertyInfo)propArray[i];
////Check for custom type
if (IsCustomType(pi.PropertyType))
{
object item1 = BuildParameterList(pi.PropertyType);
pi.SetValue(item, item1, null);
}
else
{
if (property.ContainsKey(pi.Name))
{
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
}
}
}
return item;
}
But if one of the property is Color (I just tested with Color type, will fail with other system types aswell-i guess), then it fails at the following line. Not sure how to handle system types - Color or something similar.
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
Can you not find what types are expected by the method, by inspecting its ParameterInfos:
endpoint.Contract.ContractType.GetMethod(methodName).GetParameters();
and then instantiating the custom types using:
Activator.CreateInstance(parameterType);