I can't seem to figure out how to include the CSV file content when calling the Swagger API generated methods for the Microsoft Cognitive Services Recommendations API method Uploadacatalogfiletoamodel(modelID, catalogDisplayName, accountKey);. I've tried setting the catalogDisplayName to the full path to the catalog file, however I'm getting "(EXT-0108) Passed argument is invalid."
When calling any of the Cog Svcs APIs that require HTTP body content, how do I include the body content when the exposed API doesn't have a parameter for the body?
I guess, Swagger can't help you testing functions that need to pass data thru a form. And I guess sending the CSV content in the form data shall do the trick, if you know the proper headers.
I work with nuGet called "Microsoft.Net.Http" and code looks like
HttpContent stringContent = new StringContent(someStringYouWannaSend);
HttpContent bytesContent = new ByteArrayContent(someBytesYouWannaSend);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "metadata", "metadata");
formData.Add(bytesContent, "bytes", "bytes");
HttpResponseMessage response = client.PostAsync(someWebApiEndPoint.ToString(), formData).Result;
if (!response.IsSuccessStatusCode)
{
return false; //LOG
}
string responseContent = response.Content.ReadAsStringAsync().Result;
jsonResult= JsonConvert.DeserializeObject<someCoolClass>(responseContent);
return true;
}
Sorry about that someVariables that can't compile. Hope you'll figure this out.
When you are basing your code on the Swagger definition you depend on the good will of the person that created that Swagger definition. Maybe it is not complete yet.
If you are working on C#, try looking at the Samples repo.
Particularly for the Uploading of the catalog there are several functions on the ApiWrapper class that might be helpful, one has this signature: public CatalogImportStats UploadCatalog(string modelId, string catalogFilePath, string catalogDisplayName), another has this other signature public UsageImportStats UploadUsage(string modelId, string usageFilePath, string usageDisplayName) (where it seems like you can point to a public url).
In your case I'd probably try the second one.
Download the sample and use the Wrapper code defined there in your project.
Related
I am using the following code to encode the SAMLRequest value to the endpoint, i.e. the XYZ when calling https://login.microsoftonline.com/common/saml2?SAMLRequest=XYZ.
Is this the correct way to encode it?
private static string DeflateEncode(string val)
{
var memoryStream = new MemoryStream();
using (var writer = new StreamWriter(new DeflateStream(memoryStream, CompressionMode.Compress, true), new UTF8Encoding(false)))
{
writer.Write(val);
writer.Close();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length, Base64FormattingOptions.None);
}
}
If you just want to convert string to a base64 encoded string, then you can use the following way:
var encoded = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(val));
Console.WriteLine(encoded);
return encoded;
Yes, that looks correct for the Http Redirect binding.
But don't do this yourself unless you really know what you are doing. Sending the AuthnRequest is the simple part. Correctly validating the received response, including guarding for Xml signature wrapping attacks is hard. Use an existing library, there are both commercial and open source libraries available.
I'm trying to consume a web service with the Web API client library. My problem is that the ReadAsAsync doesn't seem to want to fully deserailize the returned object when the submitting function uses a POST method.
If I get the response as a string and manually deserailize it works. (I get a apmsgMessage with all the fields populated)
HttpClient client = GetClient();
var response = client.PostAsJsonAsync("api/robot/Preview", ad).Result;
var msg = response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<apmsgMessage>(msg.Result);
I originally tried the code below which returns an apmsgMessage Object, but all the fields are null.
HttpClient client = GetClient();
var response = client.PostAsJsonAsync("api/robot/Preview", ad).Result;
var msg = response.Content.ReadAsAsync<apmsgMessage>().Result;
return msg;
My question is why dosn't my orginal (the PostAsJsonAsync) return a apmsgMessage fully populated. Am I doing somethign wrong with the ReadAsAsync?
I just had the same issue, and in my case I solved it by removing the [Serializable] attribute from the class.
I don't know why this attribute conflicts with the deserialization process, but as soon as I took that out, the ReadAsAsync method worked as expected.
Can i start by saying i am new to programming and SoapUI(more like a week old). i apologies in advance for asking the question(s) i am about to ask.
Problem
basically, i am trying to automate webservice.
I need to create xml using Groovy in soapui and send it as part of a request body to a webservice(REST not SOAP) and do some assertion on the response received. i will be sending quite a few request, hence the reason to automate.
My proposed solution (which i am not sure about)
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
class XmlGenerator {
// I created a class i.e. called XmlGenerator with a
// static method called GetXML() which looks like this:
public static def GetXML()
{
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.GetDMessage() //creating the xml message
{
PrescribedItems
{
PrescribedMethod(xml,'Some Value','Some Value','Some Value')
PrescribedItem
{
PrescribedMethod(xml,'Some Value','Some Value','Some Value')
}
}
}
return writer
}
// This method creates the XML needed but then i need to
// pass the xml generated to a request boy; so i
//create another method within the same class:
static def postXML(String baseUrl, String path)
{
def RequestBody = XmlGenerator.GetXML() // i am not sure if this will work
try
{
def ret = null
def http = new HTTPBuilder(baseUrl)
http.request(Method.POST, ContentType.XML)
{
uri.path = path
body = RequestBody
}
}
catch (groovyx.net.http.HttpResponseException ex)
{
ex.printStackTrace()
return null
}
catch (java.net.ConnectException ex)
{
ex.printStackTrace()
return null
}
}
}
Summary
A class called XmlGenerator() with 2 methods; GetXML() (used to generate XML ) and postXML() (Used to send XML generated by GetXML() to the Webservice.)
Questions
How can i make sure that this 2 methods ( GetXML() and postXML() ) are used by other request messages i.e. do i need to import the groovy scripte.g. do i do an import ... GroovyScriptName , if yes, please how?
How can i create create the xml and run the request in subsequent request messages. For instance;
do i do this; XmlGenerator() gen = new XmlGenerator(), then do gen.GetXML() and gen.postXML() to create and run the request. Also, what role can testRunner play in all this
Running the code currently throws up HTTPBuilder, ContentType , Method can not be resolved even though i have imported them in the script (see above)
Finally, what role can property play in building this framework? bearing in mind that the each request will be independent from the other request i.e. nothing is been passed around from one request to the other during test execution
You can specify the REST request you are testing using standard soapui functionality, as outlined here:
http://www.soapui.org/REST-Testing/getting-started.html
Follow the steps in the above page to create a:
New REST Service
New REST Resource
New REST Method
Then you can add a REST Test Step to your Test Case that invokes that request.
You can then insert a Groovy Test Step before the REST Test Step to build your xml body; here's a simple example of building a XML string:
import groovy.xml.MarkupBuilder
context.writer = new StringWriter()
def xml = new MarkupBuilder(context.writer)
xml.books() {
book(name:'blue ocean') {
format ('paperback')
year ('2010')
}
book(name:'quicksilver') {
format ('hardback')
year ('2011')
}
}
Note that the XML is assigned to a context variable (context.writer). This makes it available for use in subsequent steps within the scope of the Test Case for the duration of the test run.
Then, insert the following code into the body of your REST Test Step:
${=context.writer}
Finally, you have the option of adding Assertions within the REST Test Step; here's some information on that:
http://www.soapui.org/Functional-Testing/getting-started-with-assertions.html
ServiceStack services are great for responding with the content type that's requested in the Accept header. But if I need to close/end the response early from within a request filter, is there a way to respond with the proper content type? All I have access to in a request filter is the raw IHttpResponse so it seems to me that the only option is to tediously, manually check the Accept header and do a bunch of switch/case statements to figure out which serializer to use and then write directly to the response.OutputStream.
To further illustrate the question, in a normal service method you can do something like this:
public object Get(FooRequest request)
{
return new FooResponseObject()
{
Prop1 = "oh hai!"
}
}
And ServiceStack will figure out what content type to use and which serializer to use. Is there anything similar to this that I can do within a request filter?
ServiceStack pre-calculates the Requested Content-Type on a number of factors (e.g. Accept: header, QueryString, etc) it stores this info in the httpReq.ResponseContentType property.
You can use this along with the IAppHost.ContentTypeFilters registry which stores a collection of all Registered Content-Type serializers in ServiceStack (i.e. built-in + Custom) and do something like:
var dto = ...;
var contentType = httpReq.ResponseContentType;
var serializer = EndpointHost.AppHost
.ContentTypeFilters.GetResponseSerializer(contentType);
if (serializer == null)
throw new Exception("Content-Type {0} does not exist".Fmt(contentType));
var serializationContext = new HttpRequestContext(httpReq, httpRes, dto);
serializer(serializationContext, dto, httpRes);
httpRes.EndServiceStackRequest(); //stops further execution of this request
Note: this just serializes the Response to the Output stream, it does not execute any other Request or Response filters or other user-defined hooks as per a normal ServiceStack request.
I want to embed an UIWebView into my MonoTouch application for an area that is not yet implemented natively.
In order to authenticate with the website I want to set a cookie containing a key for the current session.
I tried creating a NSDictionary with the properties for the Cookie and then create a new NSHttpCookie and add it to the NSHttpCookieStorage.SharedStorage.
Sadly the cookie seems to be empty and not used for the request.
An example of how to build be cookie with properties and a comment on whether or not this is the simplest way to do this would be greatly appreciated.
Following Anuj's bug report I felt bad about how many lines of code were required to create the cookies. So the next MonoTouch versions will have new constructors for NSHttpCookie, similar to System.Net.Cookie that will allow you do to something like:
// this ctor requires all mandatory parameters
// so you don't have to guess them while coding
var cookie = new NSHttpCookie ("iherd", "ulikecookies", "/", "yodawg.com");
You'll even be able to create a NSHttpCookie from a .NET System.Net.Cookie.
Note: Never hesitate to fill a bug report when an API proves to be way more complicated than it should be :-)
Whenever I need to send cookies and params up to the server I use something like RestSharp or Hammock and then pass the response.Content value into UIWebView's loadHtmlString method:
//setup cookies and params here
var response = client.Execute(req);
_webView = new UIWebView();
_webView.LoadHtmlString(response.Content, new NSUrl(baseUrl));
The NSDictionary API is fairly trivial too:
var props = new NSMutableDictionary ();
props.Add (NSHttpCookie.KeyOriginURL, new
NSString("http://yodawg.com"));
props.Add (NSHttpCookie.KeyName, new NSString("iherd"));
props.Add (NSHttpCookie.KeyValue, new NSString("ulikecookies"));
props.Add (NSHttpCookie.KeyPath, new NSString("/"));
AFAIK every application has its own cookie storage so try to use this code before rendering the page in the UIWebView
NSHttpCookie cookie = new NSHttpCookie()
{
Domain = "yourdomain.com",
Name = "YourName",
Value = "YourValue" //and any other info you need to set
};
NSHttpCookieStorage cookiejar = NSHttpCookieStorage.SharedStorage;
cookiejar.SetCookie(cookie);
I'm not in a MAC right now so im not able to test it hope this helps
okay sorry, i wasn't able to test it before posting, anyways I won't get home until tonight so give this a spin
var objects = new object[] { "http://yoururl.com", "CookieName", "CookieValue", "/" };
var keys = new object[] { "NSHTTPCookieOriginURL", "NSHTTPCookieName", "NSHTTPCookieValue", "NSHTTPCookiePath" };
NSDictionary properties = (NSDictionary) NSDictionary.FromObjectsAndKeys(objects, keys);
NSHttpCookie cookie = NSHttpCookie.CookieFromProperties(properties);
NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
As you stated above, in the case that doesn't work might be a bug on monotouch binding so you can bind it manually by doing this
var objects = new object[] { "http://yoururl.com", "CookieName", "CookieValue", "/" };
var keys = new object[] { "NSHTTPCookieOriginURL", "NSHTTPCookieName", "NSHTTPCookieValue", "NSHTTPCookiePath" };
NSDictionary properties = (NSDictionary) NSDictionary.FromObjectsAndKeys(objects, keys);
NSHttpCookie cookie = (NSHttpCookie) Runtime.GetNSObject(Messaging.IntPtr_objc_msgSend_IntPtr(new Class("NSHTTPCookie").Handle, new Selector("cookieWithProperties:").Handle, properties.Handle))
NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
also don't forget to include using MonoTouch.ObjCRuntime; if manually binding it
if manually binding works please don't forget to post a bug report on https://bugzilla.xamarin.com/
Alex
I’ve wrote the NSMutableURLRequest+XSURLRequest catagory and XSCookie class to do this;-) http://blog.peakji.com/cocoansurlrequest-with-cookies/
This might give you a lead. Previously I used a similar strategy to make a
WebRequest to a site and collect cookies which were stored in the .Net/Mono CookieStore. Then when loading a url in the UIWebView I copied those cookies over to the NSHttpCookieStorage.
public NSHttpCookieStorage _cookieStorage;
/// <summary>
/// Convert the .NET cookie storage to the iOS NSHttpCookieStorage with Login Cookies
/// </summary>
void DotNetCookieStoreToNSHttpCookieStore()
{
foreach (Cookie c in _cookies.GetCookies(new Uri(UrlCollection["Login"], UriKind.Absolute))) {
Console.WriteLine (c);
_cookieStorage.SetCookie(new NSHttpCookie(c));
}
}