Example #1
0
        /// <summary>
        /// Send file to create asset (image or video)
        /// </summary>
        /// <param name="itemToSend">Byte array of the file</param>
        /// <param name="fileName">File's name</param>
        /// <param name="contentType">File's content type </param>
        /// <returns></returns>
        public async Task <string> PostFileAssetAsync(byte[] itemToSend, string fileName, string contentType)
        {
            string resultJson = string.Empty;
            string parameters = $"/api/{this.ApiVersion}file_asset";

            try
            {
                HttpClient        request     = new HttpClient();
                var               content     = new HttpMultipartFormDataContent();
                HttpBufferContent itemContent = new HttpBufferContent(itemToSend.AsBuffer());
                itemContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(contentType);
                content.Add(itemContent, "file_upload", fileName);
                using (HttpResponseMessage response = await request.PostAsync(new Uri(this.HttpLink + parameters), content))
                {
                    resultJson = await response.Content.ReadAsStringAsync();
                }

                if (!resultJson.Equals(string.Empty))
                {
                    return(JsonConvert.DeserializeObject <string>(resultJson));
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"[Device = {this.Name}; IP = {this.IpAddress}] Error while sending file.", ex);
            }
            return(null);
        }
Example #2
0
        /// <summary>
        /// Flash a compiled firmware to a device
        /// A return of true only means it was sent to the device, not that flash is successful
        /// </summary>
        /// <param name="deviceId">Device ID</param>
        /// <param name="firmwareStream">Stream of compiled binary</param>
        /// <param name="filename">Filename of compiled binary</param>
        /// <returns>Returns true if binary is sent to device</returns>
        public override async Task <bool> DeviceFlashBinaryAsync(string deviceId, Stream firmwareStream, string filename)
        {
            if (deviceId == null)
            {
                throw new ArgumentNullException(nameof(deviceId));
            }
            if (firmwareStream == null)
            {
                throw new ArgumentNullException(nameof(firmwareStream));
            }

            using (IHttpContent file = new HttpStreamContent(firmwareStream.AsInputStream()))
            {
                file.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/octet-stream");

                var content = new HttpMultipartFormDataContent();
                content.Add(new HttpStringContent("binary"), "file_type");
                content.Add(file, "file", filename);

                try
                {
                    var responseContent = await PutDataAsync($"{ParticleCloud.ParticleApiVersion}/{ParticleCloud.ParticleApiPathDevices}/{deviceId}", content);

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Flash a compiled firmware to a device
        /// A return of true only means it was sent to the device, not that flash is successful
        /// </summary>
        /// <param name="firmwareStream">Stream of compiled binary</param>
        /// <param name="filename">Filename of compiled binary</param>
        /// <returns>Returns true if binary is sent to device</returns>
        public async Task <bool> FlashBinaryAsync(Stream firmwareStream, string filename)
        {
            if (firmwareStream == null)
            {
                throw new ArgumentNullException(nameof(firmwareStream));
            }

            State      = ParticleDeviceState.Flashing;
            isFlashing = true;

            using (IHttpContent file = new HttpStreamContent(firmwareStream.AsInputStream()))
            {
                file.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/octet-stream");

                var content = new HttpMultipartFormDataContent();
                content.Add(new HttpStringContent("binary"), "file_type");
                content.Add(file, "file", filename);

                try
                {
                    onlineEventListenerID = await SubscribeToDeviceEventsWithPrefixAsync(CheckForOnlineEvent);

                    var responseContent = await particleCloud.PutDataAsync($"{ParticleCloud.ParticleApiVersion}/{ParticleCloud.ParticleApiPathDevices}/{Id}", content);

                    isFlashing = false;
                    return(true);
                }
                catch
                {
                    isFlashing = false;
                    State      = ParticleDeviceState.Unknown;
                    return(false);
                }
            }
        }
Example #4
0
        public static IHttpContent CreateHttpContentFromString(string jsonString, HttpMethod method)
        {
            var content = new HttpStringContent(jsonString);

            content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(method == HttpMethod.Patch ? "application/json-patch+json" : "application/json");
            return(content);
        }
            public async Task <HttpRequestMessage> Create(string uri)
            {
                // TODO: ETag support required??
                // TODO: choose rational timeout values
                var request = HttpRequestHelper.CreateHttpWebRequest(uri, false);


                //request.AllowWriteStreamBuffering = _allowWriteStreamBuffering;

                if (_etag != null && _etag.Length != 0)
                {
                    request.Headers["If-match"] = _etag;
                }

                await _parent._requestFilter(request);

                using (Stream inS = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var streamContent = new HttpStreamContent(inS.AsInputStream());
                    streamContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(MimeHelper.GetContentType(Path.GetExtension(_filename)));
                    if (_parent._options != null && _parent._options.SupportsSlug)
                    {
                        request.Headers["Slug"] = Path.GetFileNameWithoutExtension(_filename);
                    }

                    request.Method = new HttpMethod(_method);
                }

                return(request);
            }
        public async Task <AccessToken> GetAccessToken(string pin)
        {
            String TwitterUrl = "https://api.twitter.com/oauth/access_token";

            string timeStamp = GetTimeStamp();
            string nonce     = GetNonce();

            String SigBaseStringParams = "oauth_consumer_key=" + consumerKey;

            SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
            SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
            SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
            SigBaseStringParams += "&" + "oauth_token=" + requestToken;
            SigBaseStringParams += "&" + "oauth_version=1.0";
            String SigBaseString = "POST&";

            SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

            String Signature = GetSignature(SigBaseString, consumerSecret);

            HttpStringContent httpContent = new HttpStringContent("oauth_verifier=" + pin, Windows.Storage.Streams.UnicodeEncoding.Utf8);

            httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
            string authorizationHeaderParams = "oauth_consumer_key=\"" + consumerKey + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(requestToken) + "\", oauth_version=\"1.0\"";

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", authorizationHeaderParams);
            var httpResponseMessage = await httpClient.PostAsync(new Uri(TwitterUrl), httpContent);

            string response = await httpResponseMessage.Content.ReadAsStringAsync();

            String[] Tokens             = response.Split('&');
            string   oauth_token_secret = null;
            string   access_token       = null;
            string   screen_name        = null;

            for (int i = 0; i < Tokens.Length; i++)
            {
                String[] splits = Tokens[i].Split('=');
                switch (splits[0])
                {
                case "screen_name":
                    screen_name = splits[1];
                    break;

                case "oauth_token":
                    access_token = splits[1];
                    break;

                case "oauth_token_secret":
                    oauth_token_secret = splits[1];
                    break;
                }
            }

            return(new AccessToken(access_token, oauth_token_secret, screen_name));
        }
Example #7
0
        //  This is called from Execute Async
        private HttpRequestMessage ConfigureHttp(IRestRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("IRestRequest parameter was null");
            }

            //if(string.IsNullOrEmpty(request.Resource))
            //{
            //    throw new ArgumentException("There was no URI Specified in request.Resource");
            //}

            Uri requestUri = BuildUri(request);
            //  Create HttpRequest message based on request
            HttpRequestMessage reqMessage = new HttpRequestMessage(ConvertHttpMethod(request.Method), requestUri);

            //   Look for request parameter type of RequestBody
            var reqBody = (from p in request.Parameters
                           where p.Type == ParameterType.RequestBody
                           select p).FirstOrDefault();

            //  Only Support JSON Right now for Windows Universal
            if (reqBody != null && request.RequestFormat == DataFormat.Json)
            {
                object            val = reqBody.Value;
                HttpStringContent content;
                if (val is byte[])
                {
                    content = new HttpStringContent(Encoding.UTF8.GetString((byte [])val, 0, ((byte [])val).Length));
                }
                else
                {
                    content = new HttpStringContent(val.ToString());
                }

                content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/json");
                reqMessage.Content          = content;
            }


            // Copy Headers from request.Parameters to request message
            var headers = from p in request.Parameters
                          where p.Type == ParameterType.HttpHeader
                          select new HttpHeader
            {
                Name  = p.Name,
                Value = p.Value.ToString()
            };

            foreach (var header in headers)
            {
                reqMessage.Headers.Add(header.Name, header.Value);
            }

            return(reqMessage);
        }
Example #8
0
        public async void requestByPostJSON(string url, string json) {
            Uri uri = new Uri(url);
            HttpStringContent content = new HttpStringContent(json);

            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");
            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);
            string rta = await response.Content.ReadAsStringAsync();
            httpRta.setRta(rta);
        }
        /// <summary>
        /// Handle the request.
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <returns><see cref="ModuleResult.Stop"/> will stop all processing except <see cref="IHttpModule.EndRequest"/>.</returns>
        /// <remarks>Invoked in turn for all modules unless you return <see cref="ModuleResult.Stop"/>.</remarks>
        public ModuleResult HandleRequest(IHttpContext context)
        {
            // only handle GET and HEAD
            if (context.Response.RequestMessage.Method != HttpMethod.Get &&
                context.Response.RequestMessage.Method != HttpMethod.Head)
            {
                return(ModuleResult.Continue);
            }

            var date = context.Response.RequestMessage.Headers.IfModifiedSince.GetValueOrDefault(DateTime.MinValue).UtcDateTime;

            FileContext fileContext = new FileContext(context.RouteUri, date);

            _fileService.GetFileAsync(fileContext);
            //var test = await _fileService.GetFile(fileContext);


            if (!fileContext.IsFound)
            {
                return(ModuleResult.Continue);
            }

            if (!fileContext.IsModified)
            {
                context.Response.StatusCode   = HttpStatusCode.NotModified;
                context.Response.ReasonPhrase = "Was last modified " + fileContext.LastModified.ToString("R");
                return(ModuleResult.Stop);
            }

            var mimeType = MimeTypeProvider.Instance.Get(fileContext.File.Name);

            if (mimeType == null)
            {
                context.Response.StatusCode   = HttpStatusCode.UnsupportedMediaType;
                context.Response.ReasonPhrase = string.Format("File type '{0}' is not supported.",
                                                              Path.GetExtension(fileContext.File.Name));
                return(ModuleResult.Stop);
            }
            context.Response.Content = new HttpStreamContent(fileContext.FileContent);
            context.Response.Content.Headers.Add("Last-Modified", fileContext.LastModified.ToString("R"));
            //context.Response.Headers.Add("Accept-Ranges", "bytes");
            context.Response.Content.Headers.Add("Content-Disposition", "inline;filename=\"" + Path.GetFileName(fileContext.File.Name) + "\"");
            context.Response.Content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(mimeType);
            //context.Response.Content.Headers.ContentLength = (ulong)fileContext.FileContent.Length;


            // do not include a body when the client only want's to get content information.
            if (context.Response.RequestMessage.Method == HttpMethod.Head && context.Response.Content != null)
            {
                context.Response.Content.Dispose();
                context.Response.Content = null;
            }
            return(ModuleResult.Stop);
        }
Example #10
0
        public async void requestByPostForm(string url, List<KeyValuePair<String, String>> form) {
            Uri uri = new Uri(url);
            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(form);

            HttpMediaTypeHeaderValue contentType = 
                new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);
            string rta = await response.Content.ReadAsStringAsync();
            httpRta.setRta(rta);
        }
Example #11
0
        public async void insertDocument(T document)
        {
            JsonSerializerSettings property = new JsonSerializerSettings();

            property.NullValueHandling = NullValueHandling.Ignore;
            String                   json        = JsonConvert.SerializeObject(document, Formatting.None, property);
            HttpStringContent        content     = new HttpStringContent(json);
            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");

            content.Headers.ContentType = contentType;
            await client.PostAsync(new Uri(url), content);
        }
Example #12
0
        public async Task <string> requestByFormPost(string url, List <KeyValuePair <string, string> > form)
        {
            Uri uri = new Uri(url);
            HttpFormUrlEncodedContent content     = new HttpFormUrlEncodedContent(form);
            HttpMediaTypeHeaderValue  contentType = new HttpMediaTypeHeaderValue("application/x-www-urlencoded");

            content.Headers.ContentType = contentType;
            HttpResponseMessage response = await client.PostAsync(uri, content);

            string rta = await response.Content.ReadAsStringAsync();

            return(rta);
        }
Example #13
0
        public async void updateDocument(T document, String id)
        {
            String urlUpdate = URL_BASE + dbName + "/collections/" + collectionName + "/" + id + "?" + this.apiKey;
            JsonSerializerSettings property = new JsonSerializerSettings();

            property.NullValueHandling = NullValueHandling.Ignore;
            String                   json        = JsonConvert.SerializeObject(document, Formatting.None, property);
            HttpStringContent        content     = new HttpStringContent(json);
            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");

            content.Headers.ContentType = contentType;
            await client.PutAsync(new Uri(url), content);
        }
Example #14
0
        public async Task <string> requestByJsonPost(string url, string json)
        {
            Uri uri = new Uri(url);
            HttpStringContent        content     = new HttpStringContent(json);
            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");

            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);

            string rta = await response.Content.ReadAsStringAsync();

            return(rta);
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="buffer">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(IBuffer buffer, HttpMediaTypeHeaderValue contentType)
        {
            if (buffer.Length == 0)
            {
                throw new ArgumentOutOfRangeException("buffer");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }

            Content     = new HttpBufferContent(buffer);
            ContentType = contentType;
        }
Example #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="content">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(IHttpContent content, HttpMediaTypeHeaderValue contentType)
        {
            if (content == null)
            {
                throw new NullReferenceException("content");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }

            Content     = content;
            ContentType = contentType;
        }
Example #17
0
        public async void requestByPostJSON(string url, string json)
        {
            Uri uri = new Uri(url);
            HttpStringContent content = new HttpStringContent(json);

            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");

            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);

            string rta = await response.Content.ReadAsStringAsync();

            httpRta.setRta(rta);
        }
Example #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="content">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(string content, string contentType)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentException("content");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }

            Content     = new HttpStringContent(content, UnicodeEncoding.Utf8, contentType);
            ContentType = HttpMediaTypeHeaderValue.Parse(contentType);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="content">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(IHttpContent content, HttpMediaTypeHeaderValue contentType)
        {
            if (content == null)
            {
                throw new NullReferenceException("content");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }

            Content = content;
            ContentType = contentType;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="buffer">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(IBuffer buffer, HttpMediaTypeHeaderValue contentType)
        {
            if (buffer.Length == 0)
            {
                throw new ArgumentOutOfRangeException("buffer");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }
            
            Content = new HttpBufferContent(buffer);
            ContentType = contentType;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentResult"/> class.
        /// </summary>
        /// <param name="content">The body content.</param>
        /// <param name="contentType">The content type header.</param>
        public ContentResult(string content, HttpMediaTypeHeaderValue contentType)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentException("content");
            }

            if (contentType == null)
            {
                throw new ArgumentException("contentType");
            }
            
            Content = new  HttpStringContent(content, UnicodeEncoding.Utf8, ContentType.MediaType);
            ContentType = contentType;
        }
Example #22
0
 //在SendRequertAsync方法里添加自定义的HTTP头
 public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
 {
     return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
     {
         request.Headers.Add("Custom-Header", "CustomRequestValue");
         HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
         HttpMediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
         if (string.IsNullOrEmpty(contentType.CharSet))
         {
             contentType.CharSet = "UTF-8";
         }
         cancellationToken.ThrowIfCancellationRequested();
         response.Headers.Add("Custom-Header", "CustomResponseValue");
         return response;
     }));
 }
Example #23
0
        public async void requestByPostForm(string url, List <KeyValuePair <String, String> > form)
        {
            Uri uri = new Uri(url);
            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(form);

            HttpMediaTypeHeaderValue contentType =
                new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");

            content.Headers.ContentType = contentType;

            HttpResponseMessage response = await client.PostAsync(uri, content);

            string rta = await response.Content.ReadAsStringAsync();

            httpRta.setRta(rta);
        }
Example #24
0
        internal static Task <AsyncResponse> HttpPostAsync(Uri url, string contentType, byte[] content, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken, IProgress <UploadProgressInfo> progress = null)
        {
            if (options == null)
            {
                options = ConnectionOptions.Default;
            }

            var req = new HttpRequestMessage(HttpMethod.Post, url);

#if WIN_RT
            var httpContent = new HttpBufferContent(content.AsBuffer());
            httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(contentType);
#else
            var httpContent = new ByteArrayContent(content);
            httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
#endif
            req.Content = httpContent;
            return(ExecuteRequest(req, authorizationHeader, options, cancellationToken, progress));
        }
        private static async Task <string> RedirectGetAccessTokenAsync(string code)
        {
            string encodingCallback = Uri.EscapeDataString(CallbackUri);

            string url = "https://api.line.me/v1/oauth/accessToken";

            string postParameter = $"grant_type=authorization_code&client_id={ClientId}&client_secret={ClientSecret}&code={code}&redirect_uri={encodingCallback}";

            HttpStringContent httpContent = new HttpStringContent(postParameter, Windows.Storage.Streams.UnicodeEncoding.Utf8);

            httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

            using (HttpClient httpClient = new HttpClient())
            {
                var httpResponseMessage = await httpClient.PostAsync(new Uri(url), httpContent);

                return(await httpResponseMessage.Content.ReadAsStringAsync());
            }
        }
Example #26
0
 public async Task<CallRet> CallWithBinary(string url, HttpMediaTypeHeaderValue contentType, Stream body, long length)
 {
     Debug.WriteLine("Client.PostWithBinary ==> URL: {0} Length:{1}", url, length);
     try
     {
         HttpClient client = new HttpClient();
         body.Position = 0;
         HttpStreamContent streamContent = new HttpStreamContent(body.AsRandomAccessStream());
         HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
         req.Content = streamContent;
         SetAuth(req,client, body);
         var resp = await client.SendRequestAsync(req);
         return await HandleResult(resp);
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.ToString());
         return new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e);
     }
 }
Example #27
0
        public async Task <CallRet> CallWithBinary(string url, HttpMediaTypeHeaderValue contentType, Stream body, long length)
        {
            Debug.WriteLine("Client.PostWithBinary ==> URL: {0} Length:{1}", url, length);
            try
            {
                HttpClient client = new HttpClient();
                body.Position = 0;
                HttpStreamContent  streamContent = new HttpStreamContent(body.AsRandomAccessStream());
                HttpRequestMessage req           = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
                req.Content = streamContent;
                SetAuth(req, client, body);
                var resp = await client.SendRequestAsync(req);

                return(await HandleResult(resp));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                return(new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e));
            }
        }
Example #28
0
        public static void Upload(string deviceId, IInputStream captureStream)
        {
            Uri uri = new Uri(string.Format(imageUploadUrl, deviceId));

            using (HttpClient httpClient = new HttpClient())
            {
                using (HttpStreamContent streamContent = new HttpStreamContent(captureStream))
                {
                    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri))
                    {
                        streamContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("image/jpeg");
                        request.Content = streamContent;

                        Debug.WriteLine("SendRequestAsync start");
                        HttpResponseMessage response = httpClient.SendRequestAsync(request).AsTask().Result;
                        Debug.WriteLine("SendRequestAsync finish");

                        response.EnsureSuccessStatusCode();
                    }
                }
            }
        }
        public virtual async Task <HttpRequestMessage> SendRequest(Stream stream)
        {
            var content = new HttpMultipartContent();

            content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(String.Format(CultureInfo.InvariantCulture,
                                                                                       @"multipart/related; boundary=""{0}""; type = ""application/atom+xml""",
                                                                                       _boundary));
            content.Add(new HttpStreamContent(stream.AsInputStream()));

            _request.Content = content;

            return(_request);

            // _request.ContentLength = _requestBodyTop.Length + stream.Length + _requestBodyBottom.Length;
            //_request.AllowWriteStreamBuffering = false;
            //_requestStream = await _request.GetRequestStreamAsync();
            //_requestStream.Write(_requestBodyTop.ToArray(), 0, (int)_requestBodyTop.Length);
            //await StreamHelper.TransferAsync(stream, _requestStream, 8192, true);
            //_requestStream.Write(_requestBodyBottom.ToArray(), 0, (int)_requestBodyBottom.Length);
            //await _requestStream.FlushAsync();
            //return _request;
        }
Example #30
0
        public async void insertDocument(T document, IMongo imongo)
        {
            JsonSerializerSettings property = new JsonSerializerSettings();

            property.NullValueHandling = NullValueHandling.Ignore;
            String                   json        = JsonConvert.SerializeObject(document, Formatting.None, property);
            HttpStringContent        content     = new HttpStringContent(json);
            HttpMediaTypeHeaderValue contentType = new HttpMediaTypeHeaderValue("application/json");

            content.Headers.ContentType = contentType;
            HttpResponseMessage x = await client.PostAsync(new Uri(url), content);

            if (x.ReasonPhrase.Equals("OK"))
            {
                MessageBox.Show("El Usuario se agregó correctamente");
                imongo.insertar(2);
            }
            else
            {
                MessageBox.Show("Error al agregar usuario, revise su conexión");
                imongo.insertar(1);
            }
        }
        public async Task <Result <ItemAckPayloadResponse> > SendDirectPhotoAsync(InstaImage image, string threadId,
                                                                                  long uploadId,
                                                                                  Action <UploaderProgress> progress = null)
        {
            var upProgress = new UploaderProgress
            {
                Caption     = string.Empty,
                UploadState = InstaUploadState.Preparing
            };

            try
            {
                var entityName = "direct_" + uploadId;
                var uri        = UriCreator.GetDirectSendPhotoUri(entityName);
                upProgress.UploadId = uploadId.ToString();
                progress?.Invoke(upProgress);
                var ruploadParams = new JObject(
                    new JProperty("media_type", 1),
                    new JProperty("upload_id", uploadId.ToString()),
                    new JProperty("upload_media_height", image.Height),
                    new JProperty("upload_media_width", image.Width));
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri);
                requestMessage.Headers.Add("X-Entity-Name", entityName);
                requestMessage.Headers.Add("X-Instagram-Rupload-Params", ruploadParams.ToString(Formatting.None));
                requestMessage.Headers.Add("Offset", "0");
                var uploadBuffer = image.UploadBuffer;
                var content      = new HttpBufferContent(uploadBuffer);
                content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("image/jpeg");
                requestMessage.Headers.Add("X-Entity-Length", uploadBuffer.Length.ToString());
                requestMessage.Content = content;
                upProgress.UploadState = InstaUploadState.Uploading;
                progress?.Invoke(upProgress);
                var response = await _httpClient.SendRequestAsync(requestMessage);

                var json = await response.Content.ReadAsStringAsync();

                DebugLogger.LogResponse(response);

                var ruploadResp = JsonConvert.DeserializeObject <RuploadResponse>(json);
                if (response.StatusCode != HttpStatusCode.Ok || !ruploadResp.IsOk())
                {
                    upProgress.UploadState = InstaUploadState.Error;
                    progress?.Invoke(upProgress);
                    return(Result <ItemAckPayloadResponse> .Fail(json));
                }

                var uploadIdResp = ruploadResp.UploadId;
                upProgress.UploadState = InstaUploadState.Uploaded;
                progress?.Invoke(upProgress);
                var configUri = UriCreator.GetDirectConfigPhotoUri();
                var config    = new Dictionary <string, string>(7)
                {
                    ["action"] = "send_item",
                    ["allow_full_aspect_ratio"] = "1",
                    ["content_type"]            = "photo",
                    ["mutation_token"]          = Guid.NewGuid().ToString(),
                    ["sampled"]   = "1",
                    ["thread_id"] = threadId,
                    ["upload_id"] = uploadIdResp
                };
                response = await _httpClient.PostAsync(configUri, new HttpFormUrlEncodedContent(config));

                json = await response.Content.ReadAsStringAsync();

                DebugLogger.LogResponse(response);
                var obj = JsonConvert.DeserializeObject <ItemAckResponse>(json);
                if (response.StatusCode != HttpStatusCode.Ok || !obj.IsOk())
                {
                    upProgress.UploadState = InstaUploadState.Error;
                    progress?.Invoke(upProgress);
                    return(Result <ItemAckPayloadResponse> .Fail(json, obj.Message));
                }

                upProgress.UploadState = InstaUploadState.Completed;
                progress?.Invoke(upProgress);
                return(Result <ItemAckPayloadResponse> .Success(obj.Payload, json, obj.Message));
            }
            catch (Exception exception)
            {
                upProgress.UploadState = InstaUploadState.Error;
                progress?.Invoke(upProgress);
                DebugLogger.LogException(exception);
                return(Result <ItemAckPayloadResponse> .Except(exception));
            }
        }
 public virtual JsonResult JsonResult(JsonObject jdom, HttpMediaTypeHeaderValue contentType)
 {
     return(new JsonResult(jdom, contentType));
 }
 public virtual ContentResult ContentResult(string content, HttpMediaTypeHeaderValue contentType)
 {
     return(new ContentResult(content, contentType));
 }
 public virtual ContentResult ContentResult(IBuffer buffer, HttpMediaTypeHeaderValue contentType)
 {
     return(new ContentResult(buffer, contentType));
 }
 public virtual ContentResult ContentResult(string content, HttpMediaTypeHeaderValue contentType)
 {
     return new ContentResult(content, contentType);
 }
 public virtual JsonResult JsonResult(JsonObject jdom, HttpMediaTypeHeaderValue contentType)
 {
     return new JsonResult(jdom, contentType);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonResult"/> class.
 /// </summary>
 /// <param name="jdom">The JSON object body content.</param>
 /// <param name="contentType">The content type header.</param>
 public JsonResult(JsonObject jdom, HttpMediaTypeHeaderValue contentType)
 {
     Content     = jdom;
     ContentType = contentType;
 }
Example #38
0
        private async Task GetTwitterUserNameAsync(string webAuthResultResponseData)
        {
            // Acquiring a access_token first
            string responseData   = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token"));
            string request_token  = null;
            string oauth_verifier = null;

            String[] keyValPairs = responseData.Split('&');

            for (int i = 0; i < keyValPairs.Length; i++)
            {
                String[] splits = keyValPairs[i].Split('=');
                switch (splits[0])
                {
                case "oauth_token":
                    request_token = splits[1];
                    break;

                case "oauth_verifier":
                    oauth_verifier = splits[1];
                    break;
                }
            }

            String TwitterUrl = "https://api.twitter.com/oauth/access_token";

            string timeStamp = GetTimeStamp();
            string nonce     = GetNonce();

            String SigBaseStringParams = "oauth_consumer_key=" + TwitterClientID.Text;

            SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
            SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
            SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
            SigBaseStringParams += "&" + "oauth_token=" + request_token;
            SigBaseStringParams += "&" + "oauth_version=1.0";
            String SigBaseString = "POST&";

            SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

            String Signature = GetSignature(SigBaseString, TwitterClientSecret.Text);

            HttpStringContent httpContent = new HttpStringContent("oauth_verifier=" + oauth_verifier, Windows.Storage.Streams.UnicodeEncoding.Utf8);

            httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
            string authorizationHeaderParams = "oauth_consumer_key=\"" + TwitterClientID.Text + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(request_token) + "\", oauth_version=\"1.0\"";

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", authorizationHeaderParams);
            HttpRequestResult result = await httpClient.TryPostAsync(new Uri(TwitterUrl), httpContent);

            if (result.Succeeded)
            {
                string response = await result.ResponseMessage.Content.ReadAsStringAsync();

                String[] Tokens             = response.Split('&');
                string   oauth_token_secret = null;
                string   access_token       = null;
                string   screen_name        = null;

                for (int i = 0; i < Tokens.Length; i++)
                {
                    String[] splits = Tokens[i].Split('=');
                    switch (splits[0])
                    {
                    case "screen_name":
                        screen_name = splits[1];
                        break;

                    case "oauth_token":
                        access_token = splits[1];
                        break;

                    case "oauth_token_secret":
                        oauth_token_secret = splits[1];
                        break;
                    }
                }

                if (access_token != null)
                {
                    // Store access_token for futher use (e.g., account management).
                }

                if (oauth_token_secret != null)
                {
                    // Store oauth_token_secret for further use (e.g., account management).
                }
                if (screen_name != null)
                {
                    rootPage.NotifyUser(screen_name + " is connected!", NotifyType.StatusMessage);
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonResult"/> class.
 /// </summary>
 /// <param name="jdom">The JSON object body content.</param>
 /// <param name="contentType">The content type header.</param>
 public JsonResult(JsonObject jdom, HttpMediaTypeHeaderValue contentType)
 {
     Content = jdom;
     ContentType = contentType;
 }
 public virtual ContentResult ContentResult(IBuffer buffer, HttpMediaTypeHeaderValue contentType)
 {
     return new ContentResult(buffer, contentType);
 }