public void GetStreamValidation()
        {
            Stream stream0 = null;
            Stream stream1 = null;

            try
            {
                MultipartFormDataContent content = new MultipartFormDataContent();
                content.Add(new StringContent("Not a file"), "notafile");
                content.Add(new StringContent("This is a file"), "file", "filename");

                MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());
                stream0 = instance.GetStream(content.ElementAt(0).Headers);
                Assert.IsType<FileStream>(stream0);
                stream1 = instance.GetStream(content.ElementAt(1).Headers);
                Assert.IsType<FileStream>(stream1);

                Assert.Equal(2, instance.BodyPartFileNames.Count);
                Assert.Contains("BodyPart", instance.BodyPartFileNames[0]);
                Assert.Contains("BodyPart", instance.BodyPartFileNames[1]);
            }
            finally
            {
                if (stream0 != null)
                {
                    stream0.Close();
                }

                if (stream1 != null)
                {
                    stream1.Close();
                }
            }
        }
        public void GetStreamValidation()
        {
            Stream stream0 = null;
            Stream stream1 = null;

            try
            {
                MultipartFormDataContent content = new MultipartFormDataContent();
                content.Add(new StringContent("Not a file"), "notafile");
                content.Add(new StringContent("This is a file"), "file", "filename");

                MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());
                stream0 = instance.GetStream(content.ElementAt(0).Headers);
                Assert.IsType <FileStream>(stream0);
                stream1 = instance.GetStream(content.ElementAt(1).Headers);
                Assert.IsType <FileStream>(stream1);

                Assert.Equal(2, instance.BodyPartFileNames.Count);
                Assert.Contains("BodyPart", instance.BodyPartFileNames[0]);
                Assert.Contains("BodyPart", instance.BodyPartFileNames[1]);
            }
            finally
            {
                if (stream0 != null)
                {
                    stream0.Close();
                }

                if (stream1 != null)
                {
                    stream1.Close();
                }
            }
        }
        public void EmptyBodyPartFileNames()
        {
            MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());

            Assert.NotNull(instance.BodyPartFileNames);
            Assert.Equal(0, instance.BodyPartFileNames.Count);
        }
Esempio n. 4
0
        public async Task PostMultipartStream()
        {
            // Verify that this is an HTML Form file upload request
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string tempDir = HttpContext.Current.Server.MapPath("~/App_Data/temp");
            var provider = new MultipartFileStreamProvider(tempDir);
            var multipart = await Request.Content.ReadAsMultipartAsync(provider);
            foreach (var fileData in multipart.FileData)
            {
                try
                {
                    var lines = File.ReadAllLines(fileData.LocalFileName);
                    var report = Parser.parse(lines);
                    this.reportLoader.LoadReport(report);
                }
                finally
                {
                    File.Delete(fileData.LocalFileName);
                }
            }
        }
        public void FileData_IsEmpty()
        {
            MultipartFileStreamProvider provider = new MultipartFileStreamProvider(
                ValidPath,
                ValidBufferSize
                );

            Assert.Empty(provider.FileData);
        }
        public HttpResponseMessage Post(HttpRequestMessage message)
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                return message.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            var streamProvider = new MultipartFileStreamProvider(Environment.CurrentDirectory);

            var bodyParts = Request.Content.ReadAsMultipartAsync(streamProvider);
            bodyParts.Wait();

            var fileNames = streamProvider.Contents;

            return message.CreateResponse(HttpStatusCode.Created, fileNames);
        }
        public void GetStream()
        {
            Stream stream0 = null;
            Stream stream1 = null;

            try
            {
                string tempPath = Path.GetTempPath();
                MultipartFormDataContent content = new MultipartFormDataContent();
                content.Add(new StringContent("Content 1"), "NoFile");
                content.Add(new StringContent("Content 2"), "File", "Filename");

                MultipartFileStreamProvider provider = new MultipartFileStreamProvider(tempPath);
                stream0 = provider.GetStream(content, content.ElementAt(0).Headers);
                stream1 = provider.GetStream(content, content.ElementAt(1).Headers);

                Assert.IsType <FileStream>(stream0);
                Assert.IsType <FileStream>(stream1);

                Assert.Equal(2, provider.FileData.Count);
                string partialFileName = String.Format("{0}BodyPart_", tempPath);
                Assert.Contains(partialFileName, provider.FileData[0].LocalFileName);
                Assert.Contains(partialFileName, provider.FileData[1].LocalFileName);

                Assert.Same(
                    content.ElementAt(0).Headers.ContentDisposition,
                    provider.FileData[0].Headers.ContentDisposition
                    );
                Assert.Same(
                    content.ElementAt(1).Headers.ContentDisposition,
                    provider.FileData[1].Headers.ContentDisposition
                    );
            }
            finally
            {
                if (stream0 != null)
                {
                    stream0.Close();
                }

                if (stream1 != null)
                {
                    stream1.Close();
                }
            }
        }
Esempio n. 8
0
		public async Task<HttpResponseMessage> ImportDatabase(int batchSize, bool includeExpiredDocuments, bool stripReplicationInformation, ItemType operateOnTypes, string filtersPipeDelimited, string transformScript)
		{
			if (!Request.Content.IsMimeMultipartContent())
			{
				throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
			}

			string tempPath = Path.GetTempPath();
			var fullTempPath = tempPath + Constants.TempUploadsDirectoryName;
			if (File.Exists(fullTempPath))
				File.Delete(fullTempPath);
			if (Directory.Exists(fullTempPath) == false)
				Directory.CreateDirectory(fullTempPath);

			var streamProvider = new MultipartFileStreamProvider(fullTempPath);
			await Request.Content.ReadAsMultipartAsync(streamProvider).ConfigureAwait(false);
			var uploadedFilePath = streamProvider.FileData[0].LocalFileName;
			
			string fileName = null;
			var fileContent = streamProvider.Contents.SingleOrDefault();
			if (fileContent != null)
			{
				fileName = fileContent.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
			}

			var status = new ImportOperationStatus();
			var cts = new CancellationTokenSource();
			
			var task = Task.Run(async () =>
			{
				try
				{
					using (var fileStream = File.Open(uploadedFilePath, FileMode.Open, FileAccess.Read))
					{
						var dataDumper = new DatabaseDataDumper(Database);
						dataDumper.Progress += s => status.LastProgress = s;
                        var smugglerOptions = dataDumper.Options;
						smugglerOptions.BatchSize = batchSize;
						smugglerOptions.ShouldExcludeExpired = !includeExpiredDocuments;
					    smugglerOptions.StripReplicationInformation = stripReplicationInformation;
						smugglerOptions.OperateOnTypes = operateOnTypes;
						smugglerOptions.TransformScript = transformScript;
						smugglerOptions.CancelToken = cts;

						// Filters are passed in without the aid of the model binder. Instead, we pass in a list of FilterSettings using a string like this: pathHere;;;valueHere;;;true|||againPathHere;;;anotherValue;;;false
						// Why? Because I don't see a way to pass a list of a values to a WebAPI method that accepts a file upload, outside of passing in a simple string value and parsing it ourselves.
						if (filtersPipeDelimited != null)
						{
							smugglerOptions.Filters.AddRange(filtersPipeDelimited
								.Split(new string[] { "|||" }, StringSplitOptions.RemoveEmptyEntries)
								.Select(f => f.Split(new string[] { ";;;" }, StringSplitOptions.RemoveEmptyEntries))
								.Select(o => new FilterSetting { Path = o[0], Values = new List<string> { o[1] }, ShouldMatch = bool.Parse(o[2]) }));
						}

						await dataDumper.ImportData(new SmugglerImportOptions<RavenConnectionStringOptions> { FromStream = fileStream });
					}
				}
				catch (Exception e)
				{
				    status.Faulted = true;
				    status.State = RavenJObject.FromObject(new
				                                           {
				                                               Error = e.ToString()
				                                           });
					if (cts.Token.IsCancellationRequested)
					{
                        status.State = RavenJObject.FromObject(new { Error = "Task was cancelled"  });
						cts.Token.ThrowIfCancellationRequested(); //needed for displaying the task status as canceled and not faulted
					}

                    if (e is InvalidDataException)
                    {
                        status.ExceptionDetails = e.Message;
                    }
                    else if (e is Imports.Newtonsoft.Json.JsonReaderException)
                    {
                        status.ExceptionDetails = "Failed to load JSON Data. Please make sure you are importing .ravendump file, exported by smuggler (aka database export). If you are importing a .ravnedump file then the file may be corrupted";
                    }
                    else
                    {
                        status.ExceptionDetails = e.ToString();
                    }
					throw;
				}
				finally
				{
					status.Completed = true;
					File.Delete(uploadedFilePath);
				}
			}, cts.Token);

			long id;
			Database.Tasks.AddTask(task, status, new TaskActions.PendingTaskDescription
			{
				StartTime = SystemTime.UtcNow,
				TaskType = TaskActions.PendingTaskType.ImportDatabase,
				Payload = fileName,
				
			}, out id, cts);

			return GetMessageWithObject(new
			{
				OperationId = id
			});
		}
        private static string ParseImages(string body, MultipartFileStreamProvider multiPartRequest)
        {
            return Regex.Replace(body, @"\[i:(\d+)\:(.*?)]", m =>
            {
                var index = m.Groups[1].Value.TryConvertTo<int>();
                if (index)
                {
                    //get the file at this index
                    var file = multiPartRequest.FileData[index.Result];

                    var rndId = Guid.NewGuid().ToString("N");

                    using (var stream = File.OpenRead(file.LocalFileName))
                    {
                        var savedFile = UmbracoMediaFile.Save(stream, "articulate/" + rndId + "/" +
                                                                      file.Headers.ContentDisposition.FileName.TrimStart("\"").TrimEnd("\""));

                        var result = string.Format("![{0}]({1})",
                            savedFile.Url,
                            savedFile.Url
                            );

                        return result;
                    }
                }

                return m.Value;
            });
        }
 private static void CleanFiles(MultipartFileStreamProvider multiPartRequest)
 {
     foreach (var f in multiPartRequest.FileData)
     {
         File.Delete(f.LocalFileName);
     }
 }
        public void GetStreamThrowsOnNull()
        {
            MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());

            Assert.ThrowsArgumentNull(() => { instance.GetStream(null); }, "headers");
        }
        public async Task<List<GroupBuyStoreMenuImage>> Post(int id)
        {
            //var streamProvider = new MultipartFormDataStreamProvider(ServerUploadFolder);

            //await Request.Content.ReadAsMultipartAsync(streamProvider);



            var provider = new MultipartFileStreamProvider(Path.GetTempPath());

            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);
            foreach (MultipartFileData file in provider.FileData)
            {
                //string fileName = blobSaveFile(file);
                string fileName = localSaveFile(file);
                GroupBuyStoreMenuImage image = new GroupBuyStoreMenuImage()
                {
                    StoreId = id,
                    ImageUrl = fileName
                };

                using (var db = new HoGameEISContext())
                {
                    db.GroupBuyStoreMenuImages.Add(image);
                    db.SaveChanges();
                }
            }
            return Get(id);
        }
 public void GetStreamThrowsOnNull()
 {
     MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());
     Assert.ThrowsArgumentNull(() => { instance.GetStream(null); }, "headers");
 }
 public void EmptyBodyPartFileNames()
 {
     MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());
     Assert.NotNull(instance.BodyPartFileNames);
     Assert.Equal(0, instance.BodyPartFileNames.Count);
 }
Esempio n. 15
0
		public async Task<HttpResponseMessage> ImportFilesystem(int batchSize)
		{
			if (!Request.Content.IsMimeMultipartContent())
			{
				throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
			}

			string tempPath = Path.GetTempPath();
			var fullTempPath = tempPath + Constants.TempUploadsDirectoryName;
			if (File.Exists(fullTempPath))
				File.Delete(fullTempPath);
			if (Directory.Exists(fullTempPath) == false)
				Directory.CreateDirectory(fullTempPath);

			var streamProvider = new MultipartFileStreamProvider(fullTempPath);
			await Request.Content.ReadAsMultipartAsync(streamProvider).ConfigureAwait(false);
			var uploadedFilePath = streamProvider.FileData[0].LocalFileName;

			string fileName = null;
			var fileContent = streamProvider.Contents.SingleOrDefault();
			if (fileContent != null)
			{
				fileName = fileContent.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
			}

			var status = new ImportOperationStatus();
			var cts = new CancellationTokenSource();

			var task = Task.Run(async () =>
			{
				try
				{
					var dataDumper = new FilesystemDataDumper(FileSystem);
					dataDumper.Progress += s => status.LastProgress = s;
					var smugglerOptions = dataDumper.Options;
					smugglerOptions.BatchSize = batchSize;
					smugglerOptions.CancelToken = cts;

					await dataDumper.ImportData(new SmugglerImportOptions<FilesConnectionStringOptions> { FromFile = uploadedFilePath });
				}
				catch (Exception e)
				{
					status.Faulted = true;
					status.State = RavenJObject.FromObject(new
					{
						Error = e.ToString()
					});
					if (cts.Token.IsCancellationRequested)
					{
						status.State = RavenJObject.FromObject(new { Error = "Task was cancelled" });
						cts.Token.ThrowIfCancellationRequested(); //needed for displaying the task status as canceled and not faulted
					}

					if (e is InvalidDataException)
					{
						status.ExceptionDetails = e.Message;
					}
					else
					{
						status.ExceptionDetails = e.ToString();
					}
					throw;
				}
				finally
				{
					status.Completed = true;
					File.Delete(uploadedFilePath);
				}
			}, cts.Token);

			long id;
			FileSystem.Tasks.AddTask(task, status, new TaskActions.PendingTaskDescription
			{
				StartTime = SystemTime.UtcNow,
				TaskType = TaskActions.PendingTaskType.ImportFileSystem,
				Payload = fileName,

			}, out id, cts);

			return GetMessageWithObject(new
			{
				OperationId = id
			});
		}
		public async Task<IHttpActionResult> SaveImageItem(string storeId, string themeId, string folderName)
		{
			if (!Request.Content.IsMimeMultipartContent())
			{
				throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
			}

			var provider = new MultipartFileStreamProvider(_pathForMultipart);

			await Request.Content.ReadAsMultipartAsync(provider);

			var loadItemInfo = new LoadItemInfo();

			foreach (var file in provider.FileData)
			{
				var fileInfo = new FileInfo(file.LocalFileName);
				using (FileStream stream = fileInfo.OpenRead())
				{
					var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
					var filePath = string.Format("{0}{1}", _pathForFiles, fileName);

					using (var f = File.Create(filePath))
					{
						await stream.CopyToAsync(f);
					}

					loadItemInfo.Name = fileName;
					loadItemInfo.ContentType = file.Headers.ContentType.MediaType;
					if (ContentTypeUtility.IsImageContentType(loadItemInfo.ContentType))
					{
						loadItemInfo.Content = ContentTypeUtility.
							ConvertImageToBase64String(File.ReadAllBytes(filePath), file.Headers.ContentType.MediaType);
					}
				}
			}

			return this.Ok(loadItemInfo);
		}