DBSetup : SQL support - dbsetup

I am trying to use DBSetup for my testing. I was able to make it run with simple Inserts:
public static final Operation INSERT_CURRENCY_DATA =
Insert.into("CURRENCY")
.columns("ID", "CODE", "NAME", "DESCRIPTION")
.values(1, "EUR", "EUR", "EUR")
.values(2, "CZK", "CZK", "CZK")
.build();
But when one table has a foreign key in another table like the example below from the website:
Operation insertVendorsAndProducts =
sequenceOf(
insertInto("VENDOR")
.columns("ID", "CODE", "NAME")
.values(1L, "AMA", "AMAZON")
.build(),
insertInto("PRODUCT")
.columns("ID", "NAME", "VENDOR_ID")
.values(1L, "Kindle", "1L")
.build(),
sql("update VENDOR set FEATURED_PRODUCT_ID = 1 where ID = 1"));
I could not compile the code and getting
Syntax error on token ',',.expected in the .build(), line

Related

How to obtain virtual user id/details in gatling?

I am new to Gatling and Scala and I need your advice.
I would like to obtain load test for n-users. Each user have to send request for creating different accounts. This is obtained by sending json file with appropriate array of objects ('entries' in our case).
Each single user must send different login as our backend system is checking if username is unique. Somehow we have to be sure that gatling is sending different data for each virtual user and also for each entries as well.
We noticed that there us session element which represents virtual user's state. Problem is that code showed below will not work as Exec structure used with expression function does not send any request.
There is section that could work but I do not know how to determine third parameter to distinguish virtual user id. Please find below simple json file structure used for this test
{
"entries": [
{
"userName": "some user name",
"password": "some password"
}
}
and scala code with my comments
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class UserCreationTest extends Simulation {
val profilesNumber = 2
val virtualUsers = 2
val httpConf = http
.baseURL("some url")
.acceptHeader("application/json")
.basicAuth("username", "password")
// This method will multiply 'entries' section in JSON 'entriesNumber' times
def createJsonUserEntries(entriesNumber: Int, users: List[String], userId : Long): String = {
val header = """{"entries": ["""
val footer = """]}"""
val builder = StringBuilder.newBuilder
for (i <- 0 until entriesNumber) {
val userIndex = (userId.toInt - 1) * entriesNumber + i
val userName = users(userIndex).get
val apiString =
s"""{
"userName": "${userName}"
"password": "password"
}"""
builder.append(apiString)
if (i != entriesNumber) {
builder.append(",")
}
}
header + builder.toString() + footer
}
// We do have method for generating user names based on profilesNumber and virtualUsers variables
// but for sake of this example lets hardcode 4 (profilesNumber * virtualUsers) user names
val usersList = List("user-1", "user-2", "user-3", "user-4")
//This will throw exception as no request was send. According to documentation function block is used to debugging/editing session
val scn = scenario("Create WiFi User Profile")
.exec(session => {
http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, userslList, session.userId).toString
)
).asJSON
session})
// This exec block will send a request but I do not know how to determine third param that should be virtual user Id
// To run this section please comment previous whole scenario block
/*
val scn = scenario("")
.exec(http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, emailList, ???).toString
)
).asJSON
)
*/
setUp(scn.inject(atOnceUsers(virtualUsers)).protocols(httpConf))
}
Can you help me on that please? Is there any other way to do that in gatling? Thank you very much in advance
so you are trying to have each user have a unique userId?
you could create a feeder that does this
var userIdFeeder = (1 to 999999).toStream.map(i => Map("userId" -> i)).toIterator
val scn = scenario("")
.feed(userIdFeeder)
.exec(http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, emailList, "${userId}").toString
)
).asJSON
)

Send SqlQuery in Azure Function's DocumentDB Attribute

I have an Azure Function that uses the DocumentDB attribute to connect to Cosmos DB. I'm using the Azure Functions for Visual Studio 2017 tooling. Here is the simple Function
[FunctionName("DocumentDbGet")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get")]HttpRequestMessage req, TraceWriter log,
[DocumentDB("FunctionJunctionDemo", "Demo")]IEnumerable<DemoModel> items)
{
//Can perform operations on the "items" variable, which will be the result of the table/collection you specify
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
var item = items.Where(x => x.FirstName == name);
return req.CreateResponse(HttpStatusCode.OK);
}
I want to be able to pass a SqlQuery as one of the parameters of the DocumentDB attribute like so:
[FunctionName("DocumentDbGet")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get")]HttpRequestMessage req, TraceWriter log,
[DocumentDB("FunctionJunctionDemo", "Demo", SqlQuery = $"select * from c where c.Id = {Id}")]IEnumerable<DemoModel> items)
{
//Can perform operations on the "items" variable, which will be the result of the table/collection you specify
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
var item = items.Where(x => x.FirstName == name);
return req.CreateResponse(HttpStatusCode.OK);
}
I've only seen 1 example do this and reported it was supposedly working. https://github.com/Azure/Azure-Functions/issues/271
The "error" I receive is it doesn't recognize anything named SqlQuery as a possible parameter.
I have looked at the documentation for Azure Function Input bindings
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-documentdb#input-sample-with-multiple-documents which shows an output in the function.json file containing a sqlQuery attribute. How did that get in there?
If it isn't possible to pass in a SqlQuery in the DocumentDB attribute, what would be the best practice to filter the results up front to avoid returning an entire collection and then running it through a LINQ query?
You need to reference 1.1.0-beta version of Microsoft.Azure.WebJobs.Extensions.DocumentDB NuGet package (or later).
In that version SqlQuery is a valid parameter of DocumentDB attribute. You code compiles for me, if I remove $ sign before select string:
[DocumentDB("FunctionJunctionDemo", "Demo", SqlQuery = "select * from c where c.Id = {Id}")]
You don't need $ - it's used for string interpolation in C#, not something you want to do here.

Acumatica get Sales Order by Customer Order field

I am attempting to retrieve a single sales order based on the Customer Order field in Acumatica with the Contract Based API. See my code below, which I based off of code in the Contract Based Documentation (page 82).
public SalesOrder GetSalesOrder(string orderNumber)
{
var binding = new System.ServiceModel.BasicHttpBinding()
{
AllowCookies = true,
MaxReceivedMessageSize = 655360,
MaxBufferSize = 655360,
SendTimeout = new TimeSpan(0, 2, 0)
};
var soToBeFound = new SalesOrder()
{
OrderType = new StringValue { Value = "SO" },
CustomerOrder = new StringValue { Value = orderNumber }
};
var address = new System.ServiceModel.EndpointAddress(ConfigurationManager.AppSettings["AcumaticaUrl"]);
using (DefaultSoapClient client = new DefaultSoapClient(binding, address))
{
client.Login(_acumaticaUid, _acumaticaPwd, _acumaticaCompany, null, null);
var existingOrder = (SalesOrder)client.Get(soToBeFound);
client.Logout();
return existingOrder;
}
}
When I execute this code I get this exception:
The request channel timed out while waiting for a reply after
00:01:59.9880722. Increase the timeout value passed to the call to
Request or increase the SendTimeout value on the Binding. The time
allotted to this operation may have been a portion of a longer
timeout."
As you can see, I've already increased the timeout to 2 minutes, which seems like forever. Is the Acumatica API really just this slow? Or am I doing something wrong in code?
EDIT:
When I try to get by the "OrderNbr" field instead of "CustomerOrder" field, it works perfectly. Is getting by "CustomerOrder" not allowed in this way? If not, how can I use "CustomerOrder" in a get request?
When you do search via the Contract-Based API, it's required to assign instance of the [FieldType]Search type instead of [FieldType]Value to all fields used in search criteria (StringSearch must be used instead of StringValue in your case):
var soToBeFound = new SalesOrder()
{
OrderType = new StringSearch { Value = "SO" },
CustomerOrder = new StringSearch { Value = orderNumber }
};
Just to confirm, StringSearch is also used in the sample on page 82 from the Contract Based documentation.

Custom EF Code First Identity Generation

Using EntityFramework 5, I have a new database where I need to specify the identity seed on tables to be something other than "1".
With either the modelbuilder, migrations, or otherwise, is there a simple way to change the identity generation for tables to handle this?
At the moment, I'm looking at creating custom sql generated to call during migrations to modify this after the tables are created. A cleaner solution would be to get the CREATE TABLE correct in the first place.
unfortunately i haven't found a way to "add pre-query" before execute query batch
if anybody will find a way to do that - then before execute commit - we could execute sql:
"set identity_inster on"
after
"set identity_inster off"
which is more natural for t-sql
I am working with same problem, for now following plan a have:
initialize customized migration plan by:
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
Check that an entity has to be generated (class
MyInitConfiguration):
protected override void Seed(MyDbContext context)
{
var he = context.Set<MyEntity>();
if (!he.Any(h => h.Id == 0))
{
...place to add code...
Add entity (or several entities) in normal way, but "before execute commit - call external sql script:
he.Add(new MyEntity{ Id = -5, Alias = "system",Title = "System"});
he.Add(new MyEntity{ Id = -4, Alias = "system1",Title = "System1"});
he.Add(new MyEntity{ Id = -3, Alias = "system2",Title = "System2"});
context.Database.ExecuteSqlCommand(
string.Format("DBCC CHECKIDENT ('{2}', RESEED, {0});",-5,"MyTableName")
);
context.Commit();
or following extension i have prepared for DBContext:
public static void UpdateIdentity<T, TKey>(this MyDbContext context, Func<T> data, TKey staticPreviousId, string tableName,string columnName="id")
where T : MyEntity<TKey>
{
var r = data();
context.Database.ExecuteSqlCommand(string.Format("DBCC CHECKIDENT ('{2}', RESEED, {0});", staticPreviousId, r.Id, tableName, columnName));
context.Commit();
}
then just execute:
context.UpdateIdentity(() => myDataSet.Add(new MyEntity{ Id = -5, Alias = "system",Title = "System"}), -5, "myTableName");
context.UpdateIdentity(() => myDataSet.Add(new MyEntity{ Id = 81, Alias = "system",Title = "System"}), 80, "myTableName");

ReSharper chop if long not working

I have the following code that when I run autoformat in ReSharper doesn't not get changed.
I thought Chop if long would cause a chop to occur if the right margin is exceeded.
If I turn on Chop always I get this.
This works, but I would rather not chop short statements like the first, which is what I assume Chop if long means.
Ideas?
Here are my ReSharper settings.
Turning on wrap long lines makes things even worse.
UPDATE1:
Here is the email I sent to JetBrains support.
The believe the central issues I'm facing is I understand the "chop always" setting, but I do not understand "chop if long" or "simple wrap". I have not found any documentation on what these settings mean, so I'm going off what I believe should be happening.
I am setting the "Wrap object collection and initializer".
Chop Always:
cdata.GetByIdData = new Category {
Id = "123",
Name = "category"
};
vdata.GetByIdData = new Vendor {
Id = "456",
Name = "vendor"
};
adata.GetByIdData.Add(new Account {
Id = "789",
Name = "account",
Balance = 5000
});
svc.ExecuteRequest(new AccountTransactionService.Add {
Kind = AccountTransaction.KIND_DEBIT,
Source = "789",
Destination = "dst",
Date = new DateTime(2011, 1, 1),
Categories = new List<AccountTransactionService.CreateCategory> {
new AccountTransactionService.CreateCategory {
Id = "123",
Amount = 200.50m
}
}
});
Chop If Long:
cdata.GetByIdData = new Category { Id = "123", Name = "category" };
vdata.GetByIdData = new Vendor { Id = "456", Name = "vendor" };
adata.GetByIdData.Add(new Account { Id = "789", Name = "account", Balance = 5000 });
svc.ExecuteRequest(new AccountTransactionService.Add { Kind = AccountTransaction.KIND_DEBIT, Source = "789", Destination = "dst", Date = new DateTime(2011, 1, 1), Categories = new List<AccountTransactionService.CreateCategory> { new AccountTransactionService.CreateCategory { Id = "123", Amount = 200.50m } } });
I would expect Chop If Long to look like this given a margin of 80:
cdata.GetByIdData = new Category { Id = "123", Name = "category" };
vdata.GetByIdData = new Vendor { Id = "456", Name = "vendor" };
adata.GetByIdData.Add(new Account { Id = "789", Name = "account", Balance = 5000 });
svc.ExecuteRequest(new AccountTransactionService.Add {
Kind = AccountTransaction.KIND_DEBIT,
Source = "789",
Destination = "dst",
Date = new DateTime(2011, 1, 1),
Categories = new List<AccountTransactionService.CreateCategory> {
new AccountTransactionService.CreateCategory {
Id = "123",
Amount = 200.50m
}
}
});
"Chop if long" works only when you turn on "Wrap long lines" option, so you should turn it on. I guess that http://youtrack.jetbrains.com/issue/RSRP-291146 prevented you from getting the formatting you wanted with "Wrap long lines" turned on. Well, it should be fixed in ReSharper 7.1 EAP - try and write us if you still have problems.
Change "Wrap object collection and initialisers" to "Simple Wrap", that should style your code in the way you want it to.
Unfortunately, I can't look up what Chop if long is supposed to do as the Resharper community site is blocked from work for some strange reason.
There is an issue logged with JetBrains that is depicting the same behavior you describe...
http://youtrack.jetbrains.com/issue/RSRP-291146

Resources