How to create #FormDataParam dynamically for dynamic file uploads - file-upload

I just need to receive multiple image or file with some text data from client side to server. I am using java restful web services with spring hibernate integration. My controller is like..
#Path("/receiveFiles")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String receiveFile(#FormDataParam("file1") InputStream f1, #FormDataParam("file2") InputStream f2 ){
UtilityMethods.saveImageFile(f1, "fileName.png");
return null;
}
My front end is html,css and java script. so the file can be uploaded through FormData() but the receiving side is a problem. I just need a solution to get files dynamically at same request. Thanks in advance.

Related

Testing Azure Blob Storage SDK

I found this great Getting Started Guide for the Azure Blob Storage SDK and how to connect to my storage account.
A quick prototype showed that it already works, but I want to ensure this and the logic behind it via tests (either unit or integration tests).
I found this resource on an Azure Testing Library that can record HTTP requests of a pipeline and was wondering whether this is applicable to the Blob Storage SDK as well?
Are there any other options to properly test my applications code interaction with the Blob Storage SDK?
My idea would for example be:
Call a method on my client with a parameter
Take the blob name from the passed parameter and make a call to the blob storage container
Validate that the call was made to the correct container and blob via a test case
• I too just tried to follow the documentation link for various tasks to be performed regarding the Azure Blob storage using the .Net v12 SDK and the results were successful as follows: -
Also, if you want to call a method/task on your client/application using a parameter with respect to Blob storage, you can surely do so by using the ‘BlobServiceClient’ class. To know more on how to use it, please refer to the documentation link below: -
https://azure.github.io/azure-sdk-korean/dotnet_introduction.html
It clearly states on how to call the service name client and the methods for which to use the parameters for performing various tasks as shown in the sample code from that document below: -
namespace Azure.<group>.<service_name> {
// main service client class
public class <service_name>Client {
// simple constructors; don't use default parameters
public <service_name>Client(<simple_binding_parameters>);
public <service_name>Client(<simple_binding_parameters>, <service_name>ClientOptions options);
// 0 or more advanced constructors
public <service_name>Client(<advanced_binding_parameters>, <service_name>ClientOptions options = default);
// mocking constructor
protected <service_name>Client();
// service methods (synchronous and asynchronous)
public virtual Task<Response<<model>> <service_operation>Async(<parameters>, CancellationToken cancellationToken = default);
public virtual Response<model> <service_operation>(<parameters>, CancellationToken cancellationToken = default);
// other members
}
// options for configuring the client
public class <service_name>ClientOptions : ClientOptions {
}
}
Also, I would suggest you to please refer this community thread: -
Call .NET Web API method whenever a new file is added to Azure Blob Storage

RESTful API Client

I am new to RESTful API client development. I have a got the sample client code to integrate to REST Server. Below is the the snap shoot of same.
public TsbPublishClient() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("publication");
}
public <T> T getJson(Class<T> responseType, String product, String version, String category) throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path(java.text.MessageFormat.format("registry/{0}/{1}/{2}", new Object[]{product, version, category}));
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
public void close() {
client.close();
}
My question is how do i invoke the getJson() method from my main class. The return type is T and it accepts responseType parameter which is of type Class <T>
Thanks in Advance.
I'm a bit surprised that you want to use JAX-WS to access a RESTful API. In this technology, a web service operation invocation is represented by an XML-based protocol such as SOAP.
There are several technologies to do a call to a RESTful applications. Here are two of them:
Restlet - a lightweight and robust Java REST framework that tackles both client and server sides.
JAX-RS (JSR 311: JAX-RS: The Java API for RESTful Web Services) - a standardized API to both consume and produce RESTful applications. Restlet provides an implementation of this specification.
Following code describes a sample of client with Restlet:
ClientResource cr = new ClientResource("http://(...)/contacts");
MyDataBean bean = cr.get(MediaType.APPLICATION_JSON);
Following code describes a sample of client with JAX-RS:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://(...)")
.path("contacts");
MyDataBean bean = target
.request(MediaType.APPLICATION_JSON_TYPE)
.get(MyDataBean.class);
Both tools can leverage content (JSON, XML, YAML, ...) / POJO conversion with for example Jackson.
Hope it helps you,
Thierry

How to Consume MVC 4 WebApi Service

I am new to Web Api world and I see a lot of potential for in the new MVC 4 Web Api. I have generated a WCF Web Service but was planning to get to know Web-APIs and their web service capabilities. Now, is MVC 4 Web-Api Service more as front end? I wrote a sample Service by following some examples online in MVC 4 Web Api but how do I consume the Service in just a basic console app? I have figured out the only way to consume it is by using HttpClient are there other ways? I am used to ASP.NET Web Service and WCF Web Service as where you reference it as a service in your references and then you are able to see all of its objects, properties to make appropriate calls.
What happens if web-api is requesting a object "Task" for post method as an example how am I able to fill an object "Task" and post it back to the web-api? As in WCF I am able to see that "Task" object and its properties because of WSDL so I am able to fill them and send it back to the service how is that done in web-api service?
The webservice would be used internally is it worth it to have an web-api service?
Thank you so much for helping clearing some question of what I have about web-api services.
---Edit as per Comment---
This screenshot shows a possible structure which you can approach. Of course, you can take a design that best suit your application.
So ControllerLib is a separate Class Library project which is brought into the main project as a Service Reference (which is not shown in the screenshot but should be inside the References folder of the SecondMVCApplication project). The two controller file (HomeController.cs and LocationController.cs is a controller file that implemented the Controller class, which is the same thing as a Controller file when you create a new MVC4 application using the template)
So for your question regarding if there is a SVC file. NO. In MVC 4, there is no such thing as a SVC file whether the application is one project or a combination of multiple project (unless I am mistaken). Inside the SecondMVCApplication, there is a file called RouteConfig.cs which holds the routing URL and as long as you add the Service Reference and there controller function exists. The code will run. Also the sample screenshot I showed also includes a WebApiConfig.cs file. You can use that file to do API stuff for mobile if you need. So, the regular RouteConfig.cs handles website request and the WebApiConfig.cs handles API request.
Good to Note: If you are using a Model project as a separate project (which I know you will as it is a M-V-C project...DUH!!). Make sure you put your connection string inside the web.config main project (in this case, the SecondMVCApplication). I remember I was stuck in this problem for 3 days (8 hours each) trying to fix this problem. Hope you don't run into it.
---End Edit---
The following answer to your question is mostly based on my knowledge and may or may not be true to all users.
Is MVC 4 Web-Api Service more as front end?
This depends on how you look at it. Typically, a Web-API service is more suited for creating back-end service to provide a data payload to different platforms, like mobile, desktop apps and so on. However, a MVC4 Internet Application will have front-end aspects in them, namely the Views, which end-users sees.
How do I consume the Service in just a basic console app?
AFAIK, there is two way to do this. One if to consume the APIs as a Service Reference. Another is to use HTTP operation (which I will mention in your question regarding the HTTP client and reserve this answer using the Service Reference method).
This depends on how your application is done. Like I said, if it is a website, your MVC pattern will not need to do anything, but the Models, Views and Controllers all are designed to work together without using any service.
Although, as I mentioned in the comments to the questions, if it is a big application then you will need to break them into different projects that will make the app modular and nimble. So you will end up creating different Service Library. If you go down the Service Library road, then you just make use of the Add Reference option to bring in your API/Projects/Whatever-you-call-it into the project. (For this, I normally put all project inside a single solution and let Visual Studio manage the build order as I am lazy to write up a build script).
Similarly, the same logic could be applied when consuming your web service in a console app.
I have figured out the only way to consume it is by using HttpClient are there other ways?
One way to consume web APIs is using HTTP. Are you aware of how to write http request headers and handle http response. If so, this is the second way I mentioned. You call the web service through it's URL and then get the data and do whatever work. If your answer to use http in console app is NO, then look at this post: Create HTTP post request and receive response using C# console application
What happens if web-api is requesting a object "Task" for post method as an example how am I able to fill an object "Task" and post it back to the web-api?
I think I indirectly answered this in your previous answer (assuming you are going to take the HTTP road). If not, then comment and I'll see if I can find some resource for you.
The webservice would be used internally is it worth it to have an web-api service?
I sort of answered this in the comment to the question. Ask if you need clarification.
Hope all this helps.
you can create your own Client Service class that will serve for every request.
public class ClientService
{
#region async helper methods
private static string m_mediaTypeHeaderValue= "application/json";
static HttpClient client = new HttpClient();
static HttpClient createHttpClientInstance()
{
return client ?? new HttpClient();
}
// SELECT
internal static async Task<T> Get<T>(string endpoint)
{
client= createHttpClientInstance();
var response = await client.GetAsync(endpoint);
string content = await response.Content.ReadAsStringAsync();
return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
}
// INSERT
static async Task<T> Post<T>(string endpoint, object data)
{
client = createHttpClientInstance();
var httpContent = new StringContent(JsonConvert.SerializeObject(data));
httpContent.Headers.ContentType = new MediaTypeHeaderValue(m_mediaTypeHeaderValue);
var response = await client.PostAsync(endpoint, httpContent);
string content = await response.Content.ReadAsStringAsync();
return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
}
// UPDATE
static async Task<T> Put<T>(string endpoint, object data)
{
client = createHttpClientInstance();
var httpContent = new StringContent(JsonConvert.SerializeObject(data));
httpContent.Headers.ContentType = new MediaTypeHeaderValue(m_mediaTypeHeaderValue);
var response = await client.PutAsync(endpoint, httpContent);
string content = await response.Content.ReadAsStringAsync();
return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
}
// DELETE
static async Task<T> Delete<T>(string endpoint)
{
client = createHttpClientInstance();
var response = await client.DeleteAsync(endpoint);
string content = await response.Content.ReadAsStringAsync();
return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
}
#endregion
}

Creating a WCF Web Api Client

I've been using the WCF Web Api recently and i've been using the WCF Web API Test Client that is built in to it to test my created webservices.
I am wanting to create a proxy in code built off of the interface rather than run svcutil.exe to create a proxy.
My webservice is working fine, however when I use fiddler to examine the message that is sent, it is putting in a namespace into the xml message.
Below is the code I use to send the request.
RegisterRequest registerRequest = new RegisterRequest
{
Email = "test#test.com",
Firstname = "firstname",
Lastname = "lastname",
Password = "password"
};
var factory = new ChannelFactory<IAccountApi>(new WebHttpBinding(), "http://localhost/WebServices/api/account");
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
var proxy = factory.CreateChannel();
proxy.Register(registerRequest);
This request below is generated via the client, and it fails, returning a 500 internal server error
<RegisterRequest xmlns="http://schemas.datacontract.org/2004/07/ServiceModel.Accounts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Email>test#test.com</Email><Firstname>firstname</Firstname><Lastname>lastname</Lastname><Password>password</Password></RegisterRequest>
Using the same headers when I send using the api test client the following message passes
<RegisterRequest><Email>test#test.com</Email><Firstname>firstname</Firstname><Lastname>lastname</Lastname><Password>password</Password></RegisterRequest>
The only difference being the namespace has been removed.
Some final points,
1) If I were able to remove this namespace the request would work
2) I am not sure if ChannelFactory can be used in conjunction with WCF Web Api. The reason being http://wcf.codeplex.com/releases/view/73423 states "[ServiceContract] is no longer required on the Web API class definition", yet Channel Factory requires it.
3) All the examples so far from the WCF Web API look like the following
HttpClient client = new HttpClient();
Contact contact = new Contact() { Name = name };
var response = client.Post("http://localhost:9000/api/contacts/",
new ObjectContent<Contact>(
contact, JsonMediaTypeFormatter.DefaultMediaType));
Should I be using HttpClient for my requests instead of channel factory?
Regards,
Andrew
It appears that the IAccountApi, which you do not show, is defining a namespace for the service contract. If you really want an empty namespace (not best practice) try something like this:
[ServiceContract(Namespace="")]
public interface IAccountApi
{ ... }
If the namespace is not defined for IAccountApi, check the [DataContract] of RegisterRequest.
I ended up using HttpClient class, it allows GET, POST, PUT and DELETE which was fine for WCF Web API (now called http://www.asp.net/web-api)
http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx
as far as building a rest proxy using codegen or being dynamic see this article
ReST Proxy Object Generator

Why am I having so much trouble uploading a file in WCF4?

This has stumped me now for over 4 hours. I can't find a simple example anywhere?
My web application has a WCF Data Service, I would love to be able to just upload an image to a custom operation on that.
Alternatively I have WCF REST TEMPLATE SERVICE that has only a .cs, NO .config to play with and NO .svc file. It does have a route in the global.asax
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("upload", new WebServiceHostFactory(), typeof(UploadService)));
My operation looks like this:
[WebInvoke(Method ="POST", UriTemplate = "update-pic/{id}")]
public Message UploadPic(string id, Stream fileContents)
{
System.Drawing.Image.FromStream(fileContents).Save(string.Format("{0:ddmmss}.jpg"));
return WebOperationContext.Current.CreateTextResponse("Success: " + id);
}
But no matter what I do on the client, when I call the service I get a 400 response. I could facing problems with message size limits, but I don't know how to configure this with the WCF RestTemplate style.
If I do not set the anything to the response stream, then I manage to hit the service.
Does anyone have an end to end service and client example for WCF4 - I'm not interested in 3.5