Ejemplo n.º 1
0
        public void ImportClipboard()
        {
            Headers.Clear();
            Cards.Clear();
            Mappings.Clear();
            NameHeader      = null;
            SizeHeader      = null;
            IdHeader        = null;
            AlternateHeader = null;

            var clipboard = Clipboard.GetDataObject();

            if (clipboard.GetDataPresent("Xml Spreadsheet"))
            {
                StreamReader stream = new StreamReader((MemoryStream)clipboard.GetData("Xml Spreadsheet"));
                stream.BaseStream.SetLength(stream.BaseStream.Length - 1);
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(stream.ReadToEnd());
                ParseXml(xml);
                StatusMessage = string.Format("Successfully imported {0} headers.", Headers.Count());

                NameHeader = new PropertyMappingItem()
                {
                    Property = ViewModelLocator.PropertyTabViewModel.NameProperty,
                    Header   = Headers.FirstOrDefault(x => x.PropertyName.Equals("Name", StringComparison.InvariantCultureIgnoreCase))
                };
                RaisePropertyChanged("NameHeader");
                SizeHeader = new PropertyMappingItem()
                {
                    Property = ViewModelLocator.PropertyTabViewModel.SizeProperty,
                    Header   = Headers.FirstOrDefault(x => x.PropertyName.Equals("Size", StringComparison.InvariantCultureIgnoreCase))
                };
                RaisePropertyChanged("SizeHeader");
                IdHeader = new PropertyMappingItem()
                {
                    Property = ViewModelLocator.PropertyTabViewModel.IdProperty,
                    Header   = Headers.FirstOrDefault(x => x.PropertyName.Equals("Id", StringComparison.InvariantCultureIgnoreCase))
                };
                RaisePropertyChanged("IdHeader");
                AlternateHeader = new PropertyMappingItem()
                {
                    Property = ViewModelLocator.PropertyTabViewModel.AlternateProperty,
                    Header   = Headers.FirstOrDefault(x => x.PropertyName.Equals("Alternate", StringComparison.InvariantCultureIgnoreCase))
                };
                RaisePropertyChanged("AlternateHeader");
                foreach (PropertyItemModel customprop in ViewModelLocator.PropertyTabViewModel.Items)
                {
                    Mappings.Add(new PropertyMappingItem()
                    {
                        Property = customprop,
                        Header   = Headers.FirstOrDefault(x => x.PropertyName.Equals(customprop.Name, StringComparison.InvariantCultureIgnoreCase))
                    });
                }
            }
            else
            {
                StatusMessage = "Invalid Clipboard Data";
            }
            RaisePropertyChanged("StatusMessage");
        }
Ejemplo n.º 2
0
        public async Task ExtractFiles(string directoryName, IFileSystem fileSystem, ExtractionProgressedToken progressReportToken = null)
        {
            if (progressReportToken != null)
            {
                progressReportToken.TotalFileCount = Headers.Count(h => h != null && !string.IsNullOrEmpty(h.Filename));
            }

            if (!fileSystem.DirectoryExists(directoryName))
            {
                fileSystem.CreateDirectory(directoryName);
            }

            var a = new AsyncFor();
            await a.RunForEach(Headers, async (header) =>
            {
                if (string.IsNullOrEmpty(header.Filename))
                {
                    return;
                }

                fileSystem.WriteAllBytes(Path.Combine(directoryName, header.Filename), await ExeFsData.ReadArrayAsync(0x200 + header.Offset, header.FileSize));

                if (progressReportToken != null)
                {
                    progressReportToken.IncrementExtractedFileCount();
                }
            });
        }
Ejemplo n.º 3
0
        protected override List <string[]> ReadBufferRows(int numRows)
        {
            var buffer = new List <string[]>();
            int cols   = Headers.Count();

            for (int row = 2, i = 0; row <= _ws.Dimension.End.Row && i < numRows; row++, i++)
            {
                buffer.Add(GetLine(row, cols));
            }
            return(buffer);
        }
Ejemplo n.º 4
0
        public override string ToString()
        {
#if DEBUG
            // This is just used for debugging purposes and will not be available when running in release mode. Problem with
            // this method is that it uses Encoding to decode the content which is a fairly complicated process. For debugging
            // purposes I'm using UTF-8 which is working most of the time. In real life you want to use the charset provided, or
            // some default encoding as explained in the HTTP specs.
            return(HttpServerResponseParser.Default.ConvertToString(this));
#else
            return($"{HttpVersion} {ResponseStatus} including {Headers.Count()} headers.");
#endif
        }
        public async Task AsyncUnaryCall_NoHeaders_RequestMessageHasNoHeaders()
        {
            // Arrange
            HttpRequestMessage?httpRequestMessage = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                HelloReply reply = new HelloReply
                {
                    Message = "Hello world"
                };

                var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout();

                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            var headers = new Metadata();

            // Act
            var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(headers : headers), new HelloRequest());

            // Assert
            Assert.AreEqual("Hello world", rs.Message);

            Assert.IsNotNull(httpRequestMessage);

            // User-Agent is always sent
            Assert.AreEqual(0, httpRequestMessage !.Headers.Count(h =>
            {
                if (string.Equals(h.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (string.Equals(h.Key, HeaderNames.TE, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (string.Equals(h.Key, GrpcProtocolConstants.MessageAcceptEncodingHeader, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                return(true);
            }));
        }
Ejemplo n.º 6
0
        public JToken AsJObject()
        {
            JArray joTable = new JArray();

            foreach (IEnumerable <string> record in Records)
            {
                JObject joRecord = new JObject();
                for (int h = 0; h < Headers.Count(); h++)
                {
                    joRecord.Add(Headers.ElementAt(h), record.ElementAt(h));
                }
                joTable.Add(joRecord);
            }

            return(joTable);
        }
Ejemplo n.º 7
0
        public override string ToString()
        {
            StringBuilder responseText = new StringBuilder();

            responseText.Append($"{GlobalConstants.HttpOneProtocolFragment}");
            responseText.AppendLine($" {(int)StatusCode} {StatusCode}");
            if (Headers != null && Headers.Count() > 0)
            {
                responseText.AppendLine(Headers.ToString());
            }
            if (Content.Length > 0)
            {
                responseText.AppendLine(Environment.NewLine);
            }
            return(responseText.ToString());
        }
        private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
        {
            token = null;
            IEnumerable <string> Headers;

            if (!request.Headers.TryGetValues("Authorization", out Headers) || Headers.Count() > 1)
            {
                return(false);
            }


            // revisa si el token tiene la palabra bearer, como es usado en la convencion y si no pues simpemente lo iguala al token en si
            var bearerToken = Headers.ElementAt(0);

            token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
            return(true);
        }
Ejemplo n.º 9
0
        public void AddRequestHeader(string key, string value)
        {
            if (Headers == null)
            {
                Headers = new List <Header>();
            }

            if (key != null && Headers.Count(x => x.Key == key && x.IsRequestHeader == true) == 0)
            {
                Headers.Add(
                    new Header {
                    Id              = Guid.NewGuid(),
                    Key             = key,
                    Value           = value,
                    IsRequestHeader = true
                });
            }
        }
Ejemplo n.º 10
0
        public static async Task <TResult> PostAsync <TResult>(string url, object data, string TokenHeader = "", params EasyPair[] Headers)
        {
            var jsonData = data?.ToJson() ?? "";
            var client   = new HttpClient();
            var content  = new StringContent(jsonData, Encoding.UTF8, "application/json");

            content.Headers.Add("Authorization", "Bearer " + TokenHeader);
            if (Headers?.Count() > 0)
            {
                foreach (var item in Headers)
                {
                    content.Headers.Add(item.Key, item.Value);
                }
            }

            var json = await client.PostAsync(url, content)?.Result?.Content?.ReadAsStringAsync();

            return((json ?? "").FromJson <TResult>());
        }
Ejemplo n.º 11
0
        public async Task AsyncUnaryCall_SetMaxValueDeadline_RequestMessageHasNoDeadlineHeader()
        {
            // Arrange
            HttpRequestMessage?httpRequestMessage = null;

            var httpClient = ClientTestHelpers.CreateTestClient(async request =>
            {
                httpRequestMessage = request;

                var streamContent = await ClientTestHelpers.CreateResponseContent(new HelloReply()).DefaultTimeout();
                return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent));
            });
            var invoker = HttpClientCallInvokerFactory.Create(httpClient);

            // Act
            await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(deadline : DateTime.MaxValue), new HelloRequest());

            // Assert
            Assert.IsNotNull(httpRequestMessage);
            Assert.AreEqual(0, httpRequestMessage !.Headers.Count(h => string.Equals(h.Key, GrpcProtocolConstants.TimeoutHeader, StringComparison.OrdinalIgnoreCase)));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Builds a HTTP request from a (network) stream
        /// </summary>
        /// <param name="requestStream"></param>
        public Request(Stream requestStream)
        {
            var sr        = new StreamReader(requestStream);
            var firstline = sr.ReadLine();

            if (firstline == null)
            {
                return;
            }
            IsValid = _requestPattern.IsMatch(firstline);
            if (!IsValid)
            {
                return;
            }
            var requestLine = firstline.Split(' ');

            Method = requestLine[0].ToUpper();
            Url    = new Url(requestLine[1]);

            while (sr.Peek() >= 0)
            {
                var rl        = sr.ReadLine();
                var tempSplit = rl.Split(':');
                if (tempSplit.Length >= 2)
                {
                    var tempKey = tempSplit[0].ToLower();
                    var tempVal = tempSplit[1].TrimStart(' ').TrimEnd('\r', '\n');
                    if (tempKey != string.Empty && tempVal != string.Empty)
                    {
                        Headers.Add(tempKey, tempVal);
                    }
                }
                else
                {
                    if (Method != "POST" || !Headers.ContainsKey("content-length"))
                    {
                        continue;
                    }
                    var buffer = new char[int.Parse(Headers["content-length"])];
                    sr.Read(buffer, 0, buffer.Length);
                    ContentString = WebUtility.UrlDecode(new string(buffer));

                    if (string.IsNullOrEmpty(ContentString))
                    {
                        continue;
                    }
                    ContentBytes  = Encoding.UTF8.GetBytes(ContentString);
                    ContentStream = new MemoryStream(ContentBytes);
                }
            }
            HeaderCount = Headers.Count();
            if (Headers.ContainsKey("user-agent"))
            {
                UserAgent = Headers["user-agent"];
            }
            if (Headers.ContainsKey("content-type"))
            {
                ContentType = Headers["content-type"];
            }
            if (Headers.ContainsKey("content-length"))
            {
                ContentLength = int.Parse(Headers["content-length"]);
            }
        }
Ejemplo n.º 13
0
 public override bool NextButton_CanExecute()
 {
     return(InputFileSpecified && SelectedSheet != null && Headers?.Count() > 0);
 }
Ejemplo n.º 14
0
        public async Task Invoke(HttpContext httpContext)
        {
            StringValues Headers;

            if (!httpContext.Request.Headers.TryGetValue("Authorization", out Headers) || Headers.Count() > 1)
            {
                httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                throw new NotImplementedException("Authorization Key Empty");
            }

            var authHeader = Headers.ElementAt(0);

            if (authHeader.StartsWith(Constants.Auth.Basic) && authHeader != null)
            {
                var encodedCredentials = authHeader.Substring(6);

                if (!string.IsNullOrWhiteSpace(encodedCredentials))
                {
                    // Get the encoded username and password
                    var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();
                    // Decode from Base64 to string
                    var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
                    // Split username and password
                    var username = decodedUsernamePassword.Split(':', 2)[0];
                    var password = decodedUsernamePassword.Split(':', 2)[1];
                    // Check if login is correct
                    if (IsAuthorized(username, password))
                    {
                        await _next.Invoke(httpContext);

                        return;
                    }
                }
            }
            else if (authHeader.StartsWith(Constants.Auth.Jwt) && authHeader != null)
            {
                var token = authHeader.Substring(7);

                if (!string.IsNullOrWhiteSpace(token))
                {
                    var tokenValidationParameters = new TokenValidationParameters
                    {
                        // Validar la firma del emisor
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SECRET_KEY"])),

                        // Validar el emisor JWT (iss)
                        ValidateIssuer = true,
                        ValidIssuer    = _configuration["ISSUER"],

                        // Validar la audiencia JWT (aud)
                        ValidateAudience = false,
                        ValidAudience    = _configuration["AUDIENCE"],

                        // Validar la caducidad del token
                        ValidateLifetime = true,
                    };
                    try
                    {
                        SecurityToken           validatedToken;
                        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                        handler.ValidateToken(token, tokenValidationParameters, out validatedToken);
                    }
                    catch (SecurityTokenExpiredException)
                    {
                        throw new SecurityTokenExpiredException();
                    }
                    catch (SecurityTokenInvalidIssuerException)
                    {
                        throw new SecurityTokenInvalidIssuerException();
                    };

                    await _next.Invoke(httpContext);

                    return;
                }
            }

            httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            throw new NotImplementedException("Request Headers Invalid");
        }