protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
     actionContext.Response = challengeMessage;
     //throw new System.Web.Http.HttpResponseException(challengeMessage);
 }
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            // 認証トークンの取得
            IEnumerable<string> x_token;
            if (actionContext.Request.Headers.TryGetValues("x-auth-token", out x_token))
            {
                // 認証トークンの確認
                if (x_token.FirstOrDefault().Equals(this.Token))
                {
                    return;
                }
                logger.Warn("不正な認証トークン. token: " + x_token.FirstOrDefault());
            }

            var res = new System.Net.Http.HttpResponseMessage();
            res.StatusCode = System.Net.HttpStatusCode.Unauthorized;
            actionContext.Response = res;
            return;
        }
示例#3
0
        public System.Net.Http.HttpResponseMessage Get()
        {
            string api_url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
            string version = Gale.REST.Config.GaleConfig.apiVersion;

            //----------------------------------
            var response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new System.Net.Http.StringContent(
                    RenderView("Gale.REST.Config.Startup.Startup.cshtml",
                    new
                    {
                        GALE_DOCS_SITE = Gale.REST.Resources.GALE_DOCS_SITE,
                        isSwaggerEnabled = Gale.REST.Config.SwaggerConfig.IsSwaggerEnabled,
                        APIUrl =api_url +  (api_url.EndsWith("/") ? "" : "/") + version
                    })
                )
            };

            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
            return response;
            //----------------------------------
        }
示例#4
0
        /// <summary>
        /// Get null duration value
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <System.TimeSpan?> > GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <System.TimeSpan?>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
 {
     var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     actionContext.Response = challengeMessage;
     throw new HttpResponseException(challengeMessage);
 }
示例#6
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var LoginCorrecto = false;

                /*Implementar llamado a web api*/

                //Login con webAPI
                #region Login con WebAPI

                var usuario    = model.UserName;
                var contrasena = model.Password;
                var usuarioId  = 0;

                string url = string.Format("http://192.168.0.173:8080/granja/usuarios/login?username={0}&password={1}", usuario, contrasena);

                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
                {
                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    System.Net.Http.HttpResponseMessage response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        var data = await response.Content.ReadAsStringAsync();

                        dynamic results = JsonConvert.DeserializeObject <dynamic>(data);
                        var     id      = Convert.ToInt32(results.id);
                        var     name    = Convert.ToString(results.userName);

                        usuarioId     = id;
                        LoginCorrecto = true;
                    }
                }
                #endregion

                //Traer sensores y volcarlo en una grilla



                ApplicationUser user = null;

                if (LoginCorrecto)
                {
                    //user = await CustomUserManager.FindAsync(model.UserName, model.Password);
                    user = new ApplicationUser {
                        Id = usuarioId.ToString(), UserName = usuario
                    };
                }

                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("", "Usuario o contraseña inválidos.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#7
0
        public async Task <IActionResult> PostGroup([FromBody] SINnerGroup mygroup, Guid SinnerId)
        {
            _logger.LogTrace("Post SINnerGroupInternal: " + mygroup?.Groupname + " (" + SinnerId + ").");
            ApplicationUser user = null;

            //SINner sinner = null;
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Select(x => x.Value.Errors)
                                 .Where(y => y.Count > 0)
                                 .ToList();
                    string msg = "ModelState is invalid: ";
                    foreach (var err in errors)
                    {
                        foreach (var singleerr in err)
                        {
                            msg += Environment.NewLine + "\t" + singleerr.ToString();
                        }
                    }
                    return(BadRequest(new HubException(msg)));
                }

                if (mygroup == null)
                {
                    return(BadRequest(new HubException("group == null.")));
                }
                if (String.IsNullOrEmpty(mygroup?.Groupname))
                {
                    return(BadRequest(new HubException("Groupname may not be empty.")));
                }

                if (SinnerId == Guid.Empty)
                {
                    return(BadRequest(new HubException("SinnerId may not be empty.")));
                }

                SINnerGroup parentGroup = null;

                var returncode = HttpStatusCode.OK;
                user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                var sinnerseq = await(from a in _context.SINners.Include(b => b.SINnerMetaData.Visibility.UserRights) where a.Id == SinnerId select a).ToListAsync();
                if (!sinnerseq.Any())
                {
                    string msg = "Please upload SINner prior to adding him/her to a group!";
                    return(BadRequest(new HubException(msg)));
                }
                foreach (var sinner in sinnerseq)
                {
                    if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false)
                    {
                        return(BadRequest(new HubException("Sinner  " + sinner.Id + ": Visibility contains no entries!")));
                    }

                    if (sinner.LastChange == null)
                    {
                        return(BadRequest(new HubException("Sinner  " + sinner.Id + ": LastChange not set!")));
                    }
                    if (sinner.SINnerMetaData.Visibility.Id == null)
                    {
                        sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid();
                    }
                    bool found = false;
                    foreach (var sinur in sinner.SINnerMetaData.Visibility.UserRights)
                    {
                        if (sinur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant())
                        {
                            if (sinur.CanEdit == true)
                            {
                                found = true;
                            }
                            break;
                        }
                    }
                    if (!found)
                    {
                        string msg = "Sinner " + sinner.Id + " is not editable for user " + user.UserName + ".";
                        return(BadRequest(new HubException(msg)));
                    }

                    List <SINnerGroup> groupfoundseq;
                    if (mygroup.Id == null || mygroup.Id == Guid.Empty)
                    {
                        groupfoundseq = await(from a in _context.SINnerGroups
                                              where a.Id == mygroup.Id
                                              select a).Take(1).ToListAsync();
                    }
                    else
                    {
                        groupfoundseq = await(from a in _context.SINnerGroups
                                              where a.Groupname == mygroup.Groupname &&
                                              a.Language == mygroup.Language
                                              select a).Take(1).ToListAsync();
                    }

                    SINnerGroup storegroup = null;
                    if ((groupfoundseq.Any()))
                    {
                        storegroup = groupfoundseq.FirstOrDefault();
                        user       = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name);

                        var roles = await _userManager.GetRolesAsync(user);

                        if (!roles.Contains("GroupAdmin") || roles.Contains(storegroup?.MyAdminIdentityRole))
                        {
                            string msg = "A group with the name " + mygroup.Groupname + " already exists and user is not GroupAdmin or " + storegroup?.MyAdminIdentityRole + "!";
                            return(BadRequest(new HubException(msg)));
                        }
                    }

                    if (storegroup == null)
                    {
                        if (mygroup.Id == null || mygroup.Id == Guid.Empty)
                        {
                            mygroup.Id = Guid.NewGuid();
                        }
                        mygroup.MyParentGroup = parentGroup;
                        parentGroup?.MyGroups.Add(mygroup);
                        _context.SINnerGroups.Add(mygroup);
                        returncode = HttpStatusCode.Created;
                    }
                    else
                    {
                        returncode = HttpStatusCode.Accepted;
                        _context.Entry(storegroup).CurrentValues.SetValues(mygroup);
                    }

                    try
                    {
                        await _context.SaveChangesAsync();
                    }

                    catch (DbUpdateConcurrencyException ex)
                    {
                        foreach (var entry in ex.Entries)
                        {
                            if (entry.Entity is SINner)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is Tag)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else if (entry.Entity is SINnerGroup)
                            {
                                Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger);
                            }
                            else
                            {
                                throw new NotSupportedException(
                                          "Don't know how to handle concurrency conflicts for "
                                          + entry.Metadata.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                            Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                            telemetry.Properties.Add("User", user?.Email);
                            telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString());


                            tc.TrackException(telemetry);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.ToString());
                        }
                        HubException hue = new HubException("Exception in PostGroup: " + e.ToString(), e);
                        var          msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            ReasonPhrase = e.Message
                        };
                        return(Conflict(hue));
                    }
                }
                switch (returncode)
                {
                case HttpStatusCode.Accepted:
                    return(Accepted("PostGroup", mygroup));

                case HttpStatusCode.Created:
                    return(CreatedAtAction("PostGroup", mygroup));

                default:
                    break;
                }
                return(BadRequest());
            }
            catch (Exception e)
            {
                try
                {
                    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
                    Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e);
                    telemetry.Properties.Add("User", user?.Email);
                    telemetry.Properties.Add("Groupname", mygroup?.Groupname?.ToString());
                    tc.TrackException(telemetry);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.ToString());
                }
                HubException hue = new HubException("Exception in PostGroup: " + e.Message, e);
                return(BadRequest(hue));
            }
        }
示例#8
0
        /// <summary>
        /// Provides the list of events. The **$filter** is very restricted and allows
        /// only the following patterns. - List events for a resource group:
        /// $filter=eventTimestamp ge '&lt;Start Time&gt;' and eventTimestamp le
        /// '&lt;End Time&gt;' and eventChannels eq 'Admin, Operation' and
        /// resourceGroupName eq '&lt;ResourceGroupName&gt;'. - List events for
        /// resource: $filter=eventTimestamp ge '&lt;Start Time&gt;' and eventTimestamp
        /// le '&lt;End Time&gt;' and eventChannels eq 'Admin, Operation' and
        /// resourceUri eq '&lt;ResourceURI&gt;'. - List events for a subscription:
        /// $filter=eventTimestamp ge '&lt;Start Time&gt;' and eventTimestamp le
        /// '&lt;End Time&gt;' and eventChannels eq 'Admin, Operation'. -List events
        /// for a resource provider: $filter=eventTimestamp ge '&lt;Start Time&gt;' and
        /// eventTimestamp le '&lt;End Time&gt;' and eventChannels eq 'Admin,
        /// Operation' and resourceProvider eq '&lt;ResourceProviderName&gt;'. - List
        /// events for a correlation Id:
        /// api-version=2014-04-01&amp;$filter=eventTimestamp ge
        /// '2014-07-16T04:36:37.6407898Z' and eventTimestamp le
        /// '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and
        /// correlationId eq '&lt;CorrelationID&gt;'. No other syntax is allowed.
        /// </summary>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='select'>
        /// Used to fetch events with only the given properties. The filter is a comma
        /// separated list of property names to be returned. Possible values are:
        /// authorization, channels, claims, correlationId, description, eventDataId,
        /// eventName, eventTimestamp, httpRequest, level, operationId, operationName,
        /// properties, resourceGroupName, resourceProviderName, resourceId, status,
        /// submissionTimestamp, subStatus, subscriptionId
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <Microsoft.Rest.Azure.IPage <EventData> > > ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery <EventData> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery <EventData>), string select = default(string), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (this.Client.SubscriptionId == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2015-04-01";
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("select", select);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/eventtypes/management/values").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (select != null)
            {
                _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <Microsoft.Rest.Azure.IPage <EventData> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Page1 <EventData> >(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#9
0
        protected virtual async System.Threading.Tasks.Task <ObjectResponseResult <T> > ReadObjectResponseAsync <T>(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary <string, System.Collections.Generic.IEnumerable <string> > headers)
        {
            if (response == null || response.Content == null)
            {
                return(new ObjectResponseResult <T>(default(T), string.Empty));
            }

            if (ReadResponseAsString)
            {
                var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseText, JsonSerializerSettings);
                    return(new ObjectResponseResult <T>(typedBody, responseText));
                }
                catch (Newtonsoft.Json.JsonException exception)
                {
                    var message = "Could not deserialize the response body string as " + typeof(T).FullName + ".";
                    throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception);
                }
            }
            else
            {
                try
                {
                    using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                        using (var streamReader = new System.IO.StreamReader(responseStream))
                            using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader))
                            {
                                var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings);
                                var typedBody  = serializer.Deserialize <T>(jsonTextReader);
                                return(new ObjectResponseResult <T>(typedBody, string.Empty));
                            }
                }
                catch (Newtonsoft.Json.JsonException exception)
                {
                    var message = "Could not deserialize the response body stream as " + typeof(T).FullName + ".";
                    throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception);
                }
            }
        }
示例#10
0
 //实现方法:HandleUnauthorizedRequest,以实现验证失败时继续提示验证
 protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
     throw new System.Web.Http.HttpResponseException(challengeMessage);
 }
示例#11
0
 public HttpResultObject(System.Net.Http.HttpResponseMessage message)
 {
     msg = message;
 }
        public async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteAuthorizationFilterAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> continuation)
        {
            if(actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            if(continuation == null)
            {
                throw new ArgumentNullException("continuation");
            }

            var controllerDescriptor = actionContext.ActionDescriptor.ControllerDescriptor;
            var actionDescriptor = actionContext.ActionDescriptor;

            var cacheKey = controllerDescriptor.ControllerName + "." + actionDescriptor.ActionName;

            //persistent property
            rolesOrPermissionsName = null;

            if(!cacheDic.ContainsKey(cacheKey))
            {
                var attrs = actionDescriptor.GetCustomAttributes<RequireRolesOrPermissionsAttribute>(false);
                if (attrs.Count == 1)
                {
                    rolesOrPermissionsName = ((RequireRolesOrPermissionsAttribute)attrs[0]).RolesOrPermissionsName;
                }
                else
                {
                    attrs = controllerDescriptor.GetCustomAttributes<RequireRolesOrPermissionsAttribute>(false);
                    if (attrs.Count == 1)
                    {
                        rolesOrPermissionsName = ((RequireRolesOrPermissionsAttribute)attrs[0]).RolesOrPermissionsName;
                    }
                }
                if (rolesOrPermissionsName != null)
                {
                    cacheDic[cacheKey] = rolesOrPermissionsName;
                }
            }
            else
            {
                rolesOrPermissionsName = cacheDic[cacheKey];
            }

            if (rolesOrPermissionsName != null)
            {
                bool isAuthorized = await new SecurityManager().IsUserInRoleAsync("admin", rolesOrPermissionsName);

                if(!isAuthorized)
                {
                    string controller = actionDescriptor.ControllerDescriptor.ControllerName;
                    string action = actionDescriptor.ActionName;

                    string sourceObj = String.Format("KoalaBlog.WebApi.Controllers.{0}Controller.{1}", controller, action);

                    System.Threading.Tasks.Task logTask = new SecurityManager().WriteLogAsync(Entity.Models.Enums.LogLevel.WARNING, sourceObj, "Forbidden");

                    //create forbidden response
                    System.Net.Http.HttpResponseMessage response = new System.Net.Http.HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Forbidden,
                        RequestMessage = actionContext.Request
                    };

                    await logTask;

                    return response;
                }
            }

            return await continuation();
        }
示例#13
0
        protected async System.Threading.Tasks.Task <ActionResult> ConsumeExternalWebAPI()
        {
            string url = "http://api.openweathermap.org/data/2.5/weather?q=Warszawa,pl&lang=pl&units=metric&cnt=1&APPID=c06d79f0976673886c40cdef7a210035";

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                WeatherInfo WeatherInfo = new WeatherInfo();
                Temperature Temperature = new Temperature();
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new
                                                        System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                System.Net.Http.HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();

                    string str = data;

                    //Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);

                    //var table = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data, new { Makes = default(System.Data.DataTable) }).Makes;
                    //var table = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data, new System.Data.DataTable());
                    //var table = JsonConvert.DeserializeAnonymousType(data, new { Makes = default(DataTable) }).Makes;

                    //var table = await System.Threading.Tasks.Task.Factory.StartNew(()=> Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data));

                    String[] strArray = str.Split(',');

                    foreach (string s in strArray)
                    {
                        if (s.Contains("name"))
                        {
                            ViewBag.Miasto = this.RemoveSpecialChars(s).Replace("name", string.Empty);
                            break;
                        }
                    }
                    foreach (string s in strArray)
                    {
                        if (s.Contains("country"))
                        {
                            string kraj = CheckCountry(RemoveSpecialChars(s).Replace("country", string.Empty));
                            ViewBag.Kraj = kraj;
                            break;
                        }
                    }
                    foreach (string s in strArray)
                    {
                        if (s.Contains("temp"))
                        {
                            string testStr = this.RemoveSpecialChars(s).Replace("maintemp", string.Empty);

                            if (Double.TryParse(testStr, out double testDbl))
                            {
                                ViewBag.Temperatura = testStr;
                                break;
                            }
                        }
                    }
                    foreach (string s in strArray)
                    {
                        if (s.Contains("id") && s.Length > 3)
                        {
                            string testStr = this.RemoveSpecialChars(s).Replace("id", string.Empty);

                            if (int.TryParse(testStr, out int test))
                            {
                                ViewBag.MiastoId = testStr;
                                break;
                            }
                        }
                    }
                }
            }
            return(RedirectToAction("Create"));
        }
示例#14
0
        /// <summary>
        /// Get alarms
        /// </summary>
        /// <remarks>
        /// It is possible to filter by state
        /// </remarks>
        /// <param name='orderby'>
        /// &lt;p&gt;&lt;a href='#queryoptions'&gt;Sorts&lt;/a&gt; the result in
        /// ascending order by the supplied property.&lt;/p&gt;&lt;p&gt;Valid values
        /// are: &lt;strong&gt;Created&lt;/strong&gt;
        /// (default).&lt;/p&gt;&lt;p&gt;Note: &lt;strong&gt;orderby&lt;/strong&gt;
        /// and &lt;strong&gt;orderbydesc&lt;/strong&gt; are mutually
        /// exclusive.&lt;/p&gt;
        /// </param>
        /// <param name='orderbydesc'>
        /// &lt;p&gt;&lt;a href='#queryoptions'&gt;Sorts&lt;/a&gt; the result in
        /// descending order by the supplied property.&lt;/p&gt;&lt;p&gt;Valid values
        /// are: &lt;strong&gt;Created&lt;/strong&gt;
        /// (default).&lt;/p&gt;&lt;p&gt;Note: &lt;strong&gt;orderby&lt;/strong&gt;
        /// and &lt;strong&gt;orderbydesc&lt;/strong&gt; are mutually
        /// exclusive.&lt;/p&gt;
        /// </param>
        /// <param name='unitAccountAccountId'>
        /// &lt;p&gt;&lt;a href="#queryoptions"&gt;Filters&lt;/a&gt; the result by
        /// Unit.Account.AccountId using the supplied operation and
        /// value.&lt;/p&gt;&lt;p&gt;Valid operations are:
        /// &lt;strong&gt;eq(int)&lt;/strong&gt;&lt;/p&gt;
        /// </param>
        /// <param name='state'>
        /// &lt;p&gt;&lt;a href="#queryoptions"&gt;Filters&lt;/a&gt; the result by
        /// State using the supplied operation and value.&lt;/p&gt;&lt;p&gt;Valid
        /// operations are:
        /// &lt;strong&gt;eq(alarmstate)&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;state =
        /// ['Unresolved', 'Reject', 'Solved', 'Reset', 'AutoResolved']&lt;/p&gt;
        /// </param>
        /// <param name='top'>
        /// &lt;a href="#queryoptions"&gt;Query paging&lt;/a&gt; Returns the maximum
        /// number of entities. Default and max value is 10000
        /// </param>
        /// <param name='skip'>
        /// &lt;a href="#queryoptions"&gt;Query paging&lt;/a&gt; Skips this number of
        /// entities
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <object, AlarmsGetCollectionAsyncByqueryOptionsHeaders> > GetCollectionAsyncByqueryOptionsWithHttpMessagesAsync(string orderby = "Created", string orderbydesc = default(string), string unitAccountAccountId = default(string), string state = default(string), int?top = 10000, int?skip = default(int?), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (top > 10000)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.InclusiveMaximum, "top", 10000);
            }
            if (top < 1)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.InclusiveMinimum, "top", 1);
            }
            if (skip < 0)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.InclusiveMinimum, "skip", 0);
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("orderby", orderby);
                tracingParameters.Add("orderbydesc", orderbydesc);
                tracingParameters.Add("unitAccountAccountId", unitAccountAccountId);
                tracingParameters.Add("state", state);
                tracingParameters.Add("top", top);
                tracingParameters.Add("skip", skip);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetCollectionAsyncByqueryOptions", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Alarms").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (orderby != null)
            {
                _queryParameters.Add(string.Format("orderby={0}", System.Uri.EscapeDataString(orderby)));
            }
            if (orderbydesc != null)
            {
                _queryParameters.Add(string.Format("orderbydesc={0}", System.Uri.EscapeDataString(orderbydesc)));
            }
            if (unitAccountAccountId != null)
            {
                _queryParameters.Add(string.Format("Unit.Account.AccountId={0}", System.Uri.EscapeDataString(unitAccountAccountId)));
            }
            if (state != null)
            {
                _queryParameters.Add(string.Format("State={0}", System.Uri.EscapeDataString(state)));
            }
            if (top != null)
            {
                _queryParameters.Add(string.Format("top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, this.Client.SerializationSettings).Trim('"'))));
            }
            if (skip != null)
            {
                _queryParameters.Add(string.Format("skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 500)
            {
                var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <object, AlarmsGetCollectionAsyncByqueryOptionsHeaders>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <System.Collections.Generic.IList <ReadAlarmDto> >(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 400)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FourZeroZeroError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 401)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FourZeroOneError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 500)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FiveZeroZeroError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <AlarmsGetCollectionAsyncByqueryOptionsHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#15
0
        /// <summary>
        /// Updates an Alarm
        /// </summary>
        /// <param name='id'>
        /// The id of the alarm
        /// </param>
        /// <param name='alarm'>
        /// The changes to apply
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <object> > PatchAsyncByidalarmWithHttpMessagesAsync(int id, EditAlarmDto alarm, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (alarm == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "alarm");
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("id", id);
                tracingParameters.Add("alarm", alarm);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PatchAsyncByidalarm", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Alarms/{id}").ToString();

            _url = _url.Replace("{id}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(id, this.Client.SerializationSettings).Trim('"')));
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (alarm != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(alarm, this.Client.SerializationSettings);
                _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 204 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 404 && (int)_statusCode != 500)
            {
                var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <object>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 204)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <object>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 400)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FourZeroZeroError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 401)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FourZeroOneError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 404)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FourZeroFourError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 500)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FiveZeroZeroError>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#16
0
        public override async Task <bool> ParseResponseAsync(System.Net.Http.HttpResponseMessage msg)
        {
            string content = await msg.Content.ReadAsStringAsync();

            return(content == "\"success\"");
        }
示例#17
0
        /// <summary>
        /// Update products
        /// </summary>
        /// <remarks>
        /// Resets products.
        /// </remarks>
        /// <param name='subscriptionId'>
        /// Subscription ID.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Resource Group ID.
        /// </param>
        /// <param name='productArrayOfDictionary'>
        /// Array of dictionary of products
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <CatalogArray> > UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, System.Collections.Generic.IList <System.Collections.Generic.IDictionary <string, Product> > productArrayOfDictionary = default(System.Collections.Generic.IList <System.Collections.Generic.IDictionary <string, Product> >), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (subscriptionId == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
            }
            string apiVersion = "2014-04-01-preview";
            CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary();

            if (productArrayOfDictionary != null)
            {
                bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary;
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("subscriptionId", subscriptionId);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("bodyParameter", bodyParameter);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (bodyParameter != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings);
                _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (this.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <CatalogArray>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CatalogArray>(_responseContent, this.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#18
0
        public static async Task<bool> downloadFile(string uri, string saveUri, string filename)
        {
            System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response = new System.Net.Http.HttpResponseMessage();
            return await Task.Run(async () =>
            {
                try
                {
                    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                    {
                        response = httpClient.GetAsync(new Uri(uri)).Result;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            Stream stream = response.Content.ReadAsStreamAsync().Result;
                            byte[] bytes = new byte[stream.Length];
                            stream.Read(bytes, 0, bytes.Length);
                            StorageFolder downFolder = null;
                            if (saveUri == "picture")
                            {
                                downFolder = KnownFolders.SavedPictures;
                            }
                            else
                            {
                                downFolder = await StorageFolder.GetFolderFromPathAsync(saveUri);
                            }
                            var saveFile = await downFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);
                            using (Stream streamSave = await saveFile.OpenStreamForWriteAsync())
                            {
                                await streamSave.WriteAsync(bytes, 0, bytes.Length);
                            }
                            return true;

                        }
                        else
                        {
                            return false;

                        }
                    }
                    else
                    {
                        return false;

                    }
                }
                catch (Exception)
                {
                    return false;
                }
            });
        }
示例#19
0
 // GET api/<controller>
 public System.Net.Http.HttpResponseMessage Get()
 {
     var response = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Redirect);
     response.Headers.Location = new Uri("ApiHelp", UriKind.Relative); 
     return response;
 }
示例#20
0
 public async Task ProcessResponseAsync(System.Net.Http.HttpClient httpClient, System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken token)
 {
     OnTrigger(new CallEvents {
         ResponseMessage = await response.Content.ReadAsStringAsync()
     });
 }
示例#21
0
        /// <summary>
        /// Read data from the meter.
        /// </summary>
        private static void ReadMeter(object parameter)
        {
            GXDLMSReader reader = null;

            System.Net.Http.HttpClient httpClient = Helpers.client;
            using (GXNet media = (GXNet)parameter)
            {
                try
                {
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddJsonFile("appsettings.json", optional: true)
                                 .Build();
                    ListenerOptions        listener = config.GetSection("Listener").Get <ListenerOptions>();
                    GXDLMSObjectCollection objects  = new GXDLMSObjectCollection();
                    GXDLMSSecureClient     client   = new GXDLMSSecureClient(listener.UseLogicalNameReferencing, listener.ClientAddress, listener.ServerAddress, (Authentication)listener.Authentication, listener.Password, (InterfaceType)listener.Interface);
                    reader = new GXDLMSReader(client, media, _logger, listener.TraceLevel, 60000, 3, 0);
                    GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255");
                    ldn.SetUIDataType(2, DataType.String);
                    reader.InitializeConnection();
                    reader.Read(ldn, 2);
                    Console.WriteLine("Meter connected: " + ldn.Value);
                    //Find device.
                    GXDevice            dev  = null;
                    ListDevicesResponse devs = null;
                    {
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                        {
                            Name = (string)ldn.Value
                        }).Result)
                        {
                            Helpers.CheckStatus(response);
                            devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                        }
                        //If device is unknown.
                        if (devs.Devices.Length == 0)
                        {
                            if (listener.DefaultDeviceTemplate == 0)
                            {
                                string str = "Unknown Meter try to connect to the Gurux.DLMS.AMI server: " + ldn.Value;
                                Console.WriteLine(str);
                                AddSystemError info = new AddSystemError();
                                info.Error = new GXSystemError()
                                {
                                    Error = str
                                };
                                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                                {
                                    Helpers.CheckStatus(response);
                                }
                                return;
                            }
                            ListDeviceTemplates lt = new ListDeviceTemplates()
                            {
                                Ids = new UInt64[] { listener.DefaultDeviceTemplate }
                            };
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/template/ListDeviceTemplates", lt).Result)
                            {
                                Helpers.CheckStatus(response);
                                ListDeviceTemplatesResponse ret = response.Content.ReadAsAsync <ListDeviceTemplatesResponse>().Result;
                                if (ret.Devices.Length != 1)
                                {
                                    throw new Exception("DefaultDeviceTemplate value is invalid: " + listener.DefaultDeviceTemplate);
                                }
                                dev = new GXDevice();
                                GXDevice.Copy(dev, ret.Devices[0]);
                                dev.Name         = Convert.ToString(ldn.Value);
                                dev.TemplateId   = listener.DefaultDeviceTemplate;
                                dev.Manufacturer = ret.Devices[0].Name;
                            }
                            dev.Dynamic = true;
                            UpdateDevice update = new UpdateDevice();
                            update.Device = dev;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/UpdateDevice", update).Result)
                            {
                                Helpers.CheckStatus(response);
                                UpdateDeviceResponse r = response.Content.ReadAsAsync <UpdateDeviceResponse>().Result;
                                dev.Id = r.DeviceId;
                            }
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                            {
                                Ids = new UInt64[] { dev.Id }
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                            }
                        }
                        else if (devs.Devices.Length != 1)
                        {
                            throw new Exception("There are multiple devices with same name: " + ldn.Value);
                        }
                        else
                        {
                            dev = devs.Devices[0];
                            if (dev.Security != Security.None)
                            {
                                Console.WriteLine("Reading frame counter.");
                                GXDLMSData fc = new GXDLMSData(listener.InvocationCounter);
                                reader.Read(fc, 2);
                                dev.InvocationCounter = 1 + Convert.ToUInt32(fc.Value);
                                Console.WriteLine("Device ID: " + dev.Id + " LDN: " + (string)ldn.Value);
                                Console.WriteLine("Frame counter: " + dev.FrameCounter);
                            }
                            GetNextTaskResponse ret;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask()
                            {
                                Listener = true, DeviceId = dev.Id
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                ret = response.Content.ReadAsAsync <GetNextTaskResponse>().Result;
                            }
                            if (ret.Tasks == null || ret.Tasks.Length == 0)
                            {
                                Console.WriteLine("No tasks to execute");
                            }
                            else
                            {
                                Console.WriteLine("Task count: " + ret.Tasks.Length);
                                if (client.ClientAddress != dev.ClientAddress || dev.Security != Security.None)
                                {
                                    reader.Release();
                                    reader.Disconnect();
                                    client = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress,
                                                                    dev.Authentication, dev.Password, dev.InterfaceType);
                                    client.UseUtc2NormalTime = dev.UtcTimeZone;
                                    client.Standard          = (Standard)dev.Standard;
                                    if (dev.Conformance != 0)
                                    {
                                        client.ProposedConformance = (Conformance)dev.Conformance;
                                    }
                                    client.Priority                    = dev.Priority;
                                    client.ServiceClass                = dev.ServiceClass;
                                    client.Ciphering.SystemTitle       = GXCommon.HexToBytes(dev.ClientSystemTitle);
                                    client.Ciphering.BlockCipherKey    = GXCommon.HexToBytes(dev.BlockCipherKey);
                                    client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey);
                                    client.ServerSystemTitle           = GXCommon.HexToBytes(dev.DeviceSystemTitle);
                                    client.Ciphering.InvocationCounter = dev.InvocationCounter;
                                    client.Ciphering.Security          = dev.Security;
                                    UInt64 devId = 0;
                                    if (dev.TraceLevel != TraceLevel.Off)
                                    {
                                        devId = dev.Id;
                                    }
                                    reader = new GXDLMSReader(client, media, _logger, listener.TraceLevel, dev.WaitTime, dev.ResendCount, devId);
                                    reader.InitializeConnection();
                                }
                                List <GXValue> values = new List <GXValue>();
                                foreach (GXTask task in ret.Tasks)
                                {
                                    GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType);
                                    obj.Version     = task.Object.Version;
                                    obj.LogicalName = task.Object.LogicalName;
                                    try
                                    {
                                        if (task.TaskType == TaskType.Write)
                                        {
                                            if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2)
                                            {
                                                client.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow));
                                            }
                                            else
                                            {
                                                client.UpdateValue(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data));
                                            }
                                            reader.Write(obj, task.Index);
                                        }
                                        else if (task.TaskType == TaskType.Action)
                                        {
                                            reader.Method(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data), DataType.None);
                                        }
                                        else if (task.TaskType == TaskType.Read)
                                        {
                                            //Reading the meter.
                                            if (task.Object.Attributes[0].DataType != 0)
                                            {
                                                obj.SetDataType(task.Index, (DataType)task.Object.Attributes[0].DataType);
                                            }
                                            if (task.Object.Attributes[0].UIDataType != 0)
                                            {
                                                obj.SetUIDataType(task.Index, (DataType)task.Object.Attributes[0].UIDataType);
                                            }
                                            Reader.Reader.Read(null, httpClient, reader, task, obj);
                                            if (task.Object.Attributes[0].DataType == 0)
                                            {
                                                task.Object.Attributes[0].DataType = (int)obj.GetDataType(task.Index);
                                                if (task.Object.Attributes[0].UIDataType == 0)
                                                {
                                                    task.Object.Attributes[0].UIDataType = (int)obj.GetUIDataType(task.Index);
                                                }
                                                UpdateDatatype u = new UpdateDatatype()
                                                {
                                                    Items = new GXAttribute[] { task.Object.Attributes[0] }
                                                };
                                                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/Object/UpdateDatatype", u).Result)
                                                {
                                                    Helpers.CheckStatus(response);
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        task.Result = ex.Message;
                                        AddError error = new AddError();
                                        error.Error = new GXError()
                                        {
                                            DeviceId = dev.Id,
                                            Error    = "Failed to " + task.TaskType + " " + task.Object.LogicalName + ":" + task.Index + ". " + ex.Message
                                        };
                                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error).Result)
                                        {
                                            Helpers.CheckStatus(response);
                                        }
                                    }
                                    using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                                    {
                                        Tasks = new GXTask[] { task }
                                    }).Result)
                                    {
                                        Helpers.CheckStatus(response);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        AddSystemError info = new AddSystemError();
                        info.Error = new GXSystemError()
                        {
                            Error = ex.Message
                        };
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                        {
                            Helpers.CheckStatus(response);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
示例#22
0
        /// <summary>
        /// Post a bunch of required parameters grouped
        /// </summary>
        /// <param name='parameterGroupingPostRequiredParameters'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParametersInner parameterGroupingPostRequiredParameters, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (parameterGroupingPostRequiredParameters == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
            }
            if (parameterGroupingPostRequiredParameters != null)
            {
                parameterGroupingPostRequiredParameters.Validate();
            }
            int body = default(int);

            if (parameterGroupingPostRequiredParameters != null)
            {
                body = parameterGroupingPostRequiredParameters.Body;
            }
            string customHeader = default(string);

            if (parameterGroupingPostRequiredParameters != null)
            {
                customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
            }
            int?query = default(int?);

            if (parameterGroupingPostRequiredParameters != null)
            {
                query = parameterGroupingPostRequiredParameters.Query;
            }
            string path = default(string);

            if (parameterGroupingPostRequiredParameters != null)
            {
                path = parameterGroupingPostRequiredParameters.Path;
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("customHeader", customHeader);
                tracingParameters.Add("query", query);
                tracingParameters.Add("path", path);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();

            _url = _url.Replace("{path}", System.Uri.EscapeDataString(path));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (query != null)
            {
                _queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeader != null)
            {
                if (_httpRequest.Headers.Contains("customHeader"))
                {
                    _httpRequest.Headers.Remove("customHeader");
                }
                _httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings);
            _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
            _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Product Types
        /// </summary>
        /// <remarks>
        /// The Products endpoint returns information about the Uber products offered
        /// at a given location. The response includes the display name and other
        /// details about each product, and lists the products in the proper display
        /// order.
        /// </remarks>
        /// <param name='animalCreateOrUpdateParameter'>
        /// An Animal
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Error2Exception">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <Animal> > CreateOrUpdatePolymorphicAnimalsWithHttpMessagesAsync(Animal animalCreateOrUpdateParameter = default(Animal), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("animalCreateOrUpdateParameter", animalCreateOrUpdateParameter);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdatePolymorphicAnimals", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getpolymorphicAnimals").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (animalCreateOrUpdateParameter != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings);
                _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new Error2Exception(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error2 _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error2>(_responseContent, this.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <Animal>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Animal>(_responseContent, this.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#24
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            NavigationController.InteractivePopGestureRecognizer.Delegate = null;

            UDID = UIDevice.CurrentDevice.IdentifierForVendor.ToString();

            emailLogo.Frame = new Rectangle(Convert.ToInt32(View.Frame.Width) / 3,
                                            Convert.ToInt32(View.Frame.Width) / 3,
                                            Convert.ToInt32(View.Frame.Width) / 3,
                                            Convert.ToInt32(View.Frame.Width) / 3);
            mainTextTV.Frame        = new Rectangle(0, (Convert.ToInt32(emailLogo.Frame.Y) + Convert.ToInt32(emailLogo.Frame.Height)) + 40, Convert.ToInt32(View.Frame.Width), 26);
            View.BackgroundColor    = UIColor.FromRGB(36, 43, 52);
            mainTextTV.Text         = "Визитка синхронизируется";
            mainTextTV.Font         = UIFont.FromName(Constants.fira_sans, 22f);
            activityIndicator.Color = UIColor.FromRGB(255, 99, 62);
            activityIndicator.Frame = new Rectangle((int)(View.Frame.Width / 2 - View.Frame.Width / 20), (int)(View.Frame.Height - View.Frame.Width / 5), (int)(View.Frame.Width / 10), (int)(View.Frame.Width / 10));
            if (!methods.IsConnected())
            {
                NoConnectionViewController.view_controller_name = GetType().Name;
                this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                return;
            }
            InvokeInBackground(async() =>
            {
                #region uploading photos
                bool photos_exist   = true;
                var documents       = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var cards_cache_dir = Path.Combine(documents, Constants.CardsPersonalImages);
                if (!Directory.Exists(cards_cache_dir))
                {
                    photos_exist = false;
                }
                else
                {
                    photos_exist       = false;
                    string[] filenames = Directory.GetFiles(cards_cache_dir);
                    foreach (var img in filenames)
                    {
                        photos_exist = true;
                        break;
                    }
                }
                var documentsLogo  = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var logo_cache_dir = Path.Combine(documentsLogo, Constants.CardsLogo);
                if (Directory.Exists(logo_cache_dir))
                {
                    string[] filenames = Directory.GetFiles(logo_cache_dir);
                    foreach (var img in filenames)
                    {
                        photos_exist = true;
                        break;
                    }
                }
                List <int> attachments_ids_list = new List <int>();
                if (photos_exist)
                {
                    InvokeOnMainThread(() =>
                    {
                        mainTextTV.Text = "Фотографии выгружаются";
                    });
                    AttachmentsUploadModel res_photos = null;
                    try
                    {
                        res_photos = await attachments.UploadIOS(databaseMethods.GetAccessJwt(), UDID);
                    }
                    catch
                    {
                        if (!methods.IsConnected())
                        {
                            InvokeOnMainThread(() =>
                            {
                                NoConnectionViewController.view_controller_name = GetType().Name;
                                this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                                return;
                            });
                        }
                        return;
                    }
                    if (res_photos != null)
                    {
                        if (res_photos.attachments_ids != null)
                        {
                            attachments_ids_list = res_photos.attachments_ids;
                        }

                        if (res_photos.logo_id == Constants.image_upload_status_code401)
                        {
                            InvokeOnMainThread(() =>
                            {
                                ShowSeveralDevicesRestriction();
                                return;
                            });
                            return;
                        }
                    }

                    InvokeOnMainThread(() =>
                    {
                        mainTextTV.Text = "Визитка синхронизируется";
                    });
                }
                #endregion uploading photos
                var temp_ids = EditViewController.ids_of_attachments;//.AddRange(attachments_ids_list);
                temp_ids.AddRange(attachments_ids_list);
                System.Net.Http.HttpResponseMessage res_user = null;
                try
                {
                    res_user = await cards.CardUpdate(databaseMethods.GetAccessJwt(),
                                                      EditViewController.card_id,
                                                      databaseMethods.GetDataFromUsersCard(company_id, databaseMethods.GetLastSubscription(), EditCompanyDataViewControllerNew.position, EditCompanyDataViewControllerNew.corporativePhone),
                                                      EditPersonalDataViewControllerNew.is_primary,
                                                      SocialNetworkTableViewSource <int, int> .socialNetworkListWithMyUrl,
                                                      temp_ids,
                                                      UDID);
                }catch
                {
                    if (!methods.IsConnected())
                    {
                        InvokeOnMainThread(() =>
                        {
                            NoConnectionViewController.view_controller_name = GetType().Name;
                            this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                            return;
                        });
                    }
                    return;
                }
                if (res_user.StatusCode.ToString().Contains("401") || res_user.StatusCode.ToString().ToLower().Contains(Constants.status_code401))
                {
                    InvokeOnMainThread(() =>
                    {
                        ShowSeveralDevicesRestriction();
                        return;
                    });
                    return;
                }
                InvokeOnMainThread(() =>
                {
                    Clear();

                    var vc = sb.InstantiateViewController(nameof(RootQRViewController));
                    this.NavigationController.PushViewController(vc, true);
                });
            });
        }
示例#25
0
        public async Task <List <TvChannels> > GetChannelListAsync()
        {
            List <TvChannels> tvChannelList = new List <TvChannels>();
            string            address       = String.Empty;

            if (!string.IsNullOrWhiteSpace(_ipAddress))
            {
                address = "http://" + _ipAddress + "/Live/Channels/getList";

                var uri = new Uri(address, UriKind.Absolute);


                #region different way to send httpClient
                //using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                //{
                //    try
                //    {

                //        var headers = httpClient.DefaultRequestHeaders;

                //        headers.UserAgent.ParseAdd(
                //            "Netia%C2%A0Player%C2%A0Pilot/2014.10.271657 CFNetwork/758.1.6 Darwin/15.0.0");


                //        var content = await httpClient.GetStreamAsync(uri);

                //        //var content = await httpClient.GetStringAsync(uri);

                //        var intt = content.Length;

                //        tvChannelList = JsonConvert.DeserializeObject<List<TvChannels>>(content.ToString());

                //        return tvChannelList;

                //    }
                //    catch (Exception ex)
                //    {

                //    }
                //}
                #endregion

                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "UTF-8");
                    try
                    {
                        System.Net.Http.HttpResponseMessage response = await client.GetAsync(uri);

                        response.EnsureSuccessStatusCode();
                        var data = await response.Content.ReadAsStringAsync();

                        tvChannelList = JsonConvert.DeserializeObject <List <TvChannels> >(data);

                        return(tvChannelList);
                    }
                    catch (Exception)
                    {
                        return(tvChannelList);
                    }
                }
            }
            return(tvChannelList);
        }
        public void PostResponseDocumentsWithContent()
        {
            const string string1 = "This is a test document.";
            const string string2 = " This is the second sentence.";

            byte[] string1Data = Encoding.Default.GetBytes(string1);
            byte[] string2Data = Encoding.Default.GetBytes(string2);

            DataContext db       = new DataContext();
            Response    response = null;

            try
            {
                RequestDataMart routing = db.RequestDataMarts.Include(dm => dm.Responses).Where(dm => dm.Status == DTO.Enums.RoutingStatus.Submitted && dm.Responses.Count > 0).OrderByDescending(dm => dm.Responses.OrderByDescending(rsp => rsp.Count).FirstOrDefault().SubmittedOn).FirstOrDefault();
                response             = routing.AddResponse(db.Users.Where(u => u.UserName == TestDMCController.TestUserName).Select(u => u.ID).Single());
                response.SubmittedOn = DateTime.Now;
                db.SaveChanges();

                Guid[] result = null;
                Guid   documentID;
                using (var controller = new TestDMCController())
                {
                    var postData = new Lpp.Dns.DTO.DataMartClient.Criteria.PostResponseDocumentsData {
                        RequestID  = routing.RequestID,
                        DataMartID = routing.DataMartID,
                        Documents  = new[] { new DTO.DataMartClient.Document {
                                                 Name = "test-document.txt", IsViewable = false, MimeType = "text/plain", Size = 0
                                             } }
                    };
                    result = AsyncHelpers.RunSync <Guid[]>(() => controller.PostResponseDocuments(postData));

                    documentID = result.ToArray()[0];
                    System.Net.Http.HttpResponseMessage postResponse = AsyncHelpers.RunSync <System.Net.Http.HttpResponseMessage>(() => controller.PostResponseDocumentChunk(documentID, string1Data));
                    Assert.IsTrue(postResponse.StatusCode == System.Net.HttpStatusCode.OK);
                    postResponse = AsyncHelpers.RunSync <System.Net.Http.HttpResponseMessage>(() => controller.PostResponseDocumentChunk(documentID, string2Data));
                    Assert.IsTrue(postResponse.StatusCode == System.Net.HttpStatusCode.OK);
                }

                Assert.IsNotNull(result);
                Assert.IsTrue(result.Count() > 0);

                Document doc = db.Documents.FirstOrDefault(d => d.ID == documentID);
                Assert.IsNotNull(doc);

                byte[] docData = doc.GetData(db);

                Assert.AreEqual(string1Data.Length + string2Data.Length, docData.Length);
                string savedString = Encoding.Default.GetString(docData);
                Console.WriteLine(savedString);
            }
            finally
            {
                if (response != null)
                {
                    db.Database.ExecuteSqlCommand("DELETE FROM Documents WHERE ItemID = @p0", response.ID);
                    db.Database.ExecuteSqlCommand("DELETE FROM RequestDataMartResponses WHERE ID = @p0", response.ID);
                    db.SaveChanges();
                }
                db.Dispose();
            }
        }
示例#27
0
 /// <summary>
 /// Returns the first header value as a string from an HttpReponseMessage.
 /// </summary>
 /// <param name="response">the HttpResponseMessage to fetch a header from</param>
 /// <param name="headerName">the header name</param>
 /// <returns>the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching</returns>
 internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty;
示例#28
0
        void sync()
        {
            InvokeInBackground(async() =>
            {
                //caching card to db
                databaseMethods.InsertUsersCard(
                    EditPersonalDataViewControllerNew.myName,
                    EditPersonalDataViewControllerNew.mySurname,
                    EditPersonalDataViewControllerNew.myMiddlename,
                    EditPersonalDataViewControllerNew.myPhone,
                    EditPersonalDataViewControllerNew.myEmail,
                    EditPersonalDataViewControllerNew.myHomePhone,
                    EditPersonalDataViewControllerNew.mySite,
                    EditPersonalDataViewControllerNew.myDegree,
                    EditPersonalDataViewControllerNew.myCardName,
                    EditPersonalDataViewControllerNew.myBirthDate,
                    HomeAddressViewController.myCountry,
                    HomeAddressViewController.myRegion,
                    HomeAddressViewController.myCity,
                    HomeAddressViewController.FullAddressStatic,
                    HomeAddressViewController.myIndex,
                    HomeAddressViewController.myNotation,
                    NewCardAddressMapViewController.lat,
                    NewCardAddressMapViewController.lng,
                    true
                    );
                System.Net.Http.HttpResponseMessage res = null;
                try
                {
                    res = await cards.CardUpdate(databaseMethods.GetAccessJwt(),
                                                 EditViewController.card_id,
                                                 databaseMethods.GetDataFromUsersCard(null,
                                                                                      databaseMethods.GetLastSubscription(),
                                                                                      EditCompanyDataViewControllerNew.position, EditCompanyDataViewControllerNew.corporativePhone),
                                                 EditPersonalDataViewControllerNew.is_primary,
                                                 SocialNetworkTableViewSource <int, int> .socialNetworkListWithMyUrl,
                                                 EditViewController.ids_of_attachments,
                                                 UDID);
                }
                catch
                {
                    if (!methods.IsConnected())
                    {
                        InvokeOnMainThread(() =>
                        {
                            NoConnectionViewController.view_controller_name = GetType().Name;
                            this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                            return;
                        });
                    }
                    return;
                }
                if (res.StatusCode.ToString().Contains("401") || res.StatusCode.ToString().ToLower().Contains(Constants.status_code401))
                {
                    InvokeOnMainThread(() =>
                    {
                        ShowSeveralDevicesRestriction();
                        return;
                    });
                    return;
                }

                InvokeOnMainThread(() =>
                {
                    ClearAll();

                    var vc = sb.InstantiateViewController(nameof(RootQRViewController));
                    try
                    {
                        this.NavigationController.PushViewController(vc, true);
                        //var vc_list = this.NavigationController.ViewControllers.ToList();
                        //try { vc_list.RemoveAt(vc_list.Count - 2); } catch { }
                        //this.NavigationController.ViewControllers = vc_list.ToArray();
                    }
                    catch { }
                });
            });
        }
示例#29
0
 /// <summary>
 /// Returns the first header value as a string from an HttpReponseMessage.
 /// </summary>
 /// <param name="response">the HttpResponseMessage to fetch a header from</param>
 /// <param name="headerName">the header name</param>
 /// <returns>the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching</returns>
 internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty;
示例#30
0
        /// <summary>
        /// Get a null array of string using the multi-array format
        /// </summary>
        /// <param name='arrayQuery'>
        /// a null array of string using the multi-array format
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse> ArrayStringMultiNullWithHttpMessagesAsync(System.Collections.Generic.IList <string> arrayQuery = default(System.Collections.Generic.IList <string>), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("arrayQuery", arrayQuery);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiNull", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/null").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (arrayQuery != null)
            {
                if (arrayQuery.Count == 0)
                {
                    _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty)));
                }
                else
                {
                    foreach (var _item in arrayQuery)
                    {
                        _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty)));
                    }
                }
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#31
0
 partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response);
示例#32
0
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <System.Collections.Generic.IList <NewsItem> > > GetNewsWithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNews", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/NewsArticle").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <System.Collections.Generic.IList <NewsItem> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <System.Collections.Generic.IList <NewsItem> >(_responseContent, this.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#33
0
 public System.Net.Http.HttpResponseMessage GetContent(string path)
 {
     using (var f = File.Open(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path), FileMode.Open, FileAccess.Read))
     {
         var response = new System.Net.Http.HttpResponseMessage(HttpStatusCode.OK);
         response.Content = new System.Net.Http.StreamContent(f);
         response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
         return response;
     }
 }
示例#34
0
        public static XmlDocument CreateRabbitResult(System.Net.Http.HttpResponseMessage context)
        {
            XmlDocument xDoc    = new XmlDocument();
            XmlElement  topNode = xDoc.CreateElement("HttpWrapper");

            xDoc.AppendChild(topNode);
            XmlElement headers = xDoc.CreateElement("headers");

            topNode.AppendChild(headers);
            foreach (var h in context.Headers)
            {
                XmlElement header = xDoc.CreateElement("header");
                XmlElement key    = xDoc.CreateElement("key");
                key.InnerText = h.Key;
                XmlElement values = xDoc.CreateElement("values");
                foreach (string strVal in h.Value)
                {
                    XmlElement value = xDoc.CreateElement("value");
                    value.InnerText = strVal;
                    values.AppendChild(value);
                }

                header.AppendChild(key);
                header.AppendChild(values);
                headers.AppendChild(header);
            }

            //XmlElement cookies = xDoc.CreateElement("cookies");
            //topNode.AppendChild(cookies);
            //foreach (var c in context.Cookies)
            //{
            //    XmlElement cookie = xDoc.CreateElement("cookie");
            //    XmlElement key = xDoc.CreateElement("key");
            //    key.InnerText = c.Key;
            //    XmlElement val = xDoc.CreateElement("value");
            //    val.InnerText = c.Value;
            //    cookie.AppendChild(key);
            //    cookie.AppendChild(val);
            //    cookies.AppendChild(cookie);
            //}
            XmlElement statusCode = xDoc.CreateElement("StatusCode");

            statusCode.InnerText = ((int)context.StatusCode).ToString();
            topNode.AppendChild(statusCode);


            XmlElement ContentType = xDoc.CreateElement("ContentType");

            if (context.Content.Headers.ContentType != null)
            {
                ContentType.InnerText = context.Content.Headers.ContentType.ToString();
                topNode.AppendChild(ContentType);
            }

            XmlElement ContentLength = xDoc.CreateElement("ContentLength");

            if (context.Content.Headers.ContentLength != null)
            {
                ContentLength.InnerText = context.Content.Headers.ContentLength.ToString();
                topNode.AppendChild(ContentLength);
            }

            XmlElement Body = xDoc.CreateElement("Body");

            try
            {
                StreamReader reader   = new StreamReader(context.Content.ReadAsStreamAsync().Result, System.Text.Encoding.UTF8);
                var          encoding = reader.CurrentEncoding;
                Body.InnerText = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Serializer | CreateRabbitResult | Exception: " + e.Message);
                Body.InnerText = string.Empty;
            }

            topNode.AppendChild(Body);
            return(xDoc);
        }
        public AccountResult Login(LoginModel model)
        {
            //string result = "{\"message\": \"Failure'\"}";
            AccountResult result = new AccountResult();

            var resp = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK);

            logger.Debug("Hit: Login - " + model.Username + " / <SECRET>");

            var db = ServicesContext.Current;

            if (ModelState.IsValid)
            {
                var user = db.User.SingleOrDefault(x => x.Username == model.Username);

                if (Membership.ValidateUser(model.Username, model.Password) || isValidLocalUser(user, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Username, true);
                    logger.Debug("User authenticated : " + model.Username);
                    logger.Debug("--> " + System.Web.HttpContext.Current.Request.LogonUserIdentity.Name);

                    if (user == null) //If user doesn't exist in our system, create it.
                    {
                        user = new User(model.Username);
                        user.BumpLastLoginDate();
                        db.User.Add(user);
                        db.SaveChanges();
                    }
                    else
                    {
                        user.BumpLastLoginDate();
                        db.Entry(user).State = System.Data.EntityState.Modified;
                        db.SaveChanges();
                    }

                    var identity = new GenericIdentity(user.Username, "Basic");
                    string[] roles = (!String.IsNullOrEmpty(user.Roles)) ? user.Roles.Split(":".ToCharArray()) : new string[0];

                    logger.Debug("Roles == " + roles.ToString());

                    var principal = new GenericPrincipal(identity, roles);
                    Thread.CurrentPrincipal = principal;
                    System.Web.HttpContext.Current.User = principal;

                    result.Success = true;
                    result.User = user;
                    result.Message = "Successfully logged in.";

                }
                else
                {
                    logger.Debug("Authentication Failed from Membership provider.  Attempted username: "******"Username or password were invalid.";
                }
            }
            else
                logger.Debug("model state invalid.");

            logger.Debug("Result = " + result);

            //NOTE: this is necessary because IE doesn't handle json returning from a POST properly.
            //resp.Content = new System.Net.Http.StringContent(result, System.Text.Encoding.UTF8, "text/plain");

            return result;
        }
        /// <summary>
        /// Deletes and autoscale setting
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='autoscaleSettingName'>
        /// The autoscale setting name.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string autoscaleSettingName, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (autoscaleSettingName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "autoscaleSettingName");
            }
            if (this.Client.SubscriptionId == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2015-04-01";
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("autoscaleSettingName", autoscaleSettingName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/autoscalesettings/{autoscaleSettingName}").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{autoscaleSettingName}", System.Uri.EscapeDataString(autoscaleSettingName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("DELETE");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 204)
            {
                var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 public ServerResponseError(System.Net.Http.HttpResponseMessage response) :
     base("REST api returned bad response code: (" + response.StatusCode + ") " + response.ReasonPhrase)
 {
     this.httpStatusCode   = response.StatusCode;
     this.httpReasonPhrase = response.ReasonPhrase;
 }
示例#38
0
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            var response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);

            actionContext.Response = response;
        }
        private  void GetCountsFromWeb(ref webResults VoteColorPair)
        {
            //Create an HTTP client object
            // Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            System.Net.Http.HttpClient snhClient = new System.Net.Http.HttpClient();
            //Add a user-agent header to the GET request. 
            var headers = snhClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri(RestUrlBox.Text);

            //Send the GET request asynchronously and retrieve the response as a string.
            System.Net.Http.HttpResponseMessage snhResponse = new System.Net.Http.HttpResponseMessage();
   
           // Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                int Reds = -1;
                int Blues = -1;

                //Send the GET request
                snhResponse = snhClient.GetAsync(requestUri).Result;
                //httpResponse =  await httpClient.GetAsync(requestUri,Windows.Web.Http.HttpCompletionOption.ResponseContentRead).Re;
                snhResponse.EnsureSuccessStatusCode();
                //httpResponse.EnsureSuccessStatusCode();
                //httpResponseBody = httpResponse.Content.ToString();
                httpResponseBody = snhResponse.Content.ReadAsStringAsync().Result;
                debugText.Text += httpResponseBody;
                int blueCloseCurlyLoc = httpResponseBody.IndexOf("}");
                string bluestring = httpResponseBody.Substring(0, blueCloseCurlyLoc);
                int lastColonLoc = bluestring.LastIndexOf(":");
                bluestring = bluestring.Substring(lastColonLoc+1, blueCloseCurlyLoc - lastColonLoc-1);
                Blues = int.Parse(bluestring);

                int redCloseCurlyLoc = httpResponseBody.LastIndexOf("}");
                string redstring = httpResponseBody.Substring(blueCloseCurlyLoc+1, redCloseCurlyLoc - blueCloseCurlyLoc);
                lastColonLoc = redstring.LastIndexOf(":");
                redCloseCurlyLoc = redstring.LastIndexOf("}");
                redstring = redstring.Substring(lastColonLoc + 1, redCloseCurlyLoc - lastColonLoc - 1);
                Reds = int.Parse(redstring);

                /*                JObject voteJson = JObject.Parse(httpResponseBody);
                if (voteJson[0]["Color"].ToString() == "Blue")
                {
                    Blues = int.Parse(voteJson[0]["Count"].ToString());
                }
                if (voteJson[1]["Color"].ToString() == "Red")
                {
                    Reds = int.Parse(voteJson[1]["Count"].ToString());
                }
*/

                VoteColorPair.RedVotes = Reds;
                VoteColorPair.BlueVotes = Blues;
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                debugText.Text = httpResponseBody;
            }


        }
        public object FileUpload()
        {
            System.Net.Http.HttpResponseMessage rmsg = new System.Net.Http.HttpResponseMessage();
            System.Web.HttpRequest request           = System.Web.HttpContext.Current.Request;
            var dir = request["dir"];

            if (dir == null || string.IsNullOrEmpty(dir) || !Microsoft.RIPSP.Model.GlobalParameters.UploadParams.ContainsKey(dir))
            {
                rmsg.Content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    Rcode = -1,
                    error = 1,
                    Rmsg  = "未注册的请求"
                }));

                return(rmsg);
            }
            int count = request.Files.Count;

            if (count == 0)
            {
                rmsg.Content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    Rcode = 0,
                    error = 1,
                    Rmsg  = "未找到上传文件"
                }));
                return(rmsg);
            }
            System.Web.HttpPostedFile file        = request.Files[0];
            UploadParamModel          uploadParam = Microsoft.RIPSP.Model.GlobalParameters.UploadParams[dir];
            string ext = Path.GetExtension(file.FileName).ToLower();

            if (Array.IndexOf <string>(uploadParam.Extension, ext) == -1)
            {
                rmsg.Content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    Rcode = 0,
                    error = 1,
                    Rmsg  = string.Format("仅可以上传[{0}]类型的文件", string.Join(";", uploadParam.Extension))
                }));
                return(rmsg);
            }

            /*
             * if (Array.IndexOf<string>(uploadParam.ContentType, file.ContentType) == -1)
             * {
             *  rmsg.Content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
             *  {
             *      Rcode = 0,
             *      error = 1,
             *      Rmsg = string.Format("仅可以上传[{0}]类型的文件", string.Join(";", uploadParam.ContentType))
             *  }));
             *  return rmsg;
             * }
             */
            if (file.ContentLength > uploadParam.ContentLength)
            {
                rmsg.Content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    Rcode = 0,
                    error = 1,
                    Rmsg  = string.Format("仅可以上传不超过[{0}]大小的文件", uploadParam.ContentLength)
                }));
                return(rmsg);
            }
            DateTime dtNow    = DateTime.Now;
            string   fileName = string.Format("{0}{1}", dtNow.ToString(@"yyyyMMddHHmmssfff"), ext);
            string   filePath = string.Format("/{0}/{1}/{2}/{3}", Models.GlobalParameters.RootFileDirectoryName, uploadParam.DirName, dtNow.ToString(@"yyyyMM"), fileName);
            string   savePath = string.Format("{0}\\{1}\\{2}\\{3}\\{4}", Models.GlobalParameters.RootFilePath, Models.GlobalParameters.RootFileDirectoryName, uploadParam.DirName, dtNow.ToString(@"yyyyMM"), fileName);

            if (!Directory.Exists(Path.GetDirectoryName(savePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(savePath));
            }
            file.SaveAs(savePath);
            var msg1 = new System.Net.Http.HttpResponseMessage()
            {
                Content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    Rcode      = 1,
                    url        = filePath,
                    filename   = fileName,
                    oridocname = file.FileName,
                    FCount     = request.Files.Count,
                    error      = 0,
                    Rmsg       = "保存成功"
                }))
            };

            return(msg1);
        }