I have a ASP.NET app that I'm trying to log custom parameters from to NewRelic. The code for logging looks like this:
this.searchResults = performanceMonitor.RecordQuery(() => searchManager.DoQuery(this.searchRequest));
The performanceMonitor is just an object that does this:
public TSearchResult RecordQuery<TSearchResult>(Func<TSearchResult> query) where TSearchResult : SearchResult
{
var stopwatch = Stopwatch.StartNew();
var result = query();
stopwatch.Stop();
var externalTime = stopwatch.ElapsedMilliseconds;
var internalTime = ToMilliseconds(result.ExecutionTicks);
NewRelicHelper.AddAttributeToTransaction("QueryExternalTime", externalTime);
NewRelicHelper.AddAttributeToTransaction("QueryInternalTime", internalTime);
return result;
}
All the line with NewRelicHelper does is call NewRelic.Api.Agent.NewRelic.AddCustomParameter with "QueryExternalTime" and externalTime.
Yet after executing this code on machines with NewRelic agents, when I run a NewRelic query, I cannot see either QueryExternalTime or QueryInternalTime with their respective values on any transactions.
Related
Async method returns list with duplicated elements. It is async method which is using mysql connector to connect with database. Then it execute query (SELECT *) and by using MySqlDataReader - I save and add to list rows until last ReadAsync() call.
Asynchronous programming is still black magic for me - I would appreciate any feedback or indicating unlogical code lines with explanation.
This method will be used in my web api controller and method purpose is to return all entries from 'Posts' table. Code is working fine when I 'reset' temp object each loop by using
temp = new Post(); but I assume it is unacceptable ? What if my database would have not 15 but 15000 entries?
`
public async Task<List<Post>> GetPostsAsync()
{
List<Post> posts = new List<Post>();
Post temp = new Post();
try
{
await _context.conn.OpenAsync();
MySqlCommand cmd = new MySqlCommand("USE idunnodb; SELECT * FROM Posts;", _context.conn);
await using MySqlDataReader reader = await cmd.ExecuteReaderAsync();
while(await reader.ReadAsync())
{
temp.PostID = (int)reader[0];
temp.UserID = (int)reader[1];
temp.PostDate = reader[2].ToString();
temp.PostTitle = reader[3].ToString();
temp.PostDescription = reader[4].ToString();
temp.ImagePath = reader[5].ToString();
posts.Add(temp);
}
await _context.conn.CloseAsync();
}
catch (Exception ex)
{
return Enumerable.Empty<Post>().ToList();
}
return posts;
}
`
Looks like you can only read data by looping through MySqlDataReader, according to your code logic, you need to read each piece of data, and then add them to the List one by one for output.
Your code is behaving this way because temp has been declared & instantiated outside of your reader.ReadAsync() statement, you are updating the same object reference each time around the loop which is why you are seeing repeating objects in your list.
So you need to instantiate in reader.ReadAsync() loop:
while(await reader.ReadAsync())
{
Post temp = new Post();
...
}
I want to retrieve the specific data using an array-values, but I don't know how to deal with it.
URL is like http://localhost/api/data?sym=aa&bb&cc
DB documents are like:
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
{"symbol":"dd","price":1.4}
{"symbol":"ee","price":1.5}
the expected result is:
[
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
]
My code is:
[HttpGet()]
public IEnumerable<Data> Get(string sym)
{
symbol = sym.Split('&');
//connect to database and collections
var client = new MongoClient("mongodb+srv://.....");
var db = client.GetDatabase("...");
var _portf = db.GetCollection<Data>("...");
return _portf.Find(???).ToList();
}
??? is where I have failed to find a solution. or I am completely wrong with the find() method.
I really need your help. Thank you!
Find takes in a FilterDefinition object. For example, a common way of getting a document from MongoDB by its ID would be:
public T LoadRecordById<T>(string table, Guid id)
{
var collection = db.GetCollection<T>(table);
var filter = Builders<T>.Filter.Eq("Id", id);
return collection.Find(filter).First();
}
You can combine multiple FilterDefinition objects together using the Or method:
var filter1 = Builders<T>.Filter.Eq("symbol", symbol);
var filter2 = Builders<T>.Filter.Eq("symbol", symbol);
var filter3 = Builders<T>.Filter.Eq("symbol", symbol);
var filter = Builders<T>.Filter.Or(filter1, filter2, filter3);
Hope this helps (it does not hurt to be nice, does it, #Dharman?)
I've found a very promising way which works perfectly. Thanks to this video
rewrite the code"
[HttpGet()]
public IEnumerable<Data> Get(string sym)
{
var symlist = sym.Split('&');
//connect to database and collections
var client = new MongoClient("mongodb+srv://.....");
var db = client.GetDatabase("...");
var _portf = db.GetCollection<Data>("...");
-->var fitlerDefinition = Builders<Findata>.Filter.In(a => a.Symbol, symlist);
return _portf.Find(fitlerDefinition).ToList();
}
I need to support pagination for azure cosmos db. I know that cosmos db works on continuation token for next set of result. However I don't understand how to navigate to previous set of result.
As i know,from official way,you could only implement pagination based on continuation token.You need to encapsulate method to achieve that.
You could refer to the document wrote by #Nick.
Also,you could refer to below sample code:
private static async Task<KeyValuePair<string, IEnumerable<CeleryTask>>> QueryDocumentsByPage(int pageNumber, int pageSize, string continuationToken)
{
DocumentClient documentClient = new DocumentClient(new Uri("https://{CosmosDB/SQL Account Name}.documents.azure.com:443/"), "{CosmosDB/SQL Account Key}");
var feedOptions = new FeedOptions {
MaxItemCount = pageSize,
EnableCrossPartitionQuery = true,
// IMPORTANT: Set the continuation token (NULL for the first ever request/page)
RequestContinuation = continuationToken
};
IQueryable<CeleryTask> filter = documentClient.CreateDocumentQuery<CeleryTask>("dbs/{Database Name}/colls/{Collection Name}", feedOptions);
IDocumentQuery<CeleryTask> query = filter.AsDocumentQuery();
FeedResponse<CeleryTask> feedRespose = await query.ExecuteNextAsync<CeleryTask>();
List<CeleryTask> documents = new List<CeleryTask>();
foreach (CeleryTask t in feedRespose)
{
documents.Add(t);
}
// IMPORTANT: Ensure the continuation token is kept for the next requests
return new KeyValuePair<string, IEnumerable<CeleryTask>>(feedRespose.ResponseContinuation, documents);
}
Then, the following example illustrates how to retrieve documents for a given page by calling the previous method:
private static async Task QueryPageByPage()
{
// Number of documents per page
const int PAGE_SIZE = 3;
int currentPageNumber = 1;
int documentNumber = 1;
// Continuation token for subsequent queries (NULL for the very first request/page)
string continuationToken = null;
do
{
Console.WriteLine($"----- PAGE {currentPageNumber} -----");
// Loads ALL documents for the current page
KeyValuePair<string, IEnumerable<CeleryTask>> currentPage = await QueryDocumentsByPage(currentPageNumber, PAGE_SIZE, continuationToken);
foreach (CeleryTask celeryTask in currentPage.Value)
{
Console.WriteLine($"[{documentNumber}] {celeryTask.Id}");
documentNumber++;
}
// Ensure the continuation token is kept for the next page query execution
continuationToken = currentPage.Key;
currentPageNumber++;
} while (continuationToken != null);
Console.WriteLine("\n--- END: Finished Querying ALL Dcuments ---");
}
BTW,you could follow below traces about this feature in cosmos db feedback:
https://github.com/Azure/azure-documentdb-dotnet/issues/377
https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/6350987--documentdb-allow-paging-skip-take
Before Google Analytic Update there api this code works.
string userName = GAEmailAddress.ToString();//Its From Database
string passWord = GAPassword.ToString();//Its From Database
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
AccountQuery query = new AccountQuery();
AnalyticsService service = new AnalyticsService("AnalyticsApp");
if (!string.IsNullOrEmpty(userName))
{
service.setUserCredentials(userName, passWord);
}
string str = "";
try
{
AccountFeed accountFeed = service.Query(query);
foreach (AccountEntry entry in accountFeed.Entries)
{
str = entry.ProfileId.Value;
}
DataQuery query1 = new DataQuery(dataFeedUrl);
// Bounce Rate Calculations
query1.Ids = str;
query1.Metrics = "ga:visits,ga:bounces";//visitors
query1.Sort = "ga:visits";
query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
query1.StartIndex = 1;
//Others code and other data for bound
I search in SO and and Find this link.
gapi account data url goes to 404
I replace this link :
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
with:
https://www.googleapis.com/analytics/v2.4/management/accounts?start-index=1&max-results=100&key=API_KEY
But I still I gett error:
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
I still search and find this link:
https://developers.google.com/analytics/devguides/reporting/core/v2/#register
As link says I replace :
https://www.googleapis.com/analytics/v2.4/data
But still I got error ? What I am missing here? Thanks.
Morning,
I am trying to pass a list of Amazon ASIN's so i can process them using the MWS API.
List<string> prodASINs = dc.aboProducts.Select(a => a.asin).ToList();
var count = prodASINs.Count();
//Loop through passing 10 at a time to AWS
for (var i = 0; i < count; i++)
{
var prodASINToSend = prodASINs.Skip(i * 10).Take(10).ToList();
//Send to AWS
MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
config.ServiceURL = productsURL;
MarketplaceWebServiceProducts.MarketplaceWebServiceProductsClient service = new MarketplaceWebServiceProductsClient(appname, version, accesskeyID, secretkey, config);
GetLowestOfferListingsForASINRequest request = new GetLowestOfferListingsForASINRequest();
request.SellerId = merchantID;
request.MarketplaceId = marketids[0];
request.ItemCondition = condition;
request.ASINList.ASIN = prodASINToSend;
However the request.ASINList.ASIN = prodASINToSend; is saying "Object reference not set to an instance of an object." However it is passing over the required List<string> prodASINToSend
Could anyone shed some light on this for em please?
The error means you forgot to declare a new instance of a class before trying to use the class object.
In your case the ASINList will need to be declared as a new instance of the ASINList class.