Get/Upload File in RESTful service

Get is simple, zero configuration rocks

This post explained how to get image from RESTful service very clearly, a nice thing of setup RESTful WCF service is no setting in web.config, so-called zero configuration.

Adding parameter is simple, just use UriTemplate.


        [OperationContract]
        [WebGet(UriTemplate = "image/{id}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
        Stream GetImage(string id);

Upload is tricky, override WebServiceHostFactory to increase MaxMessageSize for posting

Stream operation is fun! Question, do I really need to set ContentType for post?

400 bad request error means file is too large, default is 32k, needs to download RESTful starter kit to override WebServiceHostFactory to return customized WebServiceHost2.

Watch out the ture parameter in the middle of ctor, ignoring it will cause non-sense error message like this:

Service ‘RuntimeType’ implements multiple ServiceContract types, and no endpoints are defined in the configuration file. WebServiceHost can set up default endpoints, but only if the service implements only a single ServiceContract. Either change the service to only implement a single ServiceContract, or else define endpoints for the service explicitly in the configuration file.


 [Test]
 public void test_upload_image_using_file_stream()
 {
 string uri = "http://localhost/FileStorageService/FileGetService.svc/upload_file/2.jpg";
 var req = WebRequest.Create(uri) as HttpWebRequest;
 if (req != null)
 {
 req.Method = "POST";
//                req.ContentType = "application/pdf";  // optional?
 Stream reqStream = req.GetRequestStream();

 var pdfStream = new FileStream(@"c:\tmp\datasource_of_datagridview.JPG", FileMode.Open, FileAccess.Read);

 pdfStream.CopyTo(reqStream);

 reqStream.Close();

 var resp = (HttpWebResponse) req.GetResponse();
 var r = new XmlTextReader(resp.GetResponseStream());
 if (r.Read())
 {
 Console.WriteLine(r.ReadString());
 }
 }
 }

 /// <summary>
 /// To increase the default post message size limit from 32656.
 /// Must change svc from Factory="System.ServiceModel.Activation.WebServiceHostFactory" to Factory="FileStorageService.CustomWebServer"
 /// </summary>
 public class CustomWebServer : WebServiceHostFactory
 {
 private static readonly long MAX_MESSAGE_SIZE = 2048576;

 protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAdresses)
 {
 WebServiceHost2 result = new WebServiceHost2(serviceType, true, baseAdresses);
 result.MaxMessageSize = MAX_MESSAGE_SIZE;
 return result;
 }
 }

Classic WCF is a little bit different, passing bytes array instead of stream needs to increase MaxArrayLength

For people do not want to deal with web request/response, there is an non-RESTful file upload solution using classic WCF service, also works very well, while it is using byte type to pass file contents to server. I have tried to switch to stream but got error said

“[For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream.]”

Solution can be found here.

Debugging in silverlight is realy painful, unfriendly 404 error hides too many info away!

Advertisements

3 thoughts on “Get/Upload File in RESTful service

  1. e} special “secrets” I take advantage of to insure which the meeting media is going right. Go proper?You discover, the consumer has paid a lot of money for the actual video as well as multimedia piece that will aid the crowd remove the cobwebs (as well as hangovers) and obtain focused over the goals, spirit along with business within the meeting. I prefer my clientele to enjoy the video tutorial, and to get the client will like it is in the event the audience enjoys it.Well, you brings in Captain christopher Walken flying on air flow, and if your room is not really right, the audience will probably be distracted and therefore major section of genius your client contracted is going to be snoozed via, ignored, or poo-poo’d meant for reasons that have already nothing about the quality with the media.It’s all while in the room. It’s friends experience, and like in a movie theatre, many things agree to make the knowledge right.Tip Just one: Let your video be viewed.You have to make a theatrical knowledge. Using a good TV Track, or a large personal computer monitor for the purpose of audiences above 5 as well as 10 folks is folly.Video projectors are generally cheap to help rent as well as buy, and these help generate the movie theatre experience visitors expect. Remember, some people from the audience could possibly have better residential theaters compared to the environment people create.The hotel’s a-v tech will help, or ones staff a-v group member can help. Screens outset at 4×6 feet appeal to crowds if around 25 consumers; after that will, you’ll be considering 6×8, or for much bigger crowds, 12×16′ as well as larger (much wider than that will and you just aren’t reading this content, anyway.)Tip A couple of: The sound need to be as “BIG” because video.This well spoken even in case your meeting is definitely a product sales call concerning you in addition to a prospect in any closet-sized office environment. Sound is the best secret marker. Words has to be understood, music need to be felt, and emotions need to be driven– very much like in the flicks. Bring together those moveable speakers, or in a very larger getting together with, rent a very good stereo speakers to check your target audience is enveloped inside words as well as music everyone or your current producer designed.Tip A couple of: Control the actual lights.Imagine a movie theatre where that they leave typically the lights with. Pretty unique, right? Now think of your assembly. To boost the impact of one’s media, you will need the picture for being seen, and your current audience to sense at ease reacting for you to what’s for the screen. There’s very little room to get a person to help feel self-conscious on the subject of laughing, applauding, or possibly even crying. Only from the anonymity in the darkened area will many people truly respond to your note and internalize the nation’s meaning. Shutter typically the windows. Turn down florescent equipment and lighting (they’re a total meeting mindblowing). Slowly fade the bedroom lights because the video will begin.Tip 3: Rehearse.Run via the technical issues with what we now have discussed. Know if the video is meant to start, when your PowerPoint is said to be played, and training switching, dimming the particular lights, adjusting typically the sound (both equally in quantities and EQ), and switching relating to the inputs in case necessary. You don’t hopeful stumbling as an alternative for speaking, and for anyone who is behind the particular scenes, you you should not want that speaker labeling you out to be asleep in the switch (choosing nasty too if you happen to were departed hanging truth be told there with nothing to talk about or do as the a-v lad is farting around using the media behind the living room.)Tip 5: Use typically the Letterman impression.In brief, chill interior. David Letterman flows his studio room at 55 degrees. It retains him and even his customers sharp. I’m possibly not saying maintain it who cold, but assuming you have more rather than 50 individuals, you come with an audience that could be a walking central heater. Body Heating is realistic, and numerous bodies necessarily suggest a comfortable room. While home may feel comfortable back at 7: 00 have always been, at 8: 00 i am attendees may perhaps be sweltering, because one didn’t anticipate the room would probably warm. A heat room would mean sleepy audience. Sleepy audience don’t applaud, will not really retain an individual’s message, won’t have excited and / or enthused, or will not even maintain their big eyes open. When most people walk within the room, feel the family room. Is this slightly chilly you? Good. Is it again quite pleasant? Bad. And you should not wait right until it should get too popular. When you want to lower a temperature, the hotel room contact can be no where available, and no matter if they conduct grace you utilizing their presence, it will administer a decent hour to help “chill” the space. The wall space retain temperature. So conduct people.I know {the following pointers|these guidelines|the following tips|these pointers|the guidelines prese

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s