I am currently in the process of developing a Windows 8 (Windows Store) app that connects to a sharepoint site using the REST interface. Currently, I have successfully managed to pull down list data from the _vti_bin/ListData.svc/ uri. However, I am stuck on creating new list items from within the app, and Posting these back into sharepoint.
I am trying to use an HTTP POST method, however am receiving a 405 error code: MethodNotAllowed. Below is my code:
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.UseDefaultCredentials = true;
HttpClient newClient = new HttpClient(clientHandler);
// HttpResponseMessage response = newClient.PostAsync("http://sharepoint/.../_vti_bin/ListData.svc/Nominations", test);
var resp = await newClient.GetAsync(newUri("http://sharepoint/.../_vti_bin/ListData.svc/Nominations"));
using (newClient)
using (var ms = new MemoryStream())
{
var djs = new DataContractJsonSerializer(typeof(NominationsItem));
djs.WriteObject(ms, test);
ms.Position = 0;
var sc = new StreamContent(ms);
sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
resp = test == null
? await newClient.PutAsync(new Uri("http://sharepoint/.../_vti_bin/ListData.svc/Nominations"), sc)
: await newClient.PostAsync(new Uri("http://sharepoint.../_vti_bin/ListData.svc/Nominations"), sc);
resp.EnsureSuccessStatusCode();
}
Any help would be appreciated!
Related
I do the update command through the API. Everything seems fine. However, the data is not up to date. When I debug there is no error.
public async Task UpdateViewRatingStore(bool value)
{
var url = baseUrl + userget;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mytokenlogin);
string jsonStr = await client.GetStringAsync(url);
var res = JsonConvert.DeserializeObject<Customer>(jsonStr);
var checkunredrating = res.RatingStores;
if (checkunredrating != null)
{
foreach (var r in checkunredrating)
{
r.ID = r.ID;
r.StoreID = r.StoreID;
r.RatingStores = r.RatingStores;
r.CommentStore = r.CommentStore;
r.UserRating = r.UserRating;
r.CreateDay = r.CreateDay;
r.Display = r.Display;
r.ViewStorer = value;
var urlput = baseUrlStoreRating + r.ID;
var stringContent = new StringContent(JsonConvert.SerializeObject(res.RatingStores), Encoding.UTF8, "application/json");
await client.PutAsync(urlput, stringContent);
}
}
}
However when I check in the database it is still not updated. I tested it manually on swagger and Posman was fine. Where did I go wrong? Ask for help. Thank you
you are trying to update a single object, but passing the entire collection every time
instead, try this
foreach (var r in checkunredrating)
{
// you only need to update the changed values
r.ViewStorer = value;
var urlput = baseUrlStoreRating + r.ID;
// only send the current object you are updating
var stringContent = new StringContent(JsonConvert.SerializeObject(r), Encoding.UTF8, "application/json");
await client.PutAsync(urlput, stringContent);
}
Im trying to determine the content type of HtmlAgility.HtmlDocument. Any idea??
HtmlWeb web = new HtmlWeb();
var hDocument = web.Load(/*string*/ url);
I want to know how to find out the contentType of hDocument if possible, or if there is any work round it. Thanks
Basically what you want is the httpwebresponse object, to get this with hap you can use the taskcompletionsource class like this.
var web = new HtmlAgilityPack.HtmlWeb();
var tcs = new TaskCompletionSource<HttpWebResponse>();
web.PostResponse = delegate(HttpWebRequest request, HttpWebResponse response)
{
tcs.SetResult(response);
};
var document = web.Load("http://stackoverflow.com/");
var httpWebResponse = await tcs.Task;
var contentType = httpWebResponse.ContentType
I have not done this in a while and didn't get a chance to test this code but it should work for what you want.
Get HttpWebResponse from Html Agility Pack HtmlWeb
https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.contenttype?view=netframework-4.7.2
am faced with a challenge for some time now. I have a web service (asp.net web api), that consumes a certain api, after the consumption, my api will then send the consumed data to another external api. I use REST Sharp for my data serialization and request.
But anytime i send this request. I get a null result.
Anybody to help?
Sequel to my question above #igor, below is my code snippet
public object AccountOpening(JObject exRequest)
{
var Account = new AccountViewModel(exRequest.ToString());
Account.cifID = "null";
Account.AddrCategory = "Mailing";
Account.Country = "NG";
Account.HoldMailFlag = "N";
Account.PrefAddr = "Y";
Account.Language = "UK (English)";
Account.IsMinor = "N";
Account.IsCustNRE = "N";
Account.DefaultAddrType = "Mailing";
Account.Occupation = "OTH";
Account.PhoneEmailType = "CELLPH";
var serviceAPI = ConfigurationManager.AppSettings["RemoteAPI"];
var request = new RestSharp.Serializers.Newtonsoft.Json.RestRequest();
request.AddParameter("application/json", Account, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.JsonSerializer = new RestSharp.Serializers.JsonSerializer();
var client = new RestClient(serviceAPI);
IRestResponse resp = client.Post(request);
if (resp.IsSuccessful==true)
{
return Json(new {resp.Content });
}
}
I'm trying to create an Atompub service with ASP.NET WEB API, all it's ok but when I try to post any image from Windows Live Writer I get an error "The blog doesn't allow the image load" I'm reading the ietf doc.
My services controller code:
public class ServicesController : ApiController
{
public HttpResponseMessage Get()
{
var serviceDocument = new ServiceDocument();
var workSpace = new Workspace
{
Title = new TextSyndicationContent("Nicoloco Site"),
BaseUri = new Uri(Request.RequestUri.GetLeftPart(UriPartial.Authority))
};
var posts = new ResourceCollectionInfo("Nicoloco Blog",
new Uri(Url.Link("DefaultApi", new { controller = "blogapi" })));
posts.Accepts.Add("application/atom+xml;type=entry");
var images = new ResourceCollectionInfo("Images Blog",
new Uri(Url.Link("DefaultApi", new { controller = "images" })));
images.Accepts.Add("image/png");
images.Accepts.Add("image/jpeg");
images.Accepts.Add("image/jpg");
images.Accepts.Add("image/gif");
var categoriesUri = new Uri(Url.Link("DefaultApi", new { controller = "tags", format = "atomcat" }));
var categories = new ReferencedCategoriesDocument(categoriesUri);
posts.Categories.Add(categories);
workSpace.Collections.Add(posts);
workSpace.Collections.Add(images);
serviceDocument.Workspaces.Add(workSpace);
var response = new HttpResponseMessage(HttpStatusCode.OK);
var formatter = new AtomPub10ServiceDocumentFormatter(serviceDocument);
var stream = new MemoryStream();
using (var writer = XmlWriter.Create(stream))
{
formatter.WriteTo(writer);
}
stream.Position = 0;
var content = new StreamContent(stream);
response.Content = content;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atomsvc+xml");
return response;
}
}
The http GET Request generate the follow XML:
<?xml version="1.0" encoding="utf-8"?>
<app:service
xmlns:a10="http://www.w3.org/2005/Atom"
xmlns:app="http://www.w3.org/2007/app">
<app:workspace xml:base="http://localhost:53644/">
<a10:title type="text">Nicoloco Site</a10:title>
<app:collection href="http://localhost:53644/api/blogapi">
<a10:title type="text">Nicoloco Blog</a10:title>
<app:accept>application/atom+xml;type=entry</app:accept>
<app:categories href="http://localhost:53644/api/tags?format=atomcat" />
</app:collection>
<app:collection href="http://localhost:53644/api/images">
<a10:title type="text">Images Blog</a10:title>
<app:accept>image/png</app:accept>
<app:accept>image/jpeg</app:accept>
<app:accept>image/jpg</app:accept>
<app:accept>image/gif</app:accept>
</app:collection>
</app:workspace>
</app:service>
But I can't publish images using this service.
Best regards.
I found my error on "categories line", WLW log file shows a malformed XML error in this line, I removed it and all works fine for me... in this blog post explains how WLW Works with image files
If somebody have any comment... I'll be grateful
I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.
However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.
Here is my Action Method
public FileStreamResult Export(){
var results = _service.GetProperties().Take(3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter txt = new System.IO.StreamWriter(ms);
CsvFileDescription inputFileDescription = new CsvFileDescription{
SeparatorChar =',',
FirstLineHasColumnNames = true
}
;
CsvContext csv = new CsvContext();
csv.Write(results,txt,inputFileDescription);
return File(ms , "application/x-excel");
}
I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.
Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.
Calling the Web API method to return CVS file from JavaScript.
public HttpResponseMessage Bidreport([FromBody]int formData).....
Fill in your IEnumerable<YourObject>query = from LINQ query
....
This is how to return it:
using (var ms = new MemoryStream())
{
using (TextWriter txt = new StreamWriter(ms))
{
var cc = new CsvContext();
cc.Write(query, txt, outputFileDescription);
txt.Flush();
ms.Position = 0;
var fileData = Encoding.ASCII.GetString(ms.ToArray());
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
return result;
}
}