0

I want to send one pre request to my server before send every request. From that pre request I will receive the token from my server and than I have to add that token into all the request. This is the process.

I have try with some methods to achieve this. But I am facing one problem. That is, When I try to send pre request, it is processing with the current request. That mean both request going parallel.

I want to send pre request first and parse the response. After parsing the pre request response only I want to send that another request. But first request not waiting for the pre request response. Please let me any way to send pre request before all the request.

This is my code:

ViewModel:

`public class ListExampleViewModel
    {
        SecurityToken sToken = null;
        public ListExampleViewModel()
        {
            GlobalConstants.isGetToken = true;
            var listResults = REQ_RESP.postAndGetResponse((new ListService().GetList("xx","xxx")));

            listResults.Subscribe(x =>
            {
                Console.WriteLine("\n\n..................................2");
                Console.WriteLine("Received Response==>" + x);
            });
        }
    }`

Constant Class for Request and Response:

`public class REQ_RESP
    {
        private static string receivedAction = "";
        private static string receivedPostDate = "";


        public static IObservable<string> postAndGetResponse(String postData)
        {
            if (GlobalConstants.isGetToken)
            {
    //Pre Request for every reusest               
                receivedPostDate = postData;
                GlobalConstants.isGetToken = false;
                getServerTokenMethod();
                postData = receivedPostDate;
            }

            HttpWebRequest serviceRequest =
            (HttpWebRequest)WebRequest.Create(new Uri(Constants.SERVICE_URI));


            var fetchRequestStream =
                 Observable.FromAsyncPattern<Stream>(serviceRequest.BeginGetRequestStream,
                                                                 serviceRequest.EndGetRequestStream);
            var fetchResponse =
                Observable.FromAsyncPattern<WebResponse>(serviceRequest.BeginGetResponse,
                                                            serviceRequest.EndGetResponse);

            Func<Stream, IObservable<HttpWebResponse>> postDataAndFetchResponse = st =>
            {
                using (var writer = new StreamWriter(st) as StreamWriter)
                {
                    writer.Write(postData);
                    writer.Close();
                }
                return fetchResponse().Select(rp => (HttpWebResponse)rp);
            };

            Func<HttpWebResponse, IObservable<string>> fetchResult = rp =>
            {
                if (rp.StatusCode == HttpStatusCode.OK)
                {

                    using (var reader = new StreamReader(rp.GetResponseStream()))
                    {
                        string result = reader.ReadToEnd();
                        reader.Close();
                        rp.GetResponseStream().Close();
                        XDocument xdoc = XDocument.Parse(result);
                        Console.WriteLine(xdoc);
                        return Observable.Return<string>(result);
                    }
                }
                else
                {
                    var msg = "HttpStatusCode == " + rp.StatusCode.ToString();
                    var ex = new System.Net.WebException(msg,
                        WebExceptionStatus.ReceiveFailure);
                    return Observable.Throw<string>(ex);
                }

            };

            return
                from st in fetchRequestStream()
                from rp in postDataAndFetchResponse(st)
                from str in fetchResult(rp)
                select str;
        }

        public static void getServerTokenMethod()
        {
            SecurityToken token = new SecurityToken();

            var getTokenResults = REQ_RESP.postAndGetResponse((new ServerToken().GetServerToken()));

            getTokenResults.Subscribe(x =>
            {
                ServerToken serverToken = new ServerToken();
                ServiceModel sm = new ServiceModel();
    //Parsing Response
                serverToken = extract(x, sm);
                if (!(string.IsNullOrEmpty(sm.NetErrorCode)))
                {
        MessageBox.Show("Show Error Message");
                }
                else
                {
                    Console.WriteLine("\n\n..................................1");
                    Console.WriteLine("\n\nserverToken.token==>" + serverToken.token);
                    Console.WriteLine("\n\nserverToken.pk==>" + serverToken.pk);                   
                }
            },
            ex =>
            {
                MessageBox.Show("Exception = " + ex.Message);
            },
            () =>
            {
                Console.WriteLine("End of Process.. Releaseing all Resources used.");
            });
        }
    }`
Vijay
  • 3,152
  • 3
  • 24
  • 33

1 Answers1

0

Here's couple options:

You could replace the Reactive Extensions model with a simpler async/await -model for the web requests using HttpClient (you also need Microsoft.Bcl.Async in WP7). With HttpClient your code would end up looking like this:

Request and Response:

        public static async Task<string> postAndGetResponse(String postData)
    {
        if (GlobalConstants.isGetToken)
        {
            //Pre Request for every reusest               
            await getServerTokenMethod();
        }

        var client = new HttpClient();
        var postMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(Constants.SERVICE_URI));
        var postResult = await client.SendAsync(postMessage);

        var stringResult = await postResult.Content.ReadAsStringAsync();

        return stringResult;
    }

Viewmodel:

    public class ListExampleViewModel
{
    SecurityToken sToken = null;
    public ListExampleViewModel()
    {
        GetData();
    }

    public async void GetData()
    {
        GlobalConstants.isGetToken = true;
        var listResults = await REQ_RESP.postAndGetResponse("postData");
    }
}

Another option is, if you want to continue using Reactive Extensions, to look at RX's Concat-method. With it you could chain the token request and the actual web request: https://stackoverflow.com/a/6754558/66988

Community
  • 1
  • 1
Mikael Koskinen
  • 12,306
  • 5
  • 48
  • 63
  • Hi I try to follow your first option. But I can not do that. I am facing some error. `The type or namespace name 'async' could not be found (are you missing a using directive or an assembly reference?)`. I am searching for the solution for this error. And I found one answer [From this Link].(http://stackoverflow.com/questions/16557032/how-to-use-async-with-visual-studio-2010-and-net-4-0). I conclude myself this is not possible. Now I am trying with your second option. But I don't know where I have to add that methods. If possible please let me any way to solve my problem. – Vijay Feb 28 '15 at 11:56
  • Hi @Mikael Koskinen.. Finally I found the solution. I used **o1().SelectMany(_ => o2()).Subscribe();** for my solution and do somw changes in my code. Now I can send pre request..!! Thanks you very much.. – Vijay Mar 02 '15 at 11:11