Ejemplo n.º 1
0
        internal HttpResponse UploadWorld(HttpRequest req)
        {
            try
            {
                var header = req.ContentType;
                var parser = new MultipartFormDataParser(new MemoryStream(req.Data), req.GetMultipartBoundary(), Encoding.UTF8);
                var uid    = parser.GetParameterValue("uid");
                var token  = parser.GetParameterValue("token");
                this.characterService.FindAndAuthorize(token, Convert.ToUInt32(uid));

                if (parser.Files.Count() < 1)
                {
                    Log.Error("Client {ip}:{port} failed to provide file for UploadWorld", req.SourceIp, req.SourcePort);
                    return(req.FailureResponse());
                }

                var file = parser.Files[0];
                Log.Information("Uploading world {uid} from client {ip}:{port}", uid, req.SourceIp, req.SourcePort);
                this.storage.SaveWorldData(uid, file.Data);
                Log.Information("Successfully saved world {uid} from client {ip}:{port}", uid, req.SourceIp, req.SourcePort);
                return(new HttpResponse(req, 200, null));
            }
            catch (Exception e)
            {
                Request.HandleException(req, e, false);
                if (e is CharacterService.NotAuthorizedException || e is CharacterService.NotFoundException)
                {
                    return(req.FailureResponse());
                }
                else
                {
                    throw e;
                }
            }
        }
Ejemplo n.º 2
0
        internal HttpResponse Upload(HttpRequest req)
        {
            uint uid = 0;

            try
            {
                var header = req.ContentType;
                var parser = new MultipartFormDataParser(new MemoryStream(req.Data), req.GetMultipartBoundary(), Encoding.UTF8);
                uid = Convert.ToUInt32(parser.GetParameterValue("uid"));
                var token     = parser.GetParameterValue("token");
                var slot      = parser.GetParameterValue("slot");
                var character = this.characterService.FindAndAuthorize(token, Convert.ToUInt32(uid));

                var slotId = Convert.ToUInt32(slot);
                if (slotId > character.NumberOfSlots)
                {
                    Log.Warning("Client {endpoint} failed to upload photo: slot out of range ({slot})!", req.GetEndpoint(), slot);
                    return(req.TextResponse("limit="));
                }

                if (parser.Files.Count() < 1)
                {
                    Log.Warning("Client {ip}:{port} failed to provide file for Photo upload", req.SourceIp, req.SourcePort);
                    return(req.FailureResponse());
                }

                var file = parser.Files[0];
                if (file.Data.Length > this.storage.SizeLimit)
                {
                    Log.Warning("Client {endpoint} failed to upload photo: over size limit {size}", req.GetEndpoint(), file.Data.Length);
                    return(req.TextResponse("limit=" + this.storage.SizeLimit));
                }
                else
                {
                    Log.Information("Uploading photo for {uid}, slot {slot} from client {ip}:{port}", uid, slot, req.SourceIp, req.SourcePort);
                    var hash = this.storage.Save(file.Data);
                    this.photoService.SetPhoto(token, uid, slot, hash);
                    return(req.TextResponse("ok=" + hash));
                }
            }
            catch (Exception e)
            {
                Request.HandleException(req, e, false);
                if (e is PhotoStorage.OversizeException)
                {
                    return(req.TextResponse("limit=" + this.storage.SizeLimit));
                }
                else if (e is CharacterService.NotAuthorizedException || e is CharacterService.NotFoundException || e is FormatException)
                {
                    return(req.FailureResponse());
                }
                else
                {
                    return(req.TextResponse("limit=1" + this.storage.SizeLimit));
                }
            }
        }
        private bool ValidateSingleValueParameters(MultipartFormDataParser parser)
        {
            // Deal with the parameters that are expected to have only one value.
            var expectedParametersWithSingleValue = ExpectedParams
                                                    .GroupBy(p => p.Name)
                                                    .Where(g => g.Count() == 1)
                                                    .Select(g => g.Single());

            foreach (var expectedParameter in expectedParametersWithSingleValue)
            {
                if (!parser.HasParameter(expectedParameter.Name))
                {
                    return(false);
                }

                var actualValue           = parser.GetParameterValue(expectedParameter.Name);
                var actualValueFromValues = parser.GetParameterValues(expectedParameter.Name).Single();

                if (actualValue != actualValueFromValues)
                {
                    return(false);
                }

                if (expectedParameter.Data != actualValue)
                {
                    return(false);
                }
            }

            return(true);
        }
 public void GetParameterValueReturnsNullIfNoParameterFound()
 {
     using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8);
         Assert.Null(parser.GetParameterValue("does not exist"));
     }
 }
Ejemplo n.º 5
0
        private void HandleRequest(object contextObject)
        {
            var context = (HttpListenerContext)contextObject;

            context.Response.SendChunked = true;

            Console.Write($"[{DateTime.Now}] {context.Request.HttpMethod} request to {context.Request.Url.AbsolutePath}... ");

            void SetResponseWithString(string response)
            {
                var bytes = Encoding.UTF8.GetBytes(response);

                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                context.Response.StatusCode = 200;
            }

            switch (context.Request.Url.AbsolutePath)
            {
            case "/api/getAllContacts" when context.Request.HttpMethod == "GET": {
                SetResponseWithString(Contact.ToVCardMany(storage.GetAllContacts()));
            }
            break;

            case "/api/findBy" when context.Request.HttpMethod == "GET": {
                string field = context.Request.QueryString["field"];
                string query = context.Request.QueryString["query"];
                Enum.TryParse(field, out Contact.FieldKind fieldKind);

                SetResponseWithString(Contact.ToVCardMany(storage.FindByField(fieldKind, query)));
            }
            break;

            case "/api/addContact" when context.Request.HttpMethod == "POST": {
                var    parser = new MultipartFormDataParser(context.Request.InputStream);
                string vcard  = parser.GetParameterValue("contact");
                Debug.Assert(vcard != null, "Request should have a 'contact' field");
                storage.AddContact(Contact.Parse(vcard), out string message);

                SetResponseWithString(message);
            }
            break;

            case "/api/greet" when context.Request.HttpMethod == "GET": {
                context.Response.StatusCode = (int)HttpStatusCode.OK;
            }
            break;

            default: {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
            break;
            }

            Console.WriteLine($" [{DateTime.Now}] -> {context.Response.StatusCode} {(HttpStatusCode)context.Response.StatusCode}");

            context.Response.Close();
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Returns the value of a parameter or the default value if it doesn't exist.
 /// </summary>
 /// <param name="parser">The parser.</param>
 /// <param name="name">The name of the parameter.</param>
 /// <param name="defaultValue">The default value.</param>
 /// <returns>The value of the parameter</returns>
 public static string GetParameterValue(this MultipartFormDataParser parser, string name, string defaultValue)
 {
     if (parser.HasParameter(name))
     {
         return(parser.GetParameterValue(name));
     }
     else
     {
         return(defaultValue);
     }
 }
Ejemplo n.º 7
0
        public async Task <IActionResult> Post()
        {
            var parser = new MultipartFormDataParser(Request.Body);

            int.TryParse(parser.GetParameterValue("messages"), out var messages);

            var sendingPmode = parser.GetParameterValue("pmode");

            if (sendingPmode == null)
            {
                throw new ArgumentNullException(nameof(sendingPmode), @"SendingPmode parameter is required!");
            }

            await submitMessageCreator.CreateSubmitMessages(new MessagePayload
            {
                Files                  = parser.Files,
                SendingPmode           = sendingPmode,
                NumberOfSubmitMessages = messages == 0 ? 1 : messages
            });

            return(Ok());
        }
Ejemplo n.º 8
0
        private string GetUserCredentials(out string password, out string token)
        {
            string user = null;

            password = null;
            token    = null;

            if (_requestFormData.HasParameter("username"))
            {
                user = _requestFormData.GetParameterValue("username");
            }

            if (_requestFormData.HasParameter("password"))
            {
                password = _requestFormData.GetParameterValue("password");
            }

            if (_requestFormData.HasParameter("token"))
            {
                token = _requestFormData.GetParameterValue("token");
            }
            return(user);
        }
        public void CorrectlyHandlesMultilineParameter()
        {
            string request = TestUtil.TrimAllLines(
                @"-----------------------------41952539122868
                Content-Disposition: form-data; name=""multilined""

                line 1
                line 2
                line 3
                -----------------------------41952539122868--");

            using (Stream stream = TestUtil.StringToStream(request, Encoding.UTF8))
            {
                var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
                Assert.AreEqual(parser.GetParameterValue("multilined"), "line 1\r\nline 2\r\nline 3");
                Assert.AreEqual(parser.GetParameterValues("multilined").First(), "line 1\r\nline 2\r\nline 3");
            }
        }
Ejemplo n.º 10
0
        public ProductMediaResponse AddProductMedia(Stream media)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(media);
            string productId = dataParser.GetParameterValue("productId");

            try
            {
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    string path = ServiceHelper.SaveImage(dataParser.Files[0].Data, dataParser.Files[0].FileName);
                    if (long.TryParse(productId, out long id))
                    {
                        ProductMedia productMedia = new ProductMedia
                        {
                            MediaSource = path,
                            ProductId   = id,
                            DateCreate  = DateTime.Now,
                            IsDeleted   = false,
                            IsMain      = false
                        };

                        entities.ProductMedias.Add(productMedia);
                        entities.SaveChanges();
                        return(new ProductMediaResponse {
                            MediaSource = path, Id = productMedia.Id
                        });
                    }
                    return(new ProductMediaResponse());
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "productId", productId }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Product);
                return(new ProductMediaResponse());
            }
        }
Ejemplo n.º 11
0
        public BlogResponse AddBlog(Stream blogData)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(blogData);

            try
            {
                string   name             = dataParser.GetParameterValue("name");
                string   description      = dataParser.GetParameterValue("description");
                string   titleDescription = dataParser.GetParameterValue("titleDescription");
                FilePart dataParserFile   = dataParser.Files[0];
                string   path             = ServiceHelper.SaveImage(dataParserFile.Data, dataParserFile.FileName);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    Blog blog = new Blog
                    {
                        Name             = name,
                        IsDeleted        = false,
                        Description      = description,
                        DateCreated      = DateTime.Now,
                        MediaUrl         = path,
                        TitleDescription = titleDescription
                    };
                    entities.Blogs.Add(blog);
                    entities.SaveChanges();
                    return(new BlogResponse
                    {
                        Name = blog.Name,
                        Description = blog.Description,
                        TitleDescription = blog.TitleDescription,
                        Id = blog.Id,
                        DateCreated = blog.DateCreated.ToLongDateString() + " " + blog.DateCreated.ToLongTimeString(),
                        MediaUrl = blog.MediaUrl
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "name", dataParser.GetParameterValue("name") },
                    { "description", dataParser.GetParameterValue("description") },
                    { "titleDescription", dataParser.GetParameterValue("titleDescription") }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Blog);
                return(new BlogResponse());
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Parses the inbound email webhook.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>The <see cref="InboundEmail"/>.</returns>
        public InboundEmail ParseInboundEmailWebhook(Stream stream)
        {
            // Parse the multipart content received from SendGrid
            var parser = new MultipartFormDataParser(stream, Encoding.UTF8);

            // Convert the 'headers' from a string into array of KeyValuePair
            var rawHeaders = parser
                             .GetParameterValue("headers", string.Empty)
                             .Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            var headers = rawHeaders
                          .Select(header =>
            {
                var splitHeader = header.Split(new[] { ": " }, StringSplitOptions.RemoveEmptyEntries);
                var key         = splitHeader[0];
                var value       = splitHeader.Length >= 2 ? splitHeader[1] : null;
                return(new KeyValuePair <string, string>(key, value));
            }).ToArray();

            // Combine the 'attachment-info' and Files into an array of Attachments
            var attachmentInfoAsJObject = JObject.Parse(parser.GetParameterValue("attachment-info", "{}"));
            var attachments             = attachmentInfoAsJObject
                                          .Properties()
                                          .Select(prop =>
            {
                var attachment = prop.Value.ToObject <InboundEmailAttachment>();
                attachment.Id  = prop.Name;

                var file = parser.Files.FirstOrDefault(f => f.Name == prop.Name);
                if (file != null)
                {
                    attachment.ContentType = file.ContentType;
                    attachment.Data        = file.Data;
                }

                return(attachment);
            }).ToArray();

            // Convert the 'envelope' from a JSON string into a strongly typed object
            var envelope = JsonConvert.DeserializeObject <InboundEmailEnvelope>(parser.GetParameterValue("envelope", "{}"));

            // Convert the 'charset' from a string into array of KeyValuePair
            var charsetsAsJObject = JObject.Parse(parser.GetParameterValue("charsets", "{}"));
            var charsets          = charsetsAsJObject
                                    .Properties()
                                    .Select(prop =>
            {
                var key   = prop.Name;
                var value = Encoding.GetEncoding(prop.Value.ToString());
                return(new KeyValuePair <string, Encoding>(key, value));
            }).ToArray();

            // Create a dictionary of parsers, one parser for each desired encoding.
            // This is necessary because MultipartFormDataParser can only handle one
            // encoding and SendGrid can use different encodings for parameters such
            // as "from", "to", "text" and "html".
            var encodedParsers = charsets
                                 .Where(c => c.Value != Encoding.UTF8)
                                 .Select(c => c.Value)
                                 .Distinct()
                                 .Select(encoding =>
            {
                stream.Position = 0;
                return(new
                {
                    Encoding = encoding,
                    Parser = new MultipartFormDataParser(stream, encoding)
                });
            })
                                 .Union(new[]
            {
                new { Encoding = Encoding.UTF8, Parser = parser }
            })
                                 .ToDictionary(ep => ep.Encoding, ep => ep.Parser);

            // Convert the 'from' from a string into an email address
            var rawFrom = GetEncodedValue("from", charsets, encodedParsers, string.Empty);
            var from    = ParseEmailAddress(rawFrom);

            // Convert the 'to' from a string into an array of email addresses
            var rawTo = GetEncodedValue("to", charsets, encodedParsers, string.Empty);
            var to    = ParseEmailAddresses(rawTo);

            // Convert the 'cc' from a string into an array of email addresses
            var rawCc = GetEncodedValue("cc", charsets, encodedParsers, string.Empty);
            var cc    = ParseEmailAddresses(rawCc);

            // Arrange the InboundEmail
            var inboundEmail = new InboundEmail
            {
                Attachments = attachments,
                Charsets    = charsets,
                Dkim        = GetEncodedValue("dkim", charsets, encodedParsers, null),
                Envelope    = envelope,
                From        = from,
                Headers     = headers,
                Html        = GetEncodedValue("html", charsets, encodedParsers, null),
                SenderIp    = GetEncodedValue("sender_ip", charsets, encodedParsers, null),
                SpamReport  = GetEncodedValue("spam_report", charsets, encodedParsers, null),
                SpamScore   = GetEncodedValue("spam_score", charsets, encodedParsers, null),
                Spf         = GetEncodedValue("SPF", charsets, encodedParsers, null),
                Subject     = GetEncodedValue("subject", charsets, encodedParsers, null),
                Text        = GetEncodedValue("text", charsets, encodedParsers, null),
                To          = to,
                Cc          = cc
            };

            return(inboundEmail);
        }
Ejemplo n.º 13
0
        public GalleryResponse AddGalery(Stream galleryStream)
        {
            GalleryResponse response = new GalleryResponse();
            objResponse     Response = new objResponse();

            GalleryManager objGalManager = new GalleryManager();
            Galleries      objGallery    = new Galleries();
            string         auth_token    = "";

            try
            {
                var parser = new MultipartFormDataParser(galleryStream);

                // Parse all the fields by name
                var token1      = parser.GetParameterValue("authentication_Token");
                var token2      = parser.GetParameterValue("authentication_token");
                var gName       = parser.GetParameterValue("name");
                var gType       = parser.GetParameterValue("gallery_Type");
                var gPrice      = parser.GetParameterValue("price");
                var gPermission = parser.GetParameterValue("gallery_Permission");

                // Check Whether Req is null or not
                if ((token1 == null && token2 == null) || gName == null || gType == null)
                {
                    response.header.ErrorCode    = 500;
                    response.header.ErrorMessage = "Bad Request";
                    response.gallery             = null;
                    return(response);
                }

                // Now Enter GalleryDetails in db

                objGallery.name         = gName;
                objGallery.gallery_Type = gType;
                objGallery.price        = gPrice;
                if (gPermission == "")
                {
                    objGallery.gallery_Permission = "Public";
                }
                else
                {
                    objGallery.gallery_Permission = gPermission;
                }


                objGallery.productIdentifier = "com.nexomni.talkblox.talkblox" + Regex.Replace(gName, "[^a-zA-Z0-9_]+", "");

                if (gPrice == "")
                {
                    objGallery.isBuy = false;
                }
                else
                {
                    objGallery.isBuy = true;
                }

                if (token1 != null)
                {
                    auth_token = token1;
                }

                if (token2 != null)
                {
                    auth_token = token2;
                }
                Response = objGalManager.AddGallery(objGallery, auth_token);

                if (Response.ErrorCode == 0)
                {
                    if (Response.ErrorMessage != "Invalid Authentication Token")
                    {
                        // Now Save All Media File On Server
                        objGallery.id = Response.ResponseData.Tables[0].Rows[0][0].ToString();

                        // Files are in list parse and save them one by one
                        foreach (var file in parser.Files)
                        {
                            var    temp     = file.FileName.Split('.');
                            string filename = Guid.NewGuid() + "." + temp[temp.Length - 1];

                            Stream data          = file.Data;
                            string ThumbnailName = file.FileName;

                            if (gType == "sound")
                            {
                                UploadAsStream(data, HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galAudioUploadDirectory"].ToString()) + filename);
                            }
                            else if (gType == "video")
                            {
                                UploadAsStream(data, HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galVideoUploadDirectory"].ToString()) + filename);
                                string fpath  = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galVideoUploadDirectory"].ToString()) + filename;
                                string thpath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galThumbUploadDirectory"].ToString()) + Guid.NewGuid() + "." + "jpg";
                                genreateThumb(fpath, thpath);
                            }
                            else if (gType == "image")
                            {
                                UploadAsStream(data, HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galImageUploadDirectory"].ToString()) + filename);
                            }
                            else if (gType == "backgroundimage")
                            {
                                UploadAsStream(data, HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galBackImageUploadDirectory"].ToString()) + filename);
                            }
                            else
                            {
                                UploadAsStream(data, HostingEnvironment.MapPath(ConfigurationManager.AppSettings["galSoundTrackUploadDirectory"].ToString()) + filename);
                            }

                            Response = objGalManager.AddGalleryMedia(objGallery.id, filename, ThumbnailName, gType);

                            if (Response.ErrorCode == 0)
                            {
                                response.header.ErrorCode    = 200;
                                response.header.ErrorMessage = "Success";
                                response.gallery.id          = objGallery.id;
                                response.gallery.name        = objGallery.name;
                                response.gallery.galleryType = objGallery.gallery_Type;
                            }
                            else
                            {
                                response.header.ErrorCode    = 501;
                                response.header.ErrorMessage = "An Error Occured In Uploading Media , Please Try Again";
                                response.gallery             = null;
                                return(response);
                            }
                        }

                        response.header.ErrorCode    = 200;
                        response.header.ErrorMessage = "Success";
                        response.gallery.id          = objGallery.id;
                        response.gallery.name        = objGallery.name;
                        response.gallery.galleryType = objGallery.gallery_Type;
                        // response.response.TimeStamp = DateTime.Now.ToUniversalTime().ToString("u");
                    }
                    else
                    {
                        response.header.ErrorCode    = 501;
                        response.header.ErrorMessage = Response.ErrorMessage;
                        response.gallery             = null;
                        return(response);
                    }
                }
                else
                {
                    response.header.ErrorCode    = 501;
                    response.header.ErrorMessage = "An Error Occured , Please Try Again";
                    response.gallery             = null;
                    return(response);
                }
            }
            catch (Exception ex)
            {
                response.header.ErrorCode    = 501;
                response.header.ErrorMessage = "Error Occured : " + ex.Message.ToString();
                response.gallery             = null;
                return(response);
            }

            return(response);
        }
 public static string GetParameterValue(this MultipartFormDataParser parser, string parameterName, string defaultValue)
 => parser.HasParameter(parameterName) ? parser.GetParameterValue(parameterName) : defaultValue;
Ejemplo n.º 15
0
        /// <summary>
        ///     Validates the output of the parser against the expected outputs for
        ///     this test
        /// </summary>
        /// <param name="parser">
        ///     The parser to validate.
        /// </param>
        /// <returns>
        ///     The <see cref="bool" /> representing if this test passed.
        /// </returns>
        public bool Validate(MultipartFormDataParser parser)
        {
            // Deal with all the parameters who are only expected to have one value.
            var expectedParametersWithSingleValue = ExpectedParams
                                                    .GroupBy(p => p.Name)
                                                    .Where(g => g.Count() == 1)
                                                    .Select(g => g.Single());

            foreach (var expectedParameter in expectedParametersWithSingleValue)
            {
                if (!parser.HasParameter(expectedParameter.Name))
                {
                    return(false);
                }

                var actualValue           = parser.GetParameterValue(expectedParameter.Name);
                var actualValueFromValues = parser.GetParameterValues(expectedParameter.Name).Single();

                if (actualValue != actualValueFromValues)
                {
                    return(false);
                }

                if (expectedParameter.Data != actualValue)
                {
                    return(false);
                }
            }

            // Deal with the parameters who are expected to have more then one value
            var expectedParametersWithMultiValues = ExpectedParams
                                                    .GroupBy(p => p.Name)
                                                    .Where(a => a.Count() > 1);

            foreach (var expectedParameters in expectedParametersWithMultiValues)
            {
                var key = expectedParameters.Key;
                if (!parser.HasParameter(key))
                {
                    return(false);
                }

                var actualValues = parser.GetParameterValues(key);

                if (actualValues.Count() != expectedParameters.Count() || actualValues.Zip(expectedParameters, Tuple.Create).Any(t => t.Item1 != t.Item2.Data))
                {
                    return(false);
                }
            }

            // Validate files
            foreach (var filePart in ExpectedFileData)
            {
                var foundPairMatch = false;
                foreach (var file in parser.Files)
                {
                    if (filePart.Name == file.Name)
                    {
                        foundPairMatch = true;

                        FilePart expectedFile = filePart;
                        FilePart actualFile   = file;

                        if (expectedFile.Name != actualFile.Name || expectedFile.FileName != actualFile.FileName)
                        {
                            return(false);
                        }

                        if (expectedFile.ContentType != actualFile.ContentType ||
                            expectedFile.ContentDisposition != actualFile.ContentDisposition)
                        {
                            return(false);
                        }

                        // Read the data from the files and see if it's the same
                        if (expectedFile.Data.CanSeek)
                        {
                            expectedFile.Data.Position = 0;
                        }

                        string expectedFileData;
                        // The last boolean parameter MUST be set to true: it ensures the stream is left open
                        using (var reader = new StreamReader(expectedFile.Data, Encoding.UTF8, false, 1024, true))
                        {
                            expectedFileData = reader.ReadToEnd();
                        }

                        string actualFileData;
                        // The last boolean parameter MUST be set to true: it ensures the stream is left open
                        using (var reader = new StreamReader(actualFile.Data, Encoding.UTF8, false, 1024, true))
                        {
                            actualFileData = reader.ReadToEnd();
                        }

                        if (expectedFileData != actualFileData)
                        {
                            return(false);
                        }

                        break;
                    }
                }

                if (!foundPairMatch)
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 16
0
        public ActionResult UpdateUserDetails(Stream userData)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(userData);

            try
            {
                string aboutMe     = dataParser.GetParameterValue("aboutMe");
                string address     = dataParser.GetParameterValue("address");
                string city        = dataParser.GetParameterValue("city");
                string country     = dataParser.GetParameterValue("country");
                string firstName   = dataParser.GetParameterValue("firstName");
                string lastName    = dataParser.GetParameterValue("lastName");
                string token       = dataParser.GetParameterValue("token");
                string phoneNumber = dataParser.GetParameterValue("phonenumber");
                string email       = dataParser.GetParameterValue("email");

                AuthenticationService authenticationService = new AuthenticationService();
                IPrincipal            jwtToken = authenticationService.AuthenticateJwtToken(token);
                string userId = jwtToken.Identity.GetUserId();
                string path   = null;
                if (dataParser.Files.Any())
                {
                    FilePart dataParserFile = dataParser.Files[0];
                    path = ServiceHelper.SaveImage(dataParserFile.Data, dataParserFile.FileName);
                }

                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    AspNetUser netUser = entities.AspNetUsers.FirstOrDefault(a => a.Id.Equals(userId));
                    if (netUser != null)
                    {
                        netUser.Email       = String.IsNullOrEmpty(email) ? netUser.Email : email;
                        netUser.PhoneNumber = String.IsNullOrEmpty(phoneNumber) ? netUser.PhoneNumber : phoneNumber;
                    }
                    UserProfile userProfile = entities.UserProfiles.FirstOrDefault(a => a.UserId.Equals(userId));
                    if (userProfile != null)
                    {
                        userProfile.AboutMe        = String.IsNullOrEmpty(aboutMe) ? userProfile.AboutMe : aboutMe;
                        userProfile.Address        = String.IsNullOrEmpty(address) ? userProfile.Address : address;
                        userProfile.City           = String.IsNullOrEmpty(city) ? userProfile.City : city;
                        userProfile.Country        = String.IsNullOrEmpty(country) ? userProfile.Country : country;
                        userProfile.FirstName      = String.IsNullOrEmpty(firstName) ? userProfile.FirstName : firstName;
                        userProfile.LastName       = String.IsNullOrEmpty(lastName) ? userProfile.LastName : lastName;
                        userProfile.ProfilePicture = String.IsNullOrEmpty(path)?userProfile.ProfilePicture:path;
                        userProfile.UserId         = userId;
                    }
                    else
                    {
                        UserProfile addUserProfile = new UserProfile
                        {
                            DateCreated    = DateTime.Now,
                            AboutMe        = aboutMe,
                            Address        = address,
                            City           = city,
                            Country        = country,
                            FirstName      = firstName,
                            LastName       = lastName,
                            ProfilePicture = path,
                            UserId         = userId
                        };
                        entities.UserProfiles.Add(addUserProfile);
                    }
                    entities.SaveChanges();
                    return(new ActionResult
                    {
                        Message = path,
                        Success = true
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "aboutMe", dataParser.GetParameterValue("aboutMe") },
                    { "address", dataParser.GetParameterValue("address") },
                    { "city", dataParser.GetParameterValue("city") },
                    { "country", dataParser.GetParameterValue("country") },
                    { "firstName", dataParser.GetParameterValue("firstName") },
                    { "lastName", dataParser.GetParameterValue("lastName") },
                    { "userId", dataParser.GetParameterValue("userId") }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.User);
                return(new ActionResult
                {
                    Message = "Failed to save profile, try again.",
                    Success = true
                });
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Parses the inbound email webhook.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>The <see cref="InboundEmail"/></returns>
        public InboundEmail ParseInboundEmailWebhook(Stream stream)
        {
            // Parse the multipart content received from SendGrid
            var parser = new MultipartFormDataParser(stream);

            // Convert the 'headers' from a string into array of KeyValuePair
            var rawHeaders = parser
                             .GetParameterValue("headers", string.Empty)
                             .Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            var headers = rawHeaders
                          .Select(header =>
            {
                var splitHeader = header.Split(new[] { ": " }, StringSplitOptions.RemoveEmptyEntries);
                var key         = splitHeader[0];
                var value       = splitHeader.Length >= 2 ? splitHeader[1] : null;
                return(new KeyValuePair <string, string>(key, value));
            }).ToArray();

            // Conbine the 'attachment-info' and Files into a single array or Attachments
            var attachmentInfoAsJObject = JObject.Parse(parser.GetParameterValue("attachment-info", "{}"));
            var attachments             = attachmentInfoAsJObject
                                          .Properties()
                                          .Select(prop =>
            {
                var attachment = prop.Value.ToObject <InboundEmailAttachment>();
                attachment.Id  = prop.Name;
                var file       = parser.Files.FirstOrDefault(f => f.Name == prop.Name);
                if (file != null)
                {
                    attachment.ContentType = file.ContentType;
                    attachment.Data        = file.Data;
                }
                return(attachment);
            }).ToArray();

            // Convert the 'charset' from a string into array of KeyValuePair
            var charsetsAsJObject = JObject.Parse(parser.GetParameterValue("charsets", "{}"));
            var charsets          = charsetsAsJObject
                                    .Properties()
                                    .Select(prop =>
            {
                var key   = prop.Name;
                var value = Encoding.GetEncoding(prop.Value.ToString());
                return(new KeyValuePair <string, Encoding>(key, value));
            }).ToArray();

            // Convert the 'envelope' from a JSON string into a strongly typed object
            var envelope = JsonConvert.DeserializeObject <InboundEmailEnvelope>(parser.GetParameterValue("envelope", "{}"));

            // Convert the 'from' from a string into a strongly typed object
            var rawFrom    = parser.GetParameterValue("from", string.Empty);
            var piecesFrom = rawFrom.Split(new[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries);
            var from       = new MailAddress(piecesFrom[1], piecesFrom[0].Replace("\"", string.Empty).Trim());

            // Convert the 'to' from a string into a strongly typed object
            var rawTo    = parser.GetParameterValue("to", string.Empty);
            var piecesTo = rawFrom.Split(new[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries);
            var to       = new MailAddress(piecesFrom[1], piecesFrom[0].Replace("\"", string.Empty).Trim());

            // Arrange the InboundEmail
            var inboundEmail = new InboundEmail
            {
                Attachments = attachments,
                Charsets    = charsets,
                Dkim        = parser.GetParameterValue("dkim", null),
                Envelope    = envelope,
                From        = from,
                Headers     = headers,
                Html        = parser.GetParameterValue("html", null),
                SenderIp    = parser.GetParameterValue("sender_ip", null),
                SpamReport  = parser.GetParameterValue("spam_report", null),
                SpamScore   = parser.GetParameterValue("spam_score", null),
                Spf         = parser.GetParameterValue("SPF", null),
                Subject     = parser.GetParameterValue("subject", null),
                To          = to
            };

            return(inboundEmail);
        }
            /// <summary>
            ///     Validates the output of the parser against the expected outputs for
            ///     this test
            /// </summary>
            /// <param name="parser">
            ///     The parser to validate.
            /// </param>
            /// <returns>
            ///     The <see cref="bool" /> representing if this test passed.
            /// </returns>
            public bool Validate(MultipartFormDataParser parser)
            {
                // Deal with all the parameters who are only expected to have one value.
                var expectedParametersWithSingleValue = ExpectedParams
                                                        .GroupBy(p => p.Name)
                                                        .Where(g => g.Count() == 1)
                                                        .Select(g => g.Single());

                foreach (var expectedParameter in expectedParametersWithSingleValue)
                {
                    if (!parser.HasParameter(expectedParameter.Name))
                    {
                        return(false);
                    }

                    var actualValue           = parser.GetParameterValue(expectedParameter.Name);
                    var actualValueFromValues = parser.GetParameterValues(expectedParameter.Name).Single();

                    if (actualValue != actualValueFromValues)
                    {
                        Console.WriteLine("GetParameterValue vs. GetParameterValues mismatch! ({0} != {1})", actualValue, actualValueFromValues);
                        return(false);
                    }

                    Console.WriteLine("Expected {0} = {1}. Found {2} = {3}", expectedParameter.Name, expectedParameter.Data, expectedParameter.Name, actualValue);

                    if (expectedParameter.Data != actualValue)
                    {
                        return(false);
                    }
                }

                // Deal with the parameters who are expected to have more then one value
                var expectedParametersWithMultiValues = ExpectedParams
                                                        .GroupBy(p => p.Name)
                                                        .Where(a => a.Count() > 1);

                foreach (var expectedParameters in expectedParametersWithMultiValues)
                {
                    var key = expectedParameters.Key;
                    if (!parser.HasParameter(key))
                    {
                        return(false);
                    }

                    var actualValues = parser.GetParameterValues(key);

                    Console.WriteLine("Expected {0} = {1}. Found {2} = {3}",
                                      key,
                                      string.Join(",", expectedParameters.Select(p => p.Data)),
                                      key,
                                      string.Join(",", actualValues)
                                      );

                    if (actualValues.Count() != expectedParameters.Count() || actualValues.Zip(expectedParameters, Tuple.Create).Any(t => t.Item1 != t.Item2.Data))
                    {
                        return(false);
                    }
                }

                // Validate files
                foreach (var filePart in ExpectedFileData)
                {
                    var foundPairMatch = false;
                    foreach (var file in parser.Files)
                    {
                        if (filePart.Name == file.Name)
                        {
                            foundPairMatch = true;

                            FilePart expectedFile = filePart;
                            FilePart actualFile   = file;

                            if (expectedFile.Name != actualFile.Name || expectedFile.FileName != actualFile.FileName)
                            {
                                return(false);
                            }

                            if (expectedFile.ContentType != actualFile.ContentType ||
                                expectedFile.ContentDisposition != actualFile.ContentDisposition)
                            {
                                return(false);
                            }

                            // Read the data from the files and see if it's the same
                            var    reader           = new StreamReader(expectedFile.Data);
                            string expectedFileData = reader.ReadToEnd();

                            reader = new StreamReader(actualFile.Data);
                            string actualFileData = reader.ReadToEnd();

                            if (expectedFileData != actualFileData)
                            {
                                return(false);
                            }

                            break;
                        }
                    }

                    if (!foundPairMatch)
                    {
                        return(false);
                    }
                }

                return(true);
            }
Ejemplo n.º 19
0
 public string RequestBodyMultipart(string pPartname)
 {
     GetBodyFiles();
     return(_BodyParser.GetParameterValue(pPartname));
 }
Ejemplo n.º 20
0
        public CreateProductResponse CreateProduct(Stream data)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(data);
            string name             = dataParser.GetParameterValue("name");
            string description      = dataParser.GetParameterValue("description");
            string catergoryId      = dataParser.GetParameterValue("catergory");
            string price            = dataParser.GetParameterValue("price");
            string per              = dataParser.GetParameterValue("per");
            string shortDescription = dataParser.GetParameterValue("shortDescription");
            string manufacturer     = dataParser.GetParameterValue("manufacturer");
            string code             = dataParser.GetParameterValue("code");
            string userId           = dataParser.GetParameterValue("userId");
            string isMain           = dataParser.GetParameterValue("IsMain");
            string isActive         = dataParser.GetParameterValue("isActive");

            try
            {
                bool.TryParse(isMain, out bool checkMain);
                bool.TryParse(isActive, out bool checkActive);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    if (checkActive)
                    {
                        List <Product> products = entities.Products.ToList();
                        products.ForEach(a => a.IsActive = false);
                        entities.SaveChanges();
                    }
                    if (checkMain)
                    {
                        List <Product> products = entities.Products.Where(a => a.IsMain).ToList();
                        if (products.Count > 3)
                        {
                            Product productMain = products.FirstOrDefault();
                            if (productMain != null)
                            {
                                productMain.IsMain = false;
                            }
                            entities.SaveChanges();
                        }
                    }
                    Product product = new Product
                    {
                        CatergoryId      = int.Parse(catergoryId),
                        Code             = code,
                        CreatedDate      = DateTime.Now,
                        Description      = description,
                        IsDeleted        = false,
                        Manufacturer     = manufacturer,
                        ModifiedDate     = DateTime.Now,
                        Name             = name,
                        Per              = per,
                        Price            = decimal.Parse(price),
                        ShortDescription = shortDescription,
                        UserId           = userId,
                        IsMain           = checkMain,
                        IsActive         = checkActive
                    };
                    entities.Products.Add(product);
                    entities.SaveChanges();
                    string       path         = ServiceHelper.SaveImage(dataParser.Files[0].Data, dataParser.Files[0].FileName);
                    ProductMedia productMedia = new ProductMedia
                    {
                        MediaSource = path,
                        ProductId   = product.Id,
                        DateCreate  = DateTime.Now,
                        IsDeleted   = false,
                        IsMain      = true
                    };
                    entities.ProductMedias.Add(productMedia);
                    entities.SaveChanges();
                    Catergory catergory = entities.Catergories.FirstOrDefault(a => a.Id == product.CatergoryId);
                    return(new CreateProductResponse
                    {
                        DateCreated = product.CreatedDate.ToLongDateString() + " " + product.CreatedDate.ToLongTimeString(),
                        ProductId = product.Id,
                        MediaSource = path,
                        Catergory = catergory == null? "":catergory.Name
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "name", name },
                    { "description", description },
                    { "catergoryId", catergoryId },
                    { "price", price },
                    { "per", per },
                    { "shortDescription", shortDescription },
                    { "manufacturer", manufacturer },
                    { "code", code },
                    { "userId", userId },
                    { "mainImage", true.ToString() },
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Product);
                return(new CreateProductResponse());
            }
        }