Why my log messages always have the top level operation name? - appinsights

When logging from the inner scope of a nested operation the log message has the "Operation Name" set to the top-level operation
using (IOperationHolder<RequestTelemetry> topHolder = telemetryClient.StartOperation<RequestTelemetry>("TopOperation1"))
{
//telemetryClient.TrackTrace("top holder log 111");
logger.LogWarning("top holder log 1");
using (IOperationHolder<RequestTelemetry> innerHolder = telemetryClient.StartOperation<RequestTelemetry>("InnerOperation1"))
{
//telemetryClient.TrackTrace("inner holder log 1 111");
logger.LogWarning("inner holder log 1");
}
}

for the new operation to be a child you will need to provide a parent id to that operation. Start the child operation by providing following parameters.
.StartOperation<RequestTelemetry>("InnerOperation1",Guid.NewGuid().ToString(), Activity.Current.Id)

Related

is it possible to create a message which has a field with its own type with protocol buffer

Is it possible to define a message which has a field of its own type as in linked lists with protocol buffers? For example the value of next field could be null at the end of the list.
message Node {
string name = 1;
Node next = 2;
}
I know you asked how to make a custom type. The documentation mentions to try to avoid that. I find that you can model almost anything with the parts / types that are built in. To make a list of nodes with the built in types do this:
message ResponseOfNodes {
repeated Node nodes = 1;
}
message Node {
string name = 1;
string someOtherData = 2;
}
Here's code that uses the generated code / list.
// make a node so it can be added to the list.
Node node1 = Node.newBuilder().setName("a name").setSomeOtherData("etc").build();
// Build a response (ResponseOfNodes) that will get nodes added to its list. Add two Nodes.
ResponseOfNodes.Builder responseBuilder = ResponseOfNodes.newBuilder().addNodes(node1);
responseBuilder.addNodes(node1.toBuilder().setName("name 2").build());
// build the ResponseOfNodes and print it out.
ResponseOfNodes responseOfNodes = responseBuilder.build();
log.info("the list: {}", responseOfNodes.getNodesList());
Console Output;
[INFO ] [main] - Hello I am a client.
[INFO ] [main] - the list: [name: "a name"
someOtherData: "etc"
, name: "name 2"
someOtherData: "etc"

Linq to entities giving error when generic repository is used with List<T> object

In my ASP.NET Web API project, I am trying to use the generic repositories with the List objects under one of the methods. But it is throwing exception
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
System.Data.Entity.Core.EntityCommandExecutionException: Calling 'Read' when the data reader is closed is not a valid operation. --->
System.Data.SqlClient.SqlException: Execution Timeout Expired. The
timeout period elapsed prior to completion of the operation or the
server is not responding. ---> System.ComponentModel.Win32Exception:
The wait operation timed out
lstFinalResult object contains few rows. partnerRepo is a generic repo and will have data at the later stage, i suppose.
Please advise, where am i making the mistake. Can we mix the List with generic repository objects in the linq query ?
Here is the linq code :-
List<UserDocumentResult> lstFinalResult = new List<UserDocumentResult>();
foreach (DocumentMapping dm in lstMappings)
{
lstFinalResult.Add(new UserDocumentResult { PID = dm.PartnerID,
DocMappingID = dm.DocumentMappingID,
EntityType = "",
Name = ""
});
}
var partnerRepo = _docRepository.PtGenericRepo.Get();
var entityCodesRepo = _docRepository.EntityCodeGenericRepo.Get();
---While debugging, I am getting error in the below code only.
var qualifiedPartnerSet = (from tmp in lstFinalResult
join px in partnerRepo on tmp.PID equals px.PartnerID
join ecx in entityCodesRepo on px.EntityCodeID equals ecx.EntityCodeID
select new UserDocumentResult
{
PID = px.PartnerID,
MappingID = tmp.MappingID,
EntityType = ecx.DisLabel.Trim(),
Name = px.NameLine1.Trim() + px.NameLine2.Trim(),
}).ToList();

MANAGED_CLASS_MAPPING_ERROR given javaClass 'class java.util.ArrayList' is mapped to ListType, expected ManagedType

We are starting to experiment with JaVers in our application. We want to track changes to orders after they are placed by users. So it's your typical order object with the main order object, items, item options, etc. About half the time we go to run the test program we are receiving this exception:
130 [main] INFO org.javers.core.JaversBuilder - JaVers instance is up
& ready Exception in thread "main" JaversException:
MANAGED_CLASS_MAPPING_ERROR given javaClass 'class
java.util.ArrayList' is mapped to ListType, expected ManagedType at
org.javers.core.metamodel.type.TypeMapper.getJaversManagedType(TypeMapper.java:149)
at
org.javers.core.metamodel.type.TypeMapper.getJaversManagedType(TypeMapper.java:132)
at
org.javers.core.metamodel.object.GlobalIdFactory.createId(GlobalIdFactory.java:39)
at
org.javers.core.graph.LiveCdoFactory.create(LiveCdoFactory.java:24)
at org.javers.core.graph.EdgeBuilder.asCdo(EdgeBuilder.java:39) at
org.javers.core.graph.EdgeBuilder.buildSingleEdge(EdgeBuilder.java:32)
at
org.javers.core.graph.ObjectGraphBuilder.buildSingleEdges(ObjectGraphBuilder.java:81)
at
org.javers.core.graph.ObjectGraphBuilder.buildEdges(ObjectGraphBuilder.java:71)
at
org.javers.core.graph.ObjectGraphBuilder.buildGraphFromCdo(ObjectGraphBuilder.java:59)
at
org.javers.core.graph.ObjectGraphBuilder.buildGraph(ObjectGraphBuilder.java:48)
at
org.javers.core.graph.LiveGraphFactory.createLiveGraph(LiveGraphFactory.java:39)
at org.javers.core.diff.DiffFactory.buildGraph(DiffFactory.java:109)
at org.javers.core.diff.DiffFactory.compare(DiffFactory.java:64) at
org.javers.core.JaversCore.compare(JaversCore.java:104)
We just rerun the program and eventually it works. The code basically looks like this.
// Original database object
OrderVO oldOrder = // load from database.
// Changed database object
OrderVO newOrder = // load from database.
// Change the email
newOrder.setEmail("test#test.com");
// Simulate changing quantity and item id on items
for (OrderItemVO OrderItemVO : newOrder.getItems()) {
OrderItemVO.setMerchantItemId(OrderItemVO.getMerchantItemId() + "A");
OrderItemVO.setQuantity(OrderItemVO.getQuantity().add(1));
}
// Remove the first item
OrderItemVO[] items = new OrderItemVO[newOrder.getItems().length - 1];
System.arraycopy(newOrder.getItems(), 1, items, 0, items.length);
newOrder.setItems(items);
// Run comparison
Javers javers = JaversBuilder.javers().withListCompareAlgorithm(ListCompareAlgorithm.LEVENSHTEIN_DISTANCE).build();
Diff diff = javers.compare(oldOrder, newOrder);

Starting Activity Indicator while Running a database download in a background thread

I am running a database download in a background thread. The threads work fine and I execute group wait before continuing.
The problem I have is that I need to start an activity indicator and it seems that due to the group_wait it gets blocked.
Is there a way to run such heavy process, ensure that all threads get completed while allowing the activity indicator to run?
I start the activity indicator with (I also tried starting the indicator w/o the dispatch_async):
dispatch_async(dispatch_get_main_queue(), {
activityIndicator.startAnimating()
})
After which, I start the thread group:
let group: dispatch_group_t = dispatch_group_create()
let queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //also tried QOS_CLASS_BACKGROUND
while iter > 0 {
iter--
dispatch_group_enter(group)
dispatch_group_async(group, queue, {
do {
print("in queue \(iter)")
temp += try query.findObjects()
query.skip += query.limit
} catch let error as NSError {
print("Fetch failed: \(error.localizedDescription)")
}
dispatch_group_leave(group)
})
}
// Wait for all threads to finish and proceed
As I am using Parse, I have modified the code as follows (psuedo code for simplicity):
trigger the activity indicator with startAnimating()
call the function that hits Parse
set an observer in the Parse class on an int to trigger an action when the value reaches 0
get count of new objects in Parse
calculate how many loop iterations I need to pull all the data (using max objects per query = 1000 which is Parse max)
while iterations > 0 {
create a Parse query object
set the query skip value
use query.findObjectsInBackroundWithBlock ({
pull objects and add to a temp array
observer--
)}
iterations--
}
When the observer hits 0, trigger a delegate to return to the caller
Works like a charm.

JMeter, threads using dynamic incremented value

I have created a JMeter functional test that essentially:
creates a user;
logs in with the user;
deletes the user.
Now, I need to be able to thread this, and dynamically generate a username with a default prefix and a numerically incremented suffix (ie TestUser_1, TestUser_2, ... etc).
I used the counter, and things were working fine until I really punched up the number of threads/loops. When I did this, I was getting a conflict with the counter. Some threads were trying to read the counter, but the counter had already been incremented by another thread. This resulted in trying to delete a thread that was just created, then trying to log in with a thread that was just deleted.
The project is set up like this:
Test Plan
Thread group
Counter
User Defined Variables
Samplers
I was hoping to solve this problem by using the counter to append a number to the user defined variables upon thread execution, but the counter cannot be accessed in the user defined variables.
Any ideas on how I can solve this problem?
Thank you in advance.
I've used the following scheme successfully with any amount of test users:
1. Generate using beanshell-script (in BeanShell Sampler e.g.) csv-file with test-user details, for example:
testUserName001,testPwd001
testUserName002,testPwd002
. . .
testUserName00N,testPwd00N
with the amount of entries you need for the test-run.
This is done once per "N users test-run", in separate Thread Group, in setUp Thread Group or maybe even in separate jmx-script... makes no difference.
You can please find working beanshell-code below.
2. Create your test users IN TEST APPLICATION using previously created users-list.
If you don't need create in application you may skip this.
Thread Group
Number of Threads = 1
Loop Count = 1
. . .
While Controller
Condition = ${__javaScript("${newUserName}"!="",)} // this will repeat until EOF
CSV Data Set Config
Filename = ${__property(user.dir)}${__BeanShell(File.separator,)}${__P(users-list,)} // path to generated users-list
Variable Names = newUserName,newUserPwd // these are test-users details read from file into pointed variables
Delimiter = '
Recycle on EOF? = False
Stop thread on EOF? = True
Sharing Mode = Current thread group
[CREATE TEST USERS LOGIC HERE] // here are actions to create separate user in application
. . .
3. Perform multi-user logic.
Schema like the given above one but Thread Group executed not for 1 but for N threads.
Thread Group
Number of Threads = ${__P(usersCount,)} // set number of users you need to test
Ramp-Up Period = ${__P(rampUpPeriod,)}
Loop Count = X
. . .
While Controller
Condition = ${__javaScript("${newUserName}"!="",)} // this will repeat until EOF
CSV Data Set Config
Filename = ${__property(user.dir)}${__BeanShell(File.separator,)}${__P(users-list,)} // path to generated users-list
Variable Names = newUserName,newUserPwd // these are test-users details read from file into pointed variables
Delimiter = '
Recycle on EOF? = False
Stop thread on EOF? = True
Sharing Mode = Current thread group
[TEST LOGIC HERE] // here are test actions
. . .
The key idea is in using Thread Group + While Controller + CSV Data Set Config combination:
3.1. CSV Data Set Config reads details for each the test users from generated file:
. . . a. only once - because of "Stop thread on EOF? = True";
. . . b. doesn't block file for further access (in another thread groups, e.g., if there are any) - because of "Sharing Mode = Current thread group";
. . . c. pointed variables - "Variable Names = newUserName,newUserPwd" - you will use in further test-actions;
3.2. While Controller forces CSV Data Set Config to read all the entries from generated file - because of defined condition (until the EOF).
3.3. Thread Group will start all the threads with defined ramp-up - or simultaneously if ramp-up = 0.
You can take here template script for described schema: multiuser.jmx.
Beanshell script to generate test-users details looks like below and takes the following args:
- test-users count
- test-user name template ("TestUser_" in your case)
- test-user name format (e.g. 0 - to get TestUser_1, 00 - to get TestUser_01, 000- for TestUser_001, etc... you can simply hardcode this orexclude at all)
- name of generated file.
import java.text.*;
import java.io.*;
import java.util.*;
String [] params = Parameters.split(",");
int count = Integer.valueOf(params[0]);
String testName = params[1];
String nameFormat = params[2];
String usersList = params[3];
StringBuilder contents = new StringBuilder();
try {
DecimalFormat formatter = new DecimalFormat(nameFormat);
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir") + File.separator + usersList);
for (int i = 1; i <= count; i++) {
String s = formatter.format(i);
String testUser = testName + s;
contents.append(testUser).append(",").append(testUser);
if (i < count) {
contents.append("\n");
}
}
byte [] buffer = contents.toString().getBytes();
fos.write(buffer);
fos.close();
}
catch (Exception ex) {
IsSuccess = false;
log.error(ex.getMessage());
System.err.println(ex.getMessage());
}
catch (Throwable thex) {
System.err.println(thex.getMessage());
}
All together it will look like:
Sorry if answer is too overloaded.
Hope this helps.
The "User Defined Variables" config element does not pick up the reference variable from the "Counter" config element. I think this is a bug in JMeter. I have verified this behavior in version 3.2.
I added a "BeanShell Sampler" element to work around the issue.
Notice that the reference name of the "Counter" element is INDEX
The RUN_FOLDER variable gets set to a combination of the TESTS_FOLDER variable and the INDEX variable in the "BeanShell Sampler"
The "Debug Sampler" simply gathers a snapshot of the variables so I can see them in the "View Results Tree" listener element. Notice how the RUN_FOLDER variable has the INDEX variable value (5 in this case) appended.

Resources