Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey everyone I'm in the process of writing a Windows phone 8 that is a copy of a clients iOS application. I need to be able to send a get request with custom header entries. Using Windows 8 this is easy, however using Windows PHONE 8 I have been having trouble.

Here is what i have:

C#
WebRequest myClient = WebRequest.Create(_devApiUrl + "session/" + _entityKey);

myClient.Headers["Host"] = _host;
myClient.ContentType = "text/json";
myClient.Method = "GET";


myClient.BeginGetResponse(ReadWebRequestCallback, myClient);


and then just trying to get a response I have this:

C#
private void ReadWebRequestCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;

            if (myRequest != null)
            {
                try
                {
                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
                }
                catch (WebException e)
                {
                    return;
                }
            }
        }


When I execute this code here is what i get:

An exception of type 'System.Net.ProtocolViolationException' occurred in System.Windows.ni.dll but was not handled in user code


I'm really not sure what I need to do here. Any help is greatly appreciated!
Posted

1 solution

Hi =)
*First of all you must deal with Async pattern more carefully !!
* Coding the way like you did , how correct to say - is old school ;)
However , let's fix your problem,i'm going to resolve it with help of third-party tool called Rx (Reactive extension for WP).

So, let's define few helper methods :

C#
public static IObservable ToResponse(this WebRequest request)
{
    var asyncGetResponse = Observable.FromAsyncPattern(
                            request.BeginGetResponse, request.EndGetResponse);

    return Observable.Defer(asyncGetResponse);
}


C#
public static IObservable ToBytes(this Stream stream)
{
    return
        Observable.Create(
            observer =>
            {
                byte[] buffer = new byte[24];

                var obsReadFactory = Observable.Defer(() => stream.AsReader()(buffer, 0, buffer.Length));

                return Observable
                         .Repeat(obsReadFactory)
                         .Select(i => buffer.Take(i).ToArray())

                         // Subscribe on the thread pool, otherwise the repeat operator will operate during the
                         // call to subscribe, preventing the whole expression to complete properly
                         .SubscribeOn(Scheduler.ThreadPool)

                         .Subscribe(
                             _ =>
                             {
                                 if (_.Length > 0)
                                 {
                                     observer.OnNext(_);
                                 }
                                 else
                                 {
                                     observer.OnCompleted();
                                 }
                             },
                             observer.OnError,
                             observer.OnCompleted
                         );
            }
        );
}


And the last thing that remain , is to deal with WebRequest and proper request for it

C#
string url = _devApiUrl + "session/" + _entityKey;
var webRequest = WebRequest.Create(url);
webRequest.Headers["Host"] = _host;
webRequest.ContentType = "text/json";
webRequest.Method = "GET";

webRequest.ToResponse()
          .SelectMany(wr => wr.GetResponseStream().ToBytes())
          .ForEach(b => {
                  //Do some stuff with bytes for example get strings 
                  string data=  Encoding.Default.GetString(b);
                  }));
 
Share this answer
 
v2
Comments
r83h 27-Dec-12 11:49am    
This looks like a great way to do it, however I'm having trouble adding reactive extensions. I have installed from: http://msdn.microsoft.com/en-us/data/gg577610 and then I added a reference to: Reactive Extensions for Windows Phone 8. I have also added "using System.Reactive" at the top of the code file. However it appears I can't just have Iobservable without a type and there is now Observable.FromAsyncPattern. Your help is greatly appreciated!
Oleksandr Kulchytskyi 27-Dec-12 11:53am    
What about
using System.Reactive.Linq ??
r83h 27-Dec-12 14:25pm    
well I added that and now I get this: The call is ambiguous between the following methods or properties: 'System.Reactive.Linq.Observable.FromAsyncPattern(System.Func<system.asynccallback,object,system.iasyncresult>, System.Action<system.iasyncresult>)' and 'System.Reactive.Linq.Observable.FromAsyncPattern<system.net.webresponse>(System.Func<system.asynccallback,object,system.iasyncresult>, System.Func<system.iasyncresult,system.net.webresponse>)'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900