Amazon Product advertising c# api - c#

Hi guys I'm having trouble fetching products from amazon web api.
I have used this code from the internet, adding all the neccessary references. I tried adding a view and chose itemsearchresponce as the model class but it does not display the product, I get the following error:
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type 'AmazonProduct.com.amazon.webservices.ImageSet' to
'AmazonProduct.com.amazon.webservices.ImageSet[]'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AmazonProduct.com.amazon.webservices;
namespace Forest.Controllers
{
public class AmazonController : Controller
{
private AmazonProduct.com.amazon.webservices.AWSECommerceService _Products;
public AmazonController()
{
_Products = new AmazonProduct.com.amazon.webservices.AWSECommerceService();
}
[HttpGet]
public ActionResult listProducts()
{
var searchIndex = "Shoes";
var keywords = "jordan";
// Create an ItemSearch wrapper
ItemSearch search = new ItemSearch();
search.AssociateTag = "[Your Associate ID]";
search.AWSAccessKeyId = "MyKey";
// search.Version= "2011-08-01";
// Create a request object
ItemSearchRequest request = new ItemSearchRequest();
// Fill the request object with request parameters
request.ResponseGroup = new string[] { "ItemAttributes" };
// Set SearchIndex and Keywords
request.SearchIndex = searchIndex;
request.Keywords = keywords;
// Set the request on the search wrapper
search.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = _Products.ItemSearch(search);
return View(response);
}
}
}

Go to the generated proxy and replace ImageSet[][] with ImageSet[].
Also take a look at Amazon Product Advertising API C# if you already haven't.

Related

REST Api Put Request Problem (RestSharp) to Netapp REST Api. Getting always "Invalid JSON input"

In my C# app I access a NetApp REST API. I am using RestSharp to access the API. No problem with Get requests. However when I try a Put request I alwas get: "Invalid JSON input. Unexpected character in stream: r around 0:0."
Added: I'm stuck with RestSharp version 105.2.3 because of other dependencies. Its a huge application and moving to a newer version of RestSharp would need changes in several modules as well as moving to another .Net version. AddStringBody method would maybe help, but is not present in the version I am using.
The method called, prepares and sends the request, as well as checks the result.
internal bool CreateQtree(Pool pool, BaseStorageConf storageConf, RestClientCustom server) {
bool isOk = false;
// Prepare request query parameters.
var request = new RestRequest("storage/qtrees");
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
request.AddParameter("return_records", "false");
request.AddParameter("return_timeout", 15);
// Prepare body.
PostCreateQTree CreateQTreePost = new PostCreateQTree();
CreateQTreePost.Name = pool.Name;
CreateQTreePost.SecurityStyle = "unix";
CreateQTreePost.Svm = new Svm();
CreateQTreePost.Svm.Name = storageConf.FileServer;
CreateQTreePost.Volume = new Volume();
CreateQTreePost.Volume.Name = storageConf.FileSystem;
// Assure that null values are not serialized.
JsonSerializerSettings setting = new JsonSerializerSettings();
setting.NullValueHandling = NullValueHandling.Ignore;
// Using this serializer makes sure that the JsonProperty are honored.
string body = JsonConvert.SerializeObject(CreateQTreePost, setting);
request.AddParameter("application/json", body, ParameterType.RequestBody);
// Execute request.
var response = server.Execute(request);
// Handle results.
if (response.StatusCode == HttpStatusCode.OK) {
// Creation of the qtree was successfull.
TheLogger.Instance.Error(string.Format("Qtree could be created. Pool: {0}", pool.Name));
isOk = true;
} else {
// There was an error, dump.
ResponseError ErrorResponse = JsonConvert.DeserializeObject<ResponseError>(response.Content);
TheLogger.Instance.Error(string.Format("Qtree could not be created. Pool: {0}, code: {1}, message: {2}", pool.Name, ErrorResponse.Error.Code, ErrorResponse.Error.Message));
}
return isOk;
}
The RestClientCustom is only to allow debugging, when working against the productive system.
using Logging;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Devices.NetAppREST {
internal class RestClientCustom:RestClient {
private readonly bool mIsDebugMode;
internal RestClientCustom(string baseUrl, bool isDebugMode): base(baseUrl) {
mIsDebugMode = isDebugMode;
}
internal RestClientCustom(Uri baseUrl, bool isDebugMode) : base(baseUrl) {
mIsDebugMode = isDebugMode;
}
public IRestResponse Execute(RestRequest request) {
IRestResponse response;
TheLogger.Instance.Debug(string.Format("REST URI:\r\n{0}", base.BuildUri(request)));
TheLogger.Instance.Debug(string.Format("Parameters:\r\n{0}", ParameterToString(request)));
if (mIsDebugMode) {
response = new RestResponse();
response.StatusCode = HttpStatusCode.OK;
return response;
} else {
response = base.Execute(request);
}
TheLogger.Instance.Debug(string.Format("StatusCode:\r\n{0}", response.StatusCode));
TheLogger.Instance.Debug(string.Format("Content:\r\n{0}", response.Content));
TheLogger.Instance.Debug(string.Format("Headers:\r\n{0}", response.Headers));
TheLogger.Instance.Debug(string.Format("ResponseURI:\r\n{0}", response.ResponseUri));
TheLogger.Instance.Debug(string.Format("ErrorMessage:\r\n{0}", response.ErrorMessage));
return response;
}
internal String ParameterToString(RestRequest request) {
var sb = new StringBuilder();
foreach (var param in request.Parameters) {
sb.AppendFormat("Name: {0}, Value: {1}, Type: {2}\r\n", param.Name, param.Value, param.Type.ToString());
}
return sb.ToString();
}
}
}
The Post JSON is created with the following class.
using Newtonsoft.Json;
namespace Devices.NetAppREST {
public class PostCreateQTree {
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("security_style")]
public string SecurityStyle { get; set; }
[JsonProperty("svm")]
public Svm Svm { get; set; }
[JsonProperty("volume")]
public Volume Volume { get; set; }
}
}
I use a Newtonsoft.Json serializer in order to get the correct naming in the body JSON, as well als filter null values. An example looks as follows ...
{"name":"G-IPH-TestPoolCreate","security_style":"unix","svm":{"name":"sy-fs-301"},"volume":{"name":"g"}}
I can take this JSON string and post it via curl, powershell or test it on the target system directly and it works. However when I use the RestSharp implementation, I get above error.
I tried the normal serializer. But it does not generate the correct JSON (capitals). I added the JSON string directly as parameter in the code, no luck. Now I use the Newtonsoft.Json serializer. But I do not think the serialization is the problem. In the debugger I see the parameters and the URI passed in the request object. They seem ok.
I suppose I am missing something. A hint would be appreciated.
If found the solution ... In the method CreateQtree I used to add to query parameters.
request.AddParameter("return_records", "false");
request.AddParameter("return_timeout", 15);
When I add them more sprecific ...
request.AddParameter("return_records", "false", ParameterType.QueryString);
request.AddParameter("return_timeout", 15, ParameterType.QueryString);
It works. It seems the two parameters are not added correctly if I do not specify them as query parameters.

Error while trying to integrate Twilio in .NET Core MVC Application

I'm trying to integrate Twilio with my ASP.NET Core MVC Application but in the controller, I'm getting an error in my return statement.
**Cannot implicitly convert type 'System.Web.Mvc.ContentResult' to 'Microsoft.AspNetCore.Mvc.ContentResult'
**
Controller Code
using Microsoft.AspNetCore.Mvc;
using System.Configuration;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
using Twilio.TwiML;
namespace TwilioTesting.Controllers
{
public class SMSController : TwilioController
{
public ContentResult Index()
{
var accountSid = "AC12345678";
var authToken = "12345678";
TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("+92313887998");
var from = new PhoneNumber("+19898980625");
var message = MessageResource.Create(
to: to,
from: from,
body: "Message from Kamran");
return Content(message.Sid);
}
}
}
You have a using Twilio.AspNet.Mvc; import which is not for .NET Core & is for ASP.NET MVC. It is unexpectedly importing in System.Web.Mvc.ContentResult which is conflicting with the import of Microsoft.AspNetCore.Mvc.ContentResult.
Remove it and replace it with using Twilio;.

Sending text message to phone using twilio

I am trying to send text message to phone. Can someone tell me why my return statement is not working? If i write only string message in my return statement then it shows that message but if i use below mentioned return statement it doesn't work. Any suggestions?
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioSendSMS.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS ----- outbound----
public ActionResult SendSms()
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "ACxxxxxxxxx";
const string authToken = "71xxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// make an associative array of people we know, indexed by phone number
var people = new Dictionary<string, string>() {
{"+18180000000", "Kim"},
{"+14401112222", "Raj"}
};
// Iterate over all our friends
foreach (var person in people)
{
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("+15005550006"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber(person.Key), // To number, if using Sandbox see note above
// Message content
body: $"Hey {person.Value} Party is at 6PM! Don't forget to bring gift.");
}
//return Content($"Message has been sent!");
return Content($"Sent message to {person.Value}");
}
}
}
Below is the working code!
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioSendSMS.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS ----- outbound----
public ActionResult SendSms()
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "ACxxxxxxxxx";
const string authToken = "71xxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// make an associative array of people we know, indexed by phone number
var people = new Dictionary<string, string>() {
{"+18180000000", "Kim"},
{"+14401112222", "Raj"}
};
// Iterate over all our friends
var name ="";
foreach (var person in people)
{
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("+15005550006"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber(person.Key), // To number, if using Sandbox see note above
// Message content
body: $"Hey {person.Value} Party is at 6PM! Don't forget to bring gift.");
name = $"{name} {person.Value}";
}
return Content($"Sent message to {name}");
}
}
}

How to create VMs using google compute engine REST API

I am new to Google Compute Engine. Some one please help me with creating Google Compute Engine VMs programmatically using REST APIs in C#.
Here [1] you can found the API documentation to create an instance and at the bottom of the document the C# examples [2]:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Services;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using Data = Google.Apis.Compute.v1.Data;
namespace ComputeSample
{
public class ComputeExample
{
public static void Main(string[] args)
{
ComputeService computeService = new ComputeService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "Google-ComputeSample/0.1",
});
// Project ID for this request.
string project = "my-project"; // TODO: Update placeholder value.
// The name of the zone for this request.
string zone = "my-zone"; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
Data.Instance requestBody = new Data.Instance();
InstancesResource.InsertRequest request = computeService.Instances.Insert(requestBody, project, zone);
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
Data.Operation response = request.Execute();
// Data.Operation response = await request.ExecuteAsync();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
public static GoogleCredential GetCredential()
{
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
}
return credential;
}
}
}
[1] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
[2] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert#examples

Content Negotiation in ASP.NET Web API

I'm migrating a web service to ASP.NET Web Api 2, and hitting trouble at almost the first hurdle.
I want to do this:
public class SomeController : ApiController
{
[Route("some\url")]
public object Get()
{
return { Message = "Hello" };
}
}
And be able to ask the service for either "application/json" or "application/xml" (or indeed any other potential format, such as Message Pack), and get a serialized response. But it seems it only works for JSON.
I've read this and seen the documentation which states clearly that the framework cannot handle serialization of anonymous types into XML (seriously) and that the solution is to not use XML (seriously).
When I attempt to call this and request XML as response type, I get
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
I'm not removing support for clients wanting to ask for XML - but I genuinely can't find a work around for this - what can I do?
Edit
I've added these:
System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
config.Formatters.Insert(0, new System.Net.Http.Formatting.XmlMediaTypeFormatter());
as per Dalorzo's answer, but it made no difference.
For clarification, the service works absolutely fine when I call it using an accept header of application/json, but bombs when I call it with an accept header of application/xml.
You have 3 options:
Create a class with a proper name and return the object instead of an anonymous type.
Or if you want to return the anonymous instance, you should remove XML formatter, because anonymous types are not supported by XML Formatter
Create your own formatter inheriting from MediaTypeFormatter or BufferedMediaTypeFormatter
You can do it by following code :
public HttpResponseMessage GetTestData()
{
var testdata = (from u in context.TestRepository.Get().ToList()
select
new Message
{
msgText = u.msgText
});
return ActionContext.Request.CreateResponse(HttpStatusCode.OK, testdata);
}
// This Code Is Used To Change Contents In Api
public HttpResponseMessage GetAllcarDetails( string formate)
{
CarModel ST = new CarModel();
CarModel ST1 = new CarModel();
List<CarModel> li = new List<CarModel>();
ST.CarName = "Maruti Waganor";
ST.CarPrice = 400000;
ST.CarModeles = "VXI";
ST.CarColor = "Brown";
ST1.CarName = "Maruti Swift";
ST1.CarPrice = 500000;
ST1.CarModeles = "VXI";
ST1.CarColor = "RED";
li.Add(ST);
li.Add(ST1);
// return li;
this.Request.Headers.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));
//For Json Use "application/json"
IContentNegotiator negotiator =
this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(
typeof(List<CarModel>), this.Request, this.Configuration.Formatters);
if (result == null) {
var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
throw new HttpResponseException(response);
}
return new HttpResponseMessage() {
Content = new ObjectContent<List<CarModel>>(
li, // What we are serializing
result.Formatter, // The media formatter
result.MediaType.MediaType // The MIME type
)
};
}
Please browse your API route on Chrome. Chrome, by default shows output in XML format. If that doesn't happen, it means that your service is preventing XML format using media formatting.
And in that case, you should search your WebApiConfig. If nothing is present there, add this file to your project
using System.Net.Http.Formatting;
using System.Collections.Generic;
using System.Net.Http;
using System;
using System.Linq;
using System.Net.Http.Headers;
namespace ExampleApp.Infrastructure
{
public class CustomNegotiator : DefaultContentNegotiator
{
public override ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
if(request.Headers.UserAgent.Where(x=>x.Product!=null&& x.Product.Name.ToLower().Equals("chrome")).Count() > 0)
{
return new ContentNegotiationResult(new JsonMediaTypeFormatter(), new MediaTypeHeaderValue("application/xml"));
}
else
{
return base.Negotiate(type, request, formatters);
}
}
}
}
and, in WebApiConfig.cs, add:
config.Services.Replace(typeof(IContentNegotiator), new CustomNegotiator());

Categories