linqpad won't show exceptions? - linqpad

I'm using the latest linqpad version : (under 4.5.1)
But when I run this code :
List<int> list = new List<int>() { 1, 2, 3 };
list.ForEach(i =>
{
if (i < 3) { list.Add(i+1); }
});
I don't get an exception where if I run it under VS-2013, I do get an exception.
Question.
It is not throwing an exception. Any reason why? How can I fix it to throw an exception?

Related

How to deal with swagger against route overrides?

I'm trying to embed Swagger in my Asp Core (.Net 6) project where there are some cases of route overriding. However, the issue I'm facing can be reproduced even on the following case.
Consider a minimal Asp Core (.Net 6) app. For instance, just like the one used by Swashbuckle as test: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites/MinimalApp
Now, consider two controllers in the same app:
[ApiController]
[Route("/api")]
public class MyFallbackController : ControllerBase
{
[HttpGet("values", Order = 1)]
public ActionResult<object> GetValues()
{
return new[] { 1, 2, 3 };
}
}
[ApiController]
[Route("/api")]
public class MyOverrideController : ControllerBase
{
[HttpGet("values", Order = 0)]
public ActionResult<object> GetValues()
{
return new[] { 4, 5, 6 };
}
}
Notice that the routes are exactly the same, but only the first (Order = 0) will be considered.
If I run the app and navigate to:
https://localhost:7263/api/values
the response gives the expected result: [4, 5, 6]
However, when I try to access the Swagger section, it does not work because (apparently) it figures as a collision the controller pair:
An unhandled exception occurred while processing the request.
SwaggerGeneratorException: Conflicting method/path combination "GET
api/values" for actions -
WebApplication2.MyFallbackController.GetValues
(WebApplication2),WebApplication2.MyOverrideController.GetValues
(WebApplication2). Actions require a unique method/path combination
for Swagger/OpenAPI 3.0. Use ConflictingActionsResolver as a
workaround
Is there any way to get rid of that problem?
Found it.
The trick is in the SwaggerGen configuration, as the exception message suggests, by the way.
using Microsoft.AspNetCore.Mvc.ApiExplorer;
services.AddSwaggerGen(c =>
{
c.ResolveConflictingActions(apiDescriptions =>
{
int best_order = int.MaxValue;
ApiDescription? best_descr = null;
foreach (var curr_descr in apiDescriptions)
{
int curr_order = curr_descr.ActionDescriptor.AttributeRouteInfo?.Order ?? 0;
if (curr_order < best_order)
{
best_descr = curr_descr;
}
}
return best_descr;
});
});
Basically, the above function selects only the ApiDescription with the lowest order among the duplicates.
That is my naive yet effective solution. For instance, I don't know if the input collection is given already sorted by order. In that case, the code could be even simpler.

mockk every {}.throws() Exception fails test

I need to verify that a certain call is not made, when a previous method call throws an Exception.
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
sut.live()
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
Problem with this code, it fails because of the Exception thrown and not because of the failed verification.
I understand that your WHEN block will always throw an exception.
In that case you have multiple options from my point of view:
Simple plain Kotlin. Wrap the WHEN block with a try-catch block, e.g. like this:
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
var exceptionThrown: Boolean = false
try {
sut.live()
} catch(exception: NotHungryException) {
// Maybe put some assertions on the exception here.
exceptionThrown = true
}
assertTrue(exceptionThrown)
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
For a bit nicer code, you can use JUnit5 API's Assertions. assertThrows will expect an exception being thrown by a specific piece of code. It will fail the test, if no exception is thrown. Also it will return the thrown exception, for you to inspect it.
import org.junit.jupiter.api.Assertions
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
val exception = Assertions.assertThrows(NotHungryException::class.java) { sut.live() }
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
If you're using Kotest you can use the shouldThrow assertion. Which also allows you to retrieve the thrown exception and validate its type.
import io.kotest.assertions.throwables.shouldThrow
// GIVEN
every { relaxedMock.eats() }.throws(NotHungryException())
// WHEN
val exception = shouldThrow<NotHungryException> { sut.live() }
// THEN
verify (exactly = 0) { relaxedMock2.sleeps() }
I had similar issue and found that my method is not surrounded by try catch. This mean the method will always throw exception.
Test
The unit test to verify the result when the following method is called while stubbing it with predefine Exception
#Test
fun returnSearchError() {
every { searchService.search(query) }.throws(BadSearchException())
val result = searchRepository.search(query)
assertEquals(SearchStates.SearchError, result)
}
Faulty code
fun search(query: String): SearchStates {
val result = searchService.search(query) // No try catch for the thrown exception
return try {
SearchStates.MatchingResult(result)
} catch (badSearchException: BadSearchException) {
SearchStates.SearchError
}
}
Refactored it to
fun search(query: String): SearchStates {
return try {
val result = searchService.search(query)
SearchStates.MatchingResult(result)
} catch (badSearchException: BadSearchException) {
SearchStates.SearchError
}
}

Can't return array<int^, 2>^ c++/cli

I am trying to use this method:
array<int^,2>^ Function1()
{
return gcnew array<int^,2>{ { 1 }, { 2 }};
}
by typing:
auto x = Function1();
but I get an error:
Exception thrown at 0x73572A55 (clr.dll) in Project1.exe: 0xC0000005: Access violation writing location 0x00000834.
How to solve this problem if I want to keep the returning type?
Thanks!
int is not a reference type, and should not be used with ^.
If you remove the ^ from int^, this code does run:
array<int, 2>^ Function1()
{
return gcnew array<int, 2>{ { 1 }, { 2 } };
}
How to solve this problem if I want to keep the returning type?
This return type is improper. There's no way to represent int^ in C#, and probably not in other .Net languages either. Having a variable of type int^ is a performance hit for each access of the integer, and I believe it's more work for the garbage collector as well.
The proper fix is to change int^ to int everywhere.
Now, that said, I cannot reproduce the error you're getting. Perhaps your error is elsewhere.
array<int^,2>^ Function1()
{
return gcnew array<int^,2>{ { 1 }, { 2 }};
}
int main(array<System::String^>^ args)
{
auto x = Function1();
Debug::WriteLine(x[0,0]);
return 0;
}
Result:
1

WCF Service: Unexpected character encountered while parsing value

I am trying to programm a test app with a client/server principle. The server is a simple WCF service which works (CRUD -> Create, Read, Udate, Delete) with an entity model.
On the client side I have this function which passes the data (in json format) to the WCF service:
save: function (w) {
var object= [{
"id": w.id,
"date": w.date,
"content": w.content
}];
$.getJSON("http://localhost:49817/Service.svc/SaveObject/" + object).done(function (data) {
App.content.setObject(data);
});
},
And here is the WCF service:
public string SaveObject(string object)
{
try
{
CustomClass myCustom= (CustomClass) JsonConvert.DeserializeObject(object, typeof (JObject));
using (AppEntities entities = new AppEntities())
{
CustomClass newCustom = new CustomClass();
newCustom.id = newCustom.id;
newCustom.date= myCustom.date;
newCustom.content = myCustom.content;
entities.Wertungen.Add(newWertung);
entities.SaveChanges();
return null;
}
}
catch(Exception e)
{
throw new FaultException("An error occured during saving the new object");
}
}
My problem is that always in this part here
CustomClass myCustom= (CustomClass) JsonConvert.DeserializeObject(object, typeof (JObject));
an error occured: Unexpected character encountered while parsing value.
I don't know the error. I have tried now since a few days and haven't a solution till today.
I hope you can help me.
Thanks.

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.