Пример #1
0
        private void BuildBatchRequestContent(IAsyncResult asyncResult)
        {
            MixpanelRequestState state   = (MixpanelRequestState)asyncResult.AsyncState;
            HttpWebRequest       request = state.Request;

            // No timeout available on HttpWebRequest object, using a signal instead.
            state.Completed = new ManualResetEvent(false);
            try
            {
                Stream stream = request.EndGetRequestStream(asyncResult);
                byte[] data   = Encoding.UTF8.GetBytes(state.RequestData);
                // Write to the request stream.
                stream.Write(data, 0, data.Length);
                stream.Flush();
                stream.Close();
            }
            catch (Exception ex)
            {
                state.Error  = ex;
                state.Result = "0";
                state.Completed.Set();
                return;
            }

            state.Completed.Reset();
            request.BeginGetResponse(new AsyncCallback(RequestCompleted), state);
        }
Пример #2
0
        private void RequestCompleted(IAsyncResult asyncResult)
        {
            MixpanelRequestState state = (MixpanelRequestState)asyncResult.AsyncState;

            try
            {
                HttpWebRequest request = state.Request;
                state.Response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                if ((int)state.Response.StatusCode >= 400)
                {
                    state.Error  = new WebException("HTTP Error");
                    state.Result = "0";
                }
                else
                {
                    // API sends 0 or 1 as response, it's safe to read stream in a single shot.
                    using (Stream stream = state.Response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream, Utilities.DefaultEncoding);
                        state.Result = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                state.Error  = ex;
                state.Result = "0";
            }
            finally
            {
                if (state.Completed != null)
                {
                    state.Completed.Set();
                }
            }
        }
Пример #3
0
        private async Task <bool> SendBatch(string endpointName, string data, IDictionary <string, string> uriParameters)
        {
            if (string.IsNullOrEmpty(endpointName))
            {
                throw new ArgumentException("String cannot be null or empty.", "endpointName");
            }

            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentException("String cannot be null or empty.", "data");
            }

            if (uriParameters == null)
            {
                throw new ArgumentNullException("uriParameters");
            }

            string requestUri = BaseUrl + endpointName + "/?ip=1";// +"&verbose=1";

            foreach (KeyValuePair <string, string> kvp in uriParameters)
            {
                if (string.IsNullOrEmpty(kvp.Key) || string.IsNullOrEmpty(kvp.Value))
                {
                    continue;
                }

                requestUri += "&" + Utilities.UrlEncode(kvp.Key) + "=" + Utilities.UrlEncode(kvp.Value);
            }

            // Ensure built-in cache is bypassed by passing a bogus changing parameter
            requestUri += "&ms-ts=" + (DateTime.UtcNow.Ticks / 10000);
            string requestData = "data=" + Utilities.ToBase64(data);

#if WINDOWS_PHONE
            HttpWebRequest request = HttpWebRequest.CreateHttp(requestUri);
            request.UserAgent   = UserAgent;
            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            MixpanelRequestState state = new MixpanelRequestState();
            state.Request     = request;
            state.RequestData = requestData;
            IAsyncResult asyncResult = request.BeginGetRequestStream(new AsyncCallback(BuildBatchRequestContent), state);
            state = (MixpanelRequestState)asyncResult.AsyncState;
            await Task.Run(() =>
            {
                bool completed = false;
                if (state.Completed != null)
                {
                    completed = state.Completed.WaitOne(MaxTimeout * 1000);
                }
                if (!completed || !asyncResult.IsCompleted)
                {
                    // Timeout
                    request.Abort();
                    throw new WebException("Timeout");
                }

                if (state.Error != null)
                {
                    throw state.Error;
                }
            });

            string result = null;
            if (state.Result != null)
            {
                result = state.Result.ToString();
            }
#else
            TimeSpan timeout = TimeSpan.FromSeconds(MaxTimeout);
            if (_httpClient.Timeout != timeout)
            {
                _httpClient.Timeout = timeout;
            }

            string result;
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri))
            {
                request.Headers.Add("User-Agent", UserAgent);
                request.Content = new StringContent(requestData);
                request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                using (HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Content == null)
                    {
                        return(false);
                    }

                    result = await response.Content.ReadAsStringAsync();
                }
            }
#endif
            return(Utilities.ToBoolean(result, false));
        }
Пример #4
0
        private async Task <bool> Send(string endpointName, string data, IDictionary <string, string> uriParameters)
        {
            if (string.IsNullOrEmpty(endpointName))
            {
                throw new ArgumentException("String cannot be null or empty.", "endpointName");
            }

            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentException("String cannot be null or empty.", "data");
            }

            if (uriParameters == null)
            {
                throw new ArgumentNullException("uriParameters");
            }

            string encodedData = Utilities.ToBase64(data);

            string requestUri = BaseUrl + endpointName + "/?";

            requestUri += (IsGeolocationEnabled) ? "ip=1" : "ip=0";
            if (IsVerboseEnabled)
            {
                requestUri += "&verbose=1";
            }
            requestUri += "&data=" + encodedData;
            foreach (KeyValuePair <string, string> kvp in uriParameters)
            {
                if (string.IsNullOrEmpty(kvp.Key) || string.IsNullOrEmpty(kvp.Value))
                {
                    continue;
                }

                requestUri += "&" + Utilities.UrlEncode(kvp.Key) + "=" + Utilities.UrlEncode(kvp.Value);
            }

#if WINDOWS_PHONE
            // Ensure built-in cache is bypassed by passing a bogus changing parameter
            requestUri += "&ms-ts=" + (DateTime.UtcNow.Ticks / 10000);
            HttpWebRequest request = HttpWebRequest.CreateHttp(requestUri);
            request.UserAgent = UserAgent;

            MixpanelRequestState state = new MixpanelRequestState();
            state.Request = request;
            // No timeout available on HttpWebRequest object, using a signal instead.
            state.Completed = new ManualResetEvent(false);
            state.Completed.Reset();

            IAsyncResult asyncResult = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(RequestCompleted), state);
            state = (MixpanelRequestState)asyncResult.AsyncState;
            await Task.Run(() =>
            {
                bool completed = false;
                if (state.Completed != null)
                {
                    completed = state.Completed.WaitOne(MaxTimeout * 1000);
                }
                if (!completed || !asyncResult.IsCompleted)
                {
                    // Timeout
                    request.Abort();
                    throw new WebException("Timeout");
                }

                if (state.Error != null)
                {
                    throw state.Error;
                }
            });

            string result = state.Result.ToString();
#else
            TimeSpan timeout = TimeSpan.FromSeconds(MaxTimeout);
            if (_httpClient.Timeout != timeout)
            {
                _httpClient.Timeout = timeout;
            }

            string result;
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                request.Headers.Add("User-Agent", UserAgent);
                using (HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Content == null)
                    {
                        return(false);
                    }

                    result = await response.Content.ReadAsStringAsync();
                }
            }
#endif
            return(Utilities.ToBoolean(result, false));
        }