WCat throwing error from ubr file generated from WCat Scenario Creator - iis

I used the WCat Scenario Creator (http://fiddler2wcat.codeplex.com/) to generate the scripts of many requests through a website.
I had to add the "port:8888;" to every request. Then, after the "All clients connected, Test beginning." response, the test produced this error:
Invalid code received.
Error accepting remote connection.
I knew the first two requests worked so it was an issue with what was wrong with the next, 3rd, request.
The request looked like
request {
id = "3";
url = "/Content/Telerik-Kendo/textures/highlight.png";
verb = GET;
cookies = True;
secure = False;
statuscode = 304;
setheader {
name = "Accept";
value = "image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5";
}
setheader {
name = "Referer";
value = "http://server.compute-1.amazonaws.com:8888/Home/Winpoints/?sessionid=502hhfoij5ef4jedzouxz02z&low=0&high=150&companyid=3&verticalmarketid=8";
}
setheader {
name = "Accept-Language";
value = "en-US";
}
setheader {
name = "User-Agent";
value = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
}
setheader {
name = "Accept-Encoding";
value = "gzip, deflate";
}
setheader {
name = "Host";
value = "server.compute-1.amazonaws.com:8888";
}
setheader {
name = "If-Modified-Since";
value = "Thu, 27 Sep 2012 05:47:46 GMT";
}
setheader {
name = "If-None-Match";
value = ""0ed9e9e739ccd1:0"";
}
setheader {
name = "Connection";
value = "Keep-Alive";
}
setheader {
name = "Cookie";
value = "ASP.NET_SessionId=502hhfoij5ef4jedzouxz02z";
}
}

The answer, at least for this problem was the double quotes around the value of the "If-None-Match" header.
setheader {
name = "If-None-Match";
value = ""0ed9e9e739ccd1:0"";
}
Changing this to have 1 opening and closing double quote fixed it.
setheader {
name = "If-None-Match";
value = "0ed9e9e739ccd1:0";
}

Related

how to use basic authentication on azure functions ISOLATED?

how do i get the user and password informed in basic authentication in azure functions ISOLATED?
exemple, using the app SOAPUI to make a call to the function:
[https://i.imgur.com/3u7eymT.png]
how do i get in the function this USER and his password ?
[Function("Function1")]
public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
response.WriteString("Welcome to Azure Functions!");
return response;
}
i also have a middleware how i get this info in him too?
public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
{
i tried to search in the header, or the identities but i can't find this info/login and password
For Basic Authentication we need to change the open API security property values as below
[OpenApiSecurity("basic_auth", SecuritySchemeType.Http, Scheme = OpenApiSecuritySchemeType.Basic)]
Below is the screenshot of SoapUI
Authorization header need to be added in SoapUI as shown below
Code In Function
var headers = req.Headers["Authorization"];
if (ValidateToken(headers))
{
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name) ? "Pass a name in the query string" : $"{name}";
return new OkObjectResult(responseMessage);
}
Validation Code part
string encode_Credentials = header.Substring("Basic ".Length).Trim();
Encoding encode = Encoding.GetEncoding("iso-8859-1");
string credentials = encode.GetString(Convert.FromBase64String(encode_Credentials));
int seperatorIndex = credentials.IndexOf(':');
var username = credentials.Substring(0, seperatorIndex);
var password = credentials.Substring(seperatorIndex + 1);
if (username is "Rajesh" && password is "1142") return true;
else return false;

How add some content to Mockito mocked Pageable class?

I want testing pagination.
I want add some fake content to my Page mocked class.
How can I?
This is my test (refactoring it from a previous test), I'm using Junit5 and of course I get that No valut at JSON path $.content.lenght() and so on (of course, Page is empty):
/**
* index
*/
#WithMockUser("username")
#Test
void testCanIndex() throws Exception {
var transaction01 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(1L,
new BigDecimal(99.99), "First Transaction");
var transaction02 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(2L,
new BigDecimal(150.00), "Second Transaction");
var result = new ArrayList<BankAccountTransactionsEntity>();
result.add(transaction01);
result.add(transaction02);
Page<BankAccountTransactionsEntity> items = mock(Page.class);
when(bankAccountTransactionsService.index(0, 1, "id", "desc")).thenReturn(items);
mvc.perform(get("/api/v1/bank-account-transactions/")).andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()", is(2))).andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$.content[1].id", is(2))).andExpect(jsonPath("$[0].amount", is(new BigDecimal(99.99))))
.andExpect(jsonPath("$.content[1].amount", is(150)))
.andExpect(jsonPath("$.content[0].purpose", is("First Transaction")))
.andExpect(jsonPath("$.content[1].purpose", is("Second Transaction")))
.andExpect(jsonPath("$.content[0]", Matchers.hasKey("transactionDate")))
.andExpect(jsonPath("$.content[1]", Matchers.hasKey("transactionDate")));
}
Edit
I made a change, calling directly a PageImpl
#Test
void testCanIndex() throws Exception {
var transaction01 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(1L,
new BigDecimal(99.99), "First Transaction");
var transaction02 = BankAccountTransactionsControllerTest.validBankAccountTransactionsEntity(2L,
new BigDecimal(150.00), "Second Transaction");
var result = new ArrayList<BankAccountTransactionsEntity>();
result.add(transaction01);
result.add(transaction02);
Page<BankAccountTransactionsEntity> items = new PageImpl<>(result);
when(bankAccountTransactionsService.index(0, 1, "id", "desc")).thenReturn(items);
mvc.perform(get("/api/v1/bank-account-transactions/")).andExpect(status().isOk())
.andExpect(jsonPath("$.content.length()", is(2)));
}
But body returned is empty
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/v1/bank-account-transactions/
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.bitbank.controllers.BankAccountTransactionsController
Method = com.bitbank.controllers.BankAccountTransactionsController#index(Integer, Integer, String, String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

Await for ChangeResourceRecordSetsAsync hangs forever when trying to create Route53 DNS record

I am trying to create a TXT record in AWS Route53, but while awaiting the call, it will never complete.
The record is not being created in the hosted zone. The account has the correct permissions which I tested using the AWS CLI.
I am able to list hosted zones as also shown in the code below.
public static async Task CreateRecordAsync()
{
var route53Client = new AmazonRoute53Client("<myAccessKey>", "<mySecretKey>", RegionEndpoint.EUCentral1);
var test = new ListHostedZonesByNameRequest();
var testResponse = route53Client.ListHostedZonesByNameAsync(test);
foreach (var zone in testResponse.Result.HostedZones)
{
Console.WriteLine($"{zone.Name}{zone.Id}");
}
var response = await route53Client.ChangeResourceRecordSetsAsync(new ChangeResourceRecordSetsRequest
{
ChangeBatch = new ChangeBatch
{
Changes = new List<Change> {
new Change {
Action = "CREATE",
ResourceRecordSet = new ResourceRecordSet {
Name = "my.domain.net",
Type = "TXT",
TTL = 60,
ResourceRecords = new List<ResourceRecord>
{
new ResourceRecord
{
Value = "test txt value"
}
}
}
}
},
Comment = "Test Entry"
},
HostedZoneId = "Z2Q***********"
});
}
The problem was that the TXT record had to be enclosed in double quotes. I just had to catch the correct exception.
try
{
....
ChangeResourceRecordSetsResponse recordsetResponse =
await route53Client.ChangeResourceRecordSetsAsync(recordsetRequest);
....
}
catch (InvalidChangeBatchException ex)
{
Console.WriteLine(ex);
}
Which means that I should have constructed my record like this using.
ResourceRecordSet recordSet = new ResourceRecordSet
{
Name = chosenDomain,
TTL = 60,
Type = RRType.TXT,
ResourceRecords = new List<ResourceRecord>
{
new ResourceRecord
{
Value = "\"This is my test txt record\""
}
}
};

Gaelyk: returned truncated JSON

I am "piping" a json feed (in some cases quite big) that is returned from an external service, to hide an access api-key to the client (the access key is the only available authentication system for that service).
I am using Gaelyk and I wrote this groovlet:
try {
feed(params.topic)
} catch(Exception e) {
redirect "/failure"
}
def feed(topic) {
URL url = new URL("https://somewhere.com/$topic/<apikey>/feed")
def restResponse = url.get()
if (restResponse.responseCode == 200) {
response.contentType = 'application/json'
out << restResponse.text
}
}
The only problem is that the "restResponse" is very big and the value returned by the groovlet is truncated. So I will get back a json like this:
[{"item":....},{"item":....},{"item":....},{"ite
How can I return the complete json without any truncation?
Well I found the solution and the problem was at the beginning (the URL content must be read as stream). So the content truncated it was not the output but the input:
def feed(topic) {
URL url = "https://somewhere.com/$topic/<apikey>/feed".toURL()
def restResponse = url.get()
if (restResponse.responseCode == 200) {
response.contentType = 'application/json'
StringBuffer sb = new StringBuffer()
url.eachLine {
sb << it
}
out << sb.toString()
}
}

How to base.RequestContext.ToOptimizedResultUsingCache() return string for Accept-Encoding: deflate?

I do have following code...
and Accept-Encoding: deflate
public object Get(DTOs.Product request)
{
...
var sCache = base.RequestContext.ToOptimizedResultUsingCache(
this.CacheClient, cacheKey, expireInTimespan, () =>
{
// Business layer returns resultant dataset as XmlDocument
...
return sXML.InnerXml;
});
//returns ServiceStack.Common.Web.HttpResult;
return GenerateResp(sCache, base.Request.Headers["Accept"]);
}
Issue is base.RequestContext.ToOptimizedResultUsingCache returns ServiceStack.Common.Web.CompressedResult even though I am returning XML. I understand that Accept-Encoding: deflate causes RequestContext.CompressionType to deflate.
Above code works fine, when there is no Accept-Encoding (through fiddler test).
But, if the request comes from a browser, it would come as a Compressed, in this case how can I get sCache as string to pass it to GenerateResp?
Thanks for your help.
I am able to resolve the issue by modifying code to...
public object Get(DTOs.Product request)
{
...
var objCache = base.RequestContext.ToOptimizedResultUsingCache(
this.CacheClient, cacheKey, expireInTimespan, () =>
{
// Business layer returns resultant dataset as XmlDocument
...
return sXML.InnerXml;
});
string compressionType = base.RequestContext.CompressionType;
bool doCompression = compressionType != null;
string transformed = "";
if (doCompression)
{
byte[] bCache = ((ServiceStack.Common.Web.CompressedResult)(objCache)).Contents;
transformed = bCache.Decompress(base.RequestContext.CompressionType);
}
else
{
transformed = (string)objCache;
}
//returns ServiceStack.Common.Web.HttpResult;
//In GenerateResp, If compressionType contains "gzip" or "deflate", I compress back the response to respective compression, and add respective Content-Encoding to the header.
return GenerateResp(transformed, base.Request.Headers["Accept"], compressionType);
}
Thank you.

Resources