Trouble Getting HttpResponse data with AngularJS $http.post - angularjs

I am try to return a custom object from VB.NET code behind to a AngularJS HTTP Post. Based on the user requests, this object could be very large. Very, very large. Whenever that happened, I got a OutOfMemoryException when trying to serialize it. Therefore, I am now using the JSON.NET package from Newtonsoft to serialze it using a StringWriter:
Using sw As New StringWriter()
Using writer As JsonWriter = New JsonTextWriter(sw)
Dim serializer As New JsonSerializer()
serializer.Serialize(writer, periodData)
writer.Flush()
End Using
End Using
While this works, when I then try to do sw.ToString I still get that OutOfMemoryException.
So, I trawled through the internet and I believe I can use a StreamWriter sent to a HttpResponse object and then flush the response to return it to the web client call. However, I cannot figure out how to do this.
Any help? Or if I am way off track, give me a better way to do this?
Update 1
Apparently, I cannot use HttpResponse in a Using statement because I get a "using operand must implement system.idisposable" error. So now I am having trouble creating an HttpResponse object in the WebMethod. Passing both TextWriter and HttpWriter as params for the constructor give me errors.
Update 2
Okay, so I am no longer getting an OutOfMemoryException when trying to serialize the object. However, I believe I am doing something wrong since my StreamWriter doesn't seem to be writing to the HttpResponse Object. This is my current code:
Dim response As HttpResponse = HttpContext.Current.Response()
response.ContentType = "application/json"
response.Clear()
response.BufferOutput = True
Using sw As New StreamWriter(response.OutputStream, System.Text.Encoding.UTF8)
Using writer As JsonWriter = New JsonTextWriter(sw)
Dim serializer As New JsonSerializer()
serializer.Serialize(writer, periodData)
writer.Flush()
End Using
sw.Flush()
End Using
response.Flush()
Then when I pause my JavaScript in the Chrome developer console, the response object is just an empty string. The javascript is just a basic Angular $http.post call:
$http.post('url.aspx/GetData', angular.toJson({
param1: data1,
param2: data2,
param3: data3
})).then(function (response) {
//Do stuff with response which is currently an empty string.
}
I don't believe my VB.NET code is correct. Help?

It's not quite clear from your question where you are, but it looks like you are having trouble constructing a StreamWriter to write into a HttpResponse.
You can get the response object from the HttpContext:
[WebMethod]
public static void YourServiceMethod()
{
HttpResponse response = HttpContext.Current.Response;
// ... now go on
}
The response object has a property OutputStream that you can give to the constructor of StreamWriter (in a using statement), like in this answer to another question:
using (TextWriter textWriter = new StreamWriter(response.OutputStream, System.Text.Encoding.UTF8))
{
// ... now write your data
}
(Excuse me giving C# samples, that's what I am much more familiar with.)

Related

MicroOrm.Dapper.Repositories SqlGenerator param - where to get that?

Im trying to use the MicroOrm.Dapper.Repositories but the usage sample left me hanging on where to get the SqlGenerator object. It's sample documentation is:
public UserRepository(IDbConnection connection, ISqlGenerator<User> sqlGenerator)
: base(connection, sqlGenerator)
{
Amy I using this right:
var conn = new MySqlConnection("connectionStringXYZ");
var generator = new SqlGenerator<User>();
var userRepo = new UserRepository(conn, generator);
which gives me internal server error 500.
You should be able to do:
ISqlGenerator<User> userSqlGenerator = new SqlGenerator<User>(ESqlConnector.MySQL);
Preferably the generator should be a singleton, possibly an injected one.
But your error is an http error, so I suppose you are swallowing the real exception somewhere in your application. Find out the underlying reason.

Making JAX RS CXF Interceptors work with WebClient

I am having a problem making interceptors fire when using the WebClient class (org.apache.cxf.jaxrs.client.WebClient). In my method that calls a RESTful service I have added an interceptor to execute in the out phase. I have intentionally provided invalid properties so I can see the interceptor fail, but the method completes successfully.
Here is the code that I am working with:
private String callService2(String webServiceUrl) {
JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
bean.setAddress(webServiceUrl);
// setup properties
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("ws-security.signature.username", "client");
properties.put("ws-security.signature.properties",
"client_nonexistantfile.properties");
bean.setProperties(properties);
XmlSigOutInterceptor sigInterceptor = new XmlSigOutInterceptor();
bean.getOutInterceptors().add(sigInterceptor);
// use WebClient (or proxy) as usual
WebClient wc = bean.createWebClient();
TestInfoResponse response = wc.accept("application/xml").get(TestInfoResponse.class);
return response.getContents();
}
I am expecting the XmlSigOutInterceptor logic to fail because the properties file does not exist, but the method completes successfully. What am I doing wrong when adding the XmlSigOutInterceptor.
Thanks in advance.
This is my bad. the XmlSigOutInterceptor does not need to do anything when a get is performed because there is no document to sign. So the interceptor was firing, it just returned right away.
Sorry for the noise.

JAX-RS with CXF / rest-assured: Handling multiparam file upload

I want to upload a JPG file and a JSON-serialized Java object. On the server I am using Apache CXF, on the client I am integration testing with rest-assured.
My server code looks like:
#POST
#Path("/document")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response storeTravelDocument(
#Context UriInfo uriInfo,
#Multipart(value = "document") JsonBean bean,
#Multipart(value = "image") InputStream pictureStream)
throws IOException
{}
My client code looks like:
given().
multiPart("document", new File("./data/json.txt"), "application/json").
multiPart("image", new File("./data/image.txt"), "image/jpeg").
expect().
statusCode(Response.Status.CREATED.getStatusCode()).
when().
post("/document");
Everything works fine when I read the json part from the file as in the first multiPart line. However, when I want to serialize the json instance I come into problems. I tried many variants, but none worked.
I thought this variant should work: on the client
JsonBean json = new JsonBean();
json.setVal1("Value 1");
json.setVal2("Value 2");
given().
contentType("application/json").
formParam("document", json).
multiPart("image", new File("./data/image.txt"), "image/jpeg").
...
and on the server
public Response storeTravelDocument(
#Context UriInfo uriInfo,
#FormParam(value = "document") JsonBean bean,
#Multipart(value = "image") InputStream pictureStream)
but no. Can anyone tell me how it should be?
Try different approach (worked for me), I am not sure if this is suitable in your case.
Make JsonBean a JAXB entity, that it add #XmlRootEntity above class definition.
Then, instead of formParam
given().
contentType("application/json").
body(bean). //bean is your JsonBean
multiPart("image", new File("./data/image.txt"), "image/jpeg").
then
public Response storeTravelDocument(
#Context UriInfo uriInfo,
JsonBean bean, //should be deserialized properly
#Multipart(value = "image") InputStream pictureStream)
I've never tried that with #Multipart part, but, hopefully it would work.
Multipart/form-data follows the rules of multipart MIME data streams, see w3.org. This means that each part of the request forms a part in the stream. Rest-assured supports already simple fields (strings), files and streams, but not object serialization into a part. After asking on the mailing list, Johan Haleby (the author of rest-assured) suggested to add an issue. The issue is already accepted, see issue 166.
The server will stay as it is:
#POST
#Path("/document")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response storeTravelDocument(
#Context UriInfo uriInfo,
#Multipart(value = "document") JsonBean bean,
#Multipart(value = "image") InputStream pictureStream)
throws IOException
{}
The client code will look like:
given().
multiPartObject("document", objectToSerialize, "application/json").
multiPart("image", new File("./data/image.txt"), "image/jpeg").
expect().
statusCode(Response.Status.CREATED.getStatusCode()).
when().
post("/document");
Maybe the name "multiPartObject" will change. We will see once it is implemented.

Using BlobRequest.CopyFrom fails with 404 Not Found error

Hope you can help.
I'm trying to copy a blob using the Protocol namespace along with a shared access signature, but the WebResponse always throws a 404 Not Found error. I have successfully used the Get/Post/Delete/List methods (where the 404 would be thrown if the permissions were insufficient), but I cannot find the answer here.
Here's some simple code that I am using:
Uri uriFrom = new Uri("file://mymachine/myfile.txt");
Uri uriTo = new Uri("file://mymachine/myfile1.txt");
//get shared access signature - set all permissions for now
uriTo = GetSharedAccessSignature(uriTo, SharedAccessPermissions.Write |
SharedAccessPermissions.Read | SharedAccessPermissions.List);
//NOTE: This returns my uriTo object in the following format:
//http://mystoragespace.blob.core.windows.net/mycontainer/steve1.txt?se=2011-07-04T12:17:18Z&sr=b&sp=rwdl&sig=sxhGBkbDJpe9qn5d9AB7/d2LK1aun/2s5Bq8LAy8mis=
//get the account name
string accountName = uriTo.Host.Replace(".blob.core.windows.net", string.Empty);
//build the canonical string
StringBuilder canonicalName = new StringBuilder();
canonicalName.AppendFormat(System.Globalization.CultureInfo.InvariantCulture,
"/{0}/mycontainer{1}", accountName, uriFrom.AbsolutePath);
//NOTE: my canonical string is now "/mystoragespace/mycontainer/myfile.txt"
//get the request
var request = BlobRequest.CopyFrom(uriTo, 300, canonicalName.ToString(),
null, ConditionHeaderKind.None, null, null);
request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
//perform the copy operation
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//do nothing. the file has been copied
}
So, my uriTo seems to have the appropriate permissions (I've tried various combinations) and the canonical string seems to have the correct source string. I'm not using snapshot functionality. The proxy isn't a problem as I've successfully used other methods.
Hope someone can help...
Many regards,
Steve
From Creating a Shared Access Signature:
The following table details which operations are allowed on a resource for a given set of permissions.
...
Create or update the content, block list, properties, and metadata of the specified blob. Note that copying a blob is not supported.

Windows Phone 7 App Quits when I attempt to deserialize JSON

I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.

Resources