I would like to start by saying that I am not a developer and this is my very first time writing a code to this extend of complication (at least to me). Any help/guidance would be much appreciated.
The idea of this program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered.
I created a folder called WebAPI which will access the API and retrieve the needed information. (please see the code)
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
Employeename status = JsonConvert.DeserializeObject<Employeename>(response);
string signature = status.Signature;
return signature;
}
}
}
I also created a class called Employeename which I defined the variables (please see code)
namespace TimeSheet_Try11_Models
{
public class Employeename
{
public string Signature { get; set; }
public string FirstName { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
}
}
Problem: There are no visible errors, however, when I start debugging and enter a name in the forms application, I get the error of "System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'" for the line "var response = wc.DownloadString(uri);" in the WebAPI folder.
Related
I am new to Web API and trying learn how to debug Web API with POSTMAN.It is working with GET request only POST request has some trouble. I am not able to trouble shoot what exactly the error is.
[HttpPost]
public HttpResponseMessage StudentDetails(Student data)
{
return new HttpResponseMessage()
{
Content = new StringContent(JArray.FromObject(data).ToString(), Encoding.UTF8, "application/json")
};
}
And Student Class is as below.
public class Student
{
public int StudentId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public string PersonalEmail { get; set; }
}
And I am trying to test the above action in POSTMAN. I added Content-Type as "application-json" and passing JSON as below .
{
StudentId :1
FirstName : 'SINI' ,
LastName :'A',
SSN : '7894300',
PersonalEmail: 'sini#gmail.com'
}
And In the POSTMAN, I gave the below URL :
http://localhost:60893/WebAPIDemo/api/Student
But it is giving me "The resource cannot be found".
Everything was perfect. I had two projects, one is web API and the other one is MVC. I forgot to keep web API as start up project.
url is not correct, change it to:
http://localhost:60893/WebAPIDemo/api/StudentDetails
so I'm pretty new to using Web.Api calls and have been reading up on them the last few days. In a nutshell I have a C# asp.net application that needs to post records to a Web.Api call that another group has setup for various applications to send records to that I need to interface with. Right now I have something that tries to work but I'm getting 'error 500: Internal server error' when I run things. I admit it could be on their end, but I wanted to make sure my end was correct as well.
So here is what I have. First I have a class I populate and send up to the wab.api call as that is what it is asking for
public class PackageData
{
public string HostName { get; set; }
public string SerialNumber { get; set; }
public int SourceID { get; set; }
public string PackageName { get; set; }
public string UserName { get; set; }
public string BatchID { get; set; }
public DateTime ReceivedTime { get; set; }
}
Here is the function I actually make the call with. Right now for testing purposes I populate a generic 'PackageData' object which I will eventually populate programatically
public string Test_Update()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://ServerName/Updates/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
PackageData InstallPackage = new PackageData();
InstallPackage.HostName = "ComputerName";
InstallPackage.SerialNumber = "SerialNumber";
InstallPackage.PackageName = "PackageName.EXE";
InstallPackage.SourceID = 1;
InstallPackage.UserName = "User";
InstallPackage.BatchID = 1;
InstallPackage.ReceivedTime = DateTime.Now;
HttpResponseMessage response = client.PostAsJsonAsync("api/Package?UserName=UserID&Password=password", InstallPackage).Result;
response.EnsureSuccessStatusCode();
return response.Headers.Location.ToString();
}
Is there anything glaring that looks wrong to anyone?
Thanks for the help!
I have a wordpress.org locally hosted on my pc.
I've installed a wordpress plugin called json-api which let you retrieve posts from your wordpress site.
I'm running the following code:
var client = new RestClient(BlogArticlesUrl);
var request = new RestRequest();
request.Timeout = 5000;
request.RequestFormat = DataFormat.Json;
request.Method = Method.GET;
request.AddParameter("json", "get_tag_posts");
request.AddParameter("slug", "featured");
request.AddParameter("count", "3");
var articles = client.Execute<List<BlogArticleModel>>(request);
After executing the code, in the variable articles I have the following:
Inside the Content there are few keys but I would only like to convert 'posts' to a model in c#
How do I acheive that?
EDIT:
I have found a solution using newtonsoft for dot net
Newtonsoft.Json.JsonConvert.DeserializeObject<BlogArticleResponse>(articles.Content);
In RestSharp, the Content is what gets deserialized. So, the type you pass into the .Execute<T> method must be the same structure as the response.
In your case, it will look something like this:
public class BlogArticleResponse
{
public string status { get; set; }
public int count { get; set; }
public int pages { get; set; }
public BlogTag tag { get; set; }
...
}
public class BlogTag
{
public int id { get; set; }
public string slug { get; set; }
public string title { get; set; }
public string description { get; set; }
...
}
You can then execute the request like this:
var result = client.Execute<BlogArticleResponse>(request);
For more information, have a look at the documentation.
I am using Microsoft Web API 2 and Protobuf-net to serialize my data. Everything is working perfectly, except when I want to send binary data to the Web API controller. I end up getting a 500 error.
Is this currently possible or is this restricted to serialization only? To verify my response was correct, I used ProtobufJS and it decoded it correctly. To pinpoint my issue, I excluded it and directly sent my response as soon as I got it. Any help getting set up would be greatly appreciated.
Web API Controller
public class UserController : ApiController
{
// GET api/<controller>
public User Get()
{
var user = new User{ Id = "ABC1", FirstName = "John", LastName = "Doe" };
return user;
}
// GET api/user/
public void Post(User user)
{
var type = "POST";
}
}
Model
[ProtoContract]
public class User
{
[ProtoMember(1)]
public string Id { get; set; }
[ProtoMember(2)]
public string FirstName { get; set; }
[ProtoMember(3)]
public string LastName { get; set; }
}
Javascript
<script>
var get = new XMLHttpRequest();
get.open("GET", "api/user", true);
get.responseType = "arraybuffer";
get.setRequestHeader("Accept", "application/x-protobuf");
get.onload = function (event) {
var arrayBuffer = get.response;
var post = new XMLHttpRequest();
post.open("POST", "api/user", true);
post.setRequestHeader("Accept", "application/x-protobuf");
post.overrideMimeType("application/x-protobuf");
post.send(arrayBuffer);
}
get.send(null);
</script>
I am wondering if anyone can assist me, I am having a problem with power bi. What I am trying to do is push some data into Power BI. I am finding it difficult to find an approach were a user can enter there user name and password and then I will be able to push data into the Power BI account.
I am getting stuck at the first hurdle of getting an Access Token. I just keeping bad request. I have also tried getting-started-for-dotnet which for some strange reason I can also not get to work.
Error given is: The remote server returned an error: (401) Unauthorized.
Registered as Web application
public class PowerBICreds
{
public string resourceUri { get; set; }
public string clientID { get; set; }
public string grantType { get; set; }
public string username { get; set; }
public string password { get; set; }
public string scope { get; set; }
public string clientSecret { get; set; }
public string loginAddress { get; set; }
public string baseurl { get; set; }
}
public static string AccessToken(PowerBICreds Creds)
{
StringBuilder Httpbody = new StringBuilder();
Httpbody.Append("resource=" + HttpUtility.UrlEncode(Creds.resourceUri));
Httpbody.Append("&client_id=" + HttpUtility.UrlEncode(Creds.clientID));
Httpbody.Append("&grant_type=" + HttpUtility.UrlEncode(Creds.grantType));
Httpbody.Append("&username=" + HttpUtility.UrlEncode(Creds.username));
Httpbody.Append("&password=" + HttpUtility.UrlEncode(Creds.password));
Httpbody.Append("&scope=" + HttpUtility.UrlEncode(Creds.scope));
Httpbody.Append("&client_secret=" + HttpUtility.UrlEncode(Creds.clientSecret));
using (WebClient web = new WebClient())
{
web.Headers.Add("client-request-id", Guid.NewGuid().ToString());
web.Headers.Add("return-client-request-id", "true");
string jsonstring = web.UploadString(Creds.loginAddress, Httpbody.ToString());
dynamic result = JsonConvert.DeserializeObject(jsonstring);
try
{
return result.access_token;
}
catch
{
}
return null;
}
}
Update when I try the sample to show how to use the Power BI API provided by Mircosoft here https://github.com/PowerBI/getting-started-for-dotnet
Additional technical information:
Correlation ID: f1281ec2-4e09-41e6-8847-3acfd3eb7922
Timestamp: 2015-12-04 22:48:58Z
AADSTS65005: The client application has requested access to resource 'https://analysis.windows.net/powerbi/api'. This request has failed because the client has not specified this resource in its requiredResourceAccess list.
The error you got when using our sample application may mean that the app you registered with AAD doesn't request any permission for Power BI. Try using our new app registration page at http://dev.powerbi.com/apps. If you just want to push data into Power BI, you just need the dataset read/write permission.