How to Use application Insights REST API in Visual Studio MVC project - c#

I want to retrieve all the data that is present in my resource on the azure portal. I have found out that there is a REST API for application insights that can help in retrieving the data. What I want is to get the data and generate a grid report on my web page which displays the events related information, that is, date, type, message and all the related information. I haven't worked with REST API's before and what I want as a help is a proper guideline to use this REST API in my MVC based web project in visual studio. If anyone can help will be a great assistance.

You can follow the steps below:
step 1: Get the Application ID and an API key.
Nav to your application insights -> API Access, see the screenshot(Please remember, when the api key is generated, write it down):
step 2: Understand the API Format, for details, refer to here:
Here is an example for get requests count in the last 6 hours:
https://api.applicationinsights.io/v1/apps/your-application-id/metrics/requests/count?timespan=PT6H
This part https://api.applicationinsights.io/v1/apps/ do not need to change.
Then input your-application-id which you get from last step.
Then you can specify metrics or events as per your demand.
This part requests/count, you can refer to this, screenshot below:
The last part ?timespan=PT6H, you can refer to this, screenshot below:
step 3: Write your code to call this api, like below:
public class Test
{
private const string URL_requests = "https://api.applicationinsights.io/v1/apps/your-application-id/metrics/requests/count?timespan=PT6H";
public string GetRequestsCount()
{
// in step 1, you get this api key
string apikey = "flk2bqn1ydur57p7pa74yc3aazhbzf52xbyxthef";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key", apikey);
var req = string.Format(URL_requests);
HttpResponseMessage response = client.GetAsync(req).Result;
if (response.IsSuccessStatusCode)
{
// you can get the request count here
return response.Content.ReadAsStringAsync().Result;
}
else
{
return response.ReasonPhrase;
}
}
}

Related

Unclear structure of authentification endpoint for changenotifications from graph api

I try to subscribe for the User[id]/messages source at the developer programm exchange server.
How i have to structure my request against graph is totally clear. and works but how i have to process the authentication request of Graph is unclear. I know i have to aswer with a 200 OK but i also have to send the processed token back according to some Tutorials. But not a single tutorial shows a example authentication endpoint.
[HttpPost]
[Route("api/changeNotifications")]
public HttpResponseMessage ChangeNotificationEndpoint(HttpRequestMessage httpRequestMessage)
{
_logger.Debug("Anfrage von Graph an Vif erhalten");
return new HttpResponseMessage
{
StatusCode = System.Net.HttpStatusCode.OK,
Content = /* The unclear section */ ;
};
}
I have tried to to follow some tutorials but each tutorial lacks of an example endpoint.
Here is the sample for Notification endpoint validation:
For more information: https://learn.microsoft.com/en-us/graph/webhooks?tabs=http#notification-endpoint-validation
Hope this helps.

Verify application for Loader.Io testing

I am trying to do some load testing with
https://loader.io/
I am currently stuck at the stage of "verifying" my localHost application to make sure I am the one controlling it.
I have added this end point:
[HttpGet("/loaderio-a65421134i3ia3d110vcv0120d1ac14b/")]
[Authorize()]
public StreamReader GetLoaderIO()
{
var file = System.IO.File.OpenText(#"C:\Users\User\Downloads\loaderio-a65421134i3ia3d110vcv0120d1ac14b.txt");
return file;
}
When I run a GET request to this URL
http://localhost:5012/loaderio-a65421134i3ia3d110vcv0120d1ac14b/
I successfully step in my end point, what do I need to return in order for the LoaderIO to be happy? Do I have to return the stream so it can be downloaded?
I can see three potential issues with your code.
First, you are targeting a localhost address instead of a deployment address (i.e. http://yourapi.com or 159.254.102.69). To fix that issue you will need to either deploy your code somewhere or open http ports from your machine.
Second the file you are trying to retrieve my not be at the same location or might not even be accessible so a simpler way would be to write the string directly (done multiple time to verify on loader.io works like a charm) like below:
[HttpGet]
[Route("loaderio-a65421134i3ia3d110vcv0120d1ac14b")]
public HttpResponseMessage GetLoaderIoVerification()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("loaderio-a65421134i3ia3d110vcv0120d1ac14b", Encoding.UTF8, "text/plain");
return response;
}
Finally, there is that Authorize attribute that will try to authenticate the loader.io request that needs to be a resource as accessible as this one: https://media4.giphy.com/media/LXONhtCmN32YU/giphy.gif In order to do so you will need to remove it.
Once those three points are corrected you will be able to verify your api for loader.io. Hope it helps.

Invalid PUT method from Webforms to Web API 2 (Azure)

I have a Web API in my Azure server and I'm making calls from an ASP.NET Webforms website.
I seem to be able to perform GET with no trouble. Now for the PUT, it's giving me this error:
The page you are looking for cannot be displayed because an invalid
method (HTTP verb) is being used
I was not able to DELETE either. I see some other topics where people disable some WebDav and stuff on their IIS servers and it works. But on Azure?
Below my code for the PUT:
HttpResponseMessage response = client.GetAsync("api/People/" + id).Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsAsync<People>().Result;
Uri peopleUrl = response.Headers.Location;
yourcustomobjects.name= "Bob";
response = await client.PutAsJsonAsync(peopleUrl, yourcustomobjects);
tbDebug.Text += await response.Content.ReadAsStringAsync();
}
Alright I grew tired of trying to fix this issue by enabling PUT.
So what I did, was I wrote a GET that makes the needed change in the database.
Cheers

Using JSON and HTTP Request in C#

I'm currently developing an Android app and I'm using Connect Android to MS SQL Server Tutorial to link my MSSQL server to the code.
And the first part is good though the second part is using a third party program to code which I don't want to. I want to write the whole code in C# (I'm using Xamarin).
I found out Json.NET / Json.NET for Xamarin website.
Though how am I supposed to use the HTTPUtils and requests in C# ? An example would be great.
Also, I have kind of a newbie question, I'm trying to get to the root of the code I sent, the .aspx file, and I don't quite understand where the web method is, I am used to a seperate .asmx file containing [Web Method]s that define them and then I can use them freely by creating a web reference on an .aspx file, so, where is the web method in the code I sent ?
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO: handle exception
}
return string;
}

How to create an otrs ticket using a soap request

The lack of documentation on this subject coupled with the fact that I'm struggling with a learning curve on all fronts and making me really confused about where to start. I need to get this done using C# if possible. I apologize for the vagueness of this question, but I'm really lost. I would love links to comprehensive guides/references.
In my efforts to get this done, I've run into the following problems/questions:
I've created a web service using the otrs gui, with the operation CreateTicket, but requests via C# to my chosen namespace are returning 404 (not found). When I try to add a service reference or web reference with that namespace, I get the same error. However, when I plug that namespace into my browser as the url, it displays "customer.pl".
Can I send a soap request without adding the web service as a service reference in visual studio? Given the previous problem I'm having I can't do it that way. Would I just build the soap request string and write it to the web request's data stream with http://domain/rpc.pl as the uri?
If the answer to the previous question is yes... When trying the below code segment I get an internal server error (500) on the last line. However the header looks like a SOAP header which confuses me because I wouldn't have thought it got that far.
var document = new StringBuilder();
document.Append("<UserLogin>some user login</UserLogin>");
document.Append("<Password>some password</Password> ");
document.Append("<Ticket>");
document.Append("<Title>some title</Title> ");
document.Append("<CustomerUser>some customer user login</CustomerUser>");
document.Append("<Queue>some queue</Queue>");
document.Append("<State>some state</State>");
document.Append("<Priority>some priority</Priority>");
document.Append("</Ticket>");
document.Append("<Article>");
document.Append("<Subject>some subject</Subject>");
document.Append("<Body>some body</Body>");
document.Append("<ContentType>text/plain; charset=utf8</ContentType>");
document.Append("</Article>");
//var uri = new Uri("http://domain/injest");
var uri = new Uri("http://domain/rpc.pl");
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(document.ToString());
httpWebReq.Timeout = 5 * 1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
httpWebReq.ContentType = "text/xml;charset=utf-8";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
Even if all you can offer is where to start, it would help me to know how to proceed, as I'm stumped.
You're using the rpc.pl endpoint which is part of the 'old' RPC-style interface.
You mention you added the web service via the GUI which means you're using the 'new' Generic Interface, which is indeed much easier from .Net.
The address of the endpoint is /otrs/nph-genericinterface.pl/Webservice/GenericTicketConnector or whatever you have called the web service in the admin section.

Categories