//Download Action
        public async Task <IActionResult> Download(string filename)
        {
            if (filename == null)
            {
                return(Content("filename not present"));
            }

            var path = Path.Combine(Directory.GetCurrentDirectory(), Services.Constants.StoragePath, filename);

            var memory = new MemoryStream();

            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }

            //update download counter
            using (var ctx = new FileUploadContext())
            {
                ctx.Files.FirstOrDefault(f => f.FileName == filename).Downloads++;

                ctx.SaveChanges();
            }
            Startup.fileUploadModels.FirstOrDefault(f => f.FileName == filename).Downloads++;

            memory.Position = 0;
            return(File(memory, MimeTypesMap.GetMimeType(filename), Path.GetFileName(path)));
        }
        public ActionResult UploadFiles([FromForm] FileUploadModel fileUploadModel)
        {
            try
            {
                using (FileUploadContext dbContext = new FileUploadContext())
                {
                    var engModel = new EngagementUploadFile()
                    {
                        FileName     = fileUploadModel.FileName,
                        UploadedBy   = fileUploadModel.UploadedBy,
                        UploadedDate = DateTime.Now
                    };

                    using (var memoryStream = new MemoryStream())
                    {
                        fileUploadModel.File.CopyTo(memoryStream);
                        engModel.UploadedFile    = memoryStream.ToArray();
                        engModel.FileContentType = fileUploadModel.File.ContentType;
                    }

                    dbContext.EngagementUploadFile.Add(engModel);
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
            }
            return(Ok());
        }
示例#3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            try
            {
                HttpPostedFile file = Request.Files["uploaded"];

                ZipFile       zipFile    = ZipFile.Read(file.InputStream);
                StringBuilder zipContent = new StringBuilder();
                foreach (var zipEntry in zipFile.Entries)
                {
                    MemoryStream memoryStream = new MemoryStream();
                    zipEntry.Extract(memoryStream);

                    memoryStream.Position = 0;
                    StreamReader reader = new StreamReader(memoryStream);
                    zipContent.AppendLine(reader.ReadToEnd());
                }

                FileUploadContext db = new FileUploadContext();
                db.Files.Add(new Models.File()
                {
                    Content = zipContent.ToString()
                });
                db.SaveChanges();


                Response.ContentType = "application/json";
                Response.Write("{}");
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
        public static async Task Run(
            [QueueTrigger("contacts", Connection = "AzureWebJobsStorage")] string contactJson,
            ILogger log,
            ExecutionContext context)
        {
            var logPrefix = GetLogPrefix();

            log.LogInformation($"{logPrefix}: {contactJson}");

            var contactFromFile = JsonConvert.DeserializeObject <FileUploadContact>(contactJson);

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", true, true)
                         .AddEnvironmentVariables()
                         .Build();
            var sqlConnectionString = config.GetConnectionString("Sql");
            var fileUploadContext   = new FileUploadContext(sqlConnectionString);

            var getEmployerQuery = new GetEmployerQuery(fileUploadContext);
            var employerInSql    = await getEmployerQuery.Execute(contactFromFile.CompanyName, contactFromFile.CreatedOnCompany);

            if (employerInSql == null)
            {
                // TODO Employer has to exist
            }

            var getContactQuery = new GetContactQuery(fileUploadContext);
            var contactInSql    = await getContactQuery.Execute(contactFromFile.CompanyName, contactFromFile.CreatedOnCompany);

            var contact = ContactMapper.Map(contactFromFile, contactInSql, employerInSql.Id);

            if (contactInSql == null)
            {
                log.LogInformation($"{logPrefix} Creating Contact: {contactFromFile.Contact}");

                var createEmployerCommand = new CreateContactCommand(fileUploadContext);
                await createEmployerCommand.Execute(contact);

                log.LogInformation($"{logPrefix} Created Contact: {contactFromFile.Contact}");
            }
            else
            {
                var areEqual = contactInSql.Equals(contact);
                if (!areEqual)
                {
                    log.LogInformation($"{logPrefix} Updating Contact: {contactFromFile.Contact}");

                    var updateContactCommand = new UpdateContactCommand(fileUploadContext);
                    await updateContactCommand.Execute(contact);

                    log.LogInformation($"{logPrefix} Updated Contact: {contactFromFile.Contact}");
                }
            }

            log.LogInformation($"{logPrefix} Processed Contact: {contactFromFile.Contact}");
        }
        public async Task <IActionResult> Post(List <IFormFile> files)
        {
            var value = HttpContext.Session.GetString("user");

            User user = JsonConvert.DeserializeObject <User>(value);

            var ticketno = Convert.ToInt32(Request.Form["tt"]);

            System.Diagnostics.Debug.WriteLine("ticketno id" + ticketno);

            long size = files.Sum(f => f.Length);

            // full path to file in temp location

            var filePath = "";

            // filePath += Path.GetTempFileName();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    filePath  = "Uploads/";
                    filePath += user.user_name;
                    // Directory.CreateDirectory(filePath);


                    //using (var stream = new FileStream(Path.Combine(filePath, formFile.FileName), FileMode.Create))
                    //{

                    //   await formFile.CopyToAsync(stream);

                    //}

                    using (var memoryStream = new MemoryStream())
                    {
                        await formFile.CopyToAsync(memoryStream);

                        byte[] file = memoryStream.ToArray();

                        FileUploadContext context = HttpContext.RequestServices.GetService(typeof(FileUploadContext)) as FileUploadContext;
                        context.SaveToDatabase(file, formFile.FileName, formFile.ContentType, ticketno);
                        //context.GetFileNames();
                    }
                }
            }



            // process uploaded files
            // Don't rely on or trust the FileName property without validation.

            // return Ok(new { count = files.Count, size, filePath });
            // TempData["User"] = user;
            return(RedirectToAction("Index", "Dashboard", user));
            //  return View("Index","Dashboard");
        }
        public static async Task Run(
            [TimerTrigger("%TimerInterval%")] TimerInfo timer,
            ILogger log,
            [Queue("employers", Connection = "AzureWebJobsStorage")] IAsyncCollector <string> employerOutput,
            [Queue("contacts", Connection = "AzureWebJobsStorage")] IAsyncCollector <string> contactOutput,
            [Queue("queries", Connection = "AzureWebJobsStorage")] IAsyncCollector <string> queryOutput,
            ExecutionContext context)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            var sqlConnectionString      = config.GetConnectionString("Sql");
            var storageAccountConnection = config.GetConnectionString("StorageAccount");

            var fileUploadContext = new FileUploadContext(sqlConnectionString);

            var getFileUploadQuery = new GetFileUploadQuery(fileUploadContext);
            var filesToProcess     = await getFileUploadQuery.Execute();

            var updateFileUploadCommand = new UpdateFileUploadCommand(fileUploadContext);

            var filesToProcessGroupedByType = filesToProcess.GroupBy(f => f.Type);

            foreach (var files in filesToProcessGroupedByType)
            {
                var fileUploadType = (FileUploadType)files.Key;
                //var containerName = GetContainerName(fileUploadType);
                var fileUploads = files.ToList();

                var queueOutput = GetQueueOutput(fileUploadType,
                                                 employerOutput,
                                                 contactOutput,
                                                 queryOutput);

                var blobImport = BlobImportFactory.Create(fileUploadContext, fileUploadType, storageAccountConnection);
                var import     = await blobImport.Import(fileUploads, queueOutput);

                if (import.IsSuccess)
                {
                    foreach (var fu in fileUploads)
                    {
                        fu.ProcessedOn = DateTime.Now;
                    }

                    await updateFileUploadCommand.Execute(fileUploads);
                }
            }
        }
 public void DoAfterPostUploadWork(BlogFileUploader fileUploader, string postId)
 {
     foreach (ISupportingFile file in _fileList)
     {
         string uploadContext = fileUploader.DestinationContext;
         if (_uploadedFiles.ContainsKey(file.FileId))
         {
             ISupportingFileUploadInfo uploadInfo        = file.GetUploadInfo(uploadContext);
             FileUploadContext         fileUploadContext = new FileUploadContext(fileUploader, postId, file, uploadInfo, false);
             fileUploader.DoUploadWorkAfterPublish(fileUploadContext);
         }
     }
 }
示例#8
0
            public void DoUploadWork(string fileReference, BlogFileUploader fileUploader, bool isLightboxCloneEnabled)
            {
                // Get both strings into the same state which is unescaped
                string          unescapedFileReference = new Uri(fileReference).ToString();
                ISupportingFile file = null;

                foreach (ISupportingFile supportingFile in _fileList)
                {
                    if (supportingFile.FileUri.ToString() == unescapedFileReference)
                    {
                        file = supportingFile;
                        break;
                    }
                }

                if (file == null)
                {
                    string listString = "";
                    foreach (ISupportingFile supportingFile in _fileList)
                    {
                        listString += supportingFile.FileUri + "\r\n";
                    }
                    Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Reference found to file that does not exist in SupportingFileService \r\nfileReference: {0}\r\n_fileList:\r\n{1}", fileReference, listString));
                    return;
                }


                string uploadContext = fileUploader.DestinationContext;

                ISupportingFileUploadInfo uploadInfo        = file.GetUploadInfo(uploadContext);
                FileUploadContext         fileUploadContext = new FileUploadContext(fileUploader, _postId, file, uploadInfo, isLightboxCloneEnabled);

                if (fileUploader.DoesFileNeedUpload(file, fileUploadContext))
                {
                    if (!_uploadedFiles.ContainsKey(file.FileId))
                    {
                        _uploadedFiles[file.FileId] = file;
                        Uri uploadUri = fileUploader.DoUploadWorkBeforePublish(fileUploadContext);
                        if (uploadUri != null)
                        {
                            file.MarkUploaded(uploadContext, uploadUri);
                            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "File Uploaded: {0}", file.FileName));
                        }
                    }
                    else
                    {
                        Trace.Fail("This file has already been uploaded during this publish operation: " + file.FileName);
                    }
                }
            }
示例#9
0
        protected void Page_PreRender(object sender, EventArgs e)
        {
            FileUploadContext db = new FileUploadContext();

            StringBuilder sb = new StringBuilder();

            foreach (var item in db.Files)
            {
                sb.AppendFormat("{0}. <br/>", item.Id);
                sb.AppendFormat("{0} <br/>", item.Content);
            }

            this.FileOutput = sb.ToString();
        }
示例#10
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (_context == null)
            {
                return;
            }

            _context.Dispose();
            _context = null;
        }
        public static async Task Run(
            [QueueTrigger("employers", Connection = "AzureWebJobsStorage")] string employersJson,
            ILogger log,
            ExecutionContext context)
        {
            var logPrefix = GetLogPrefix();

            log.LogInformation($"{logPrefix}: {employersJson}");

            var employerFromFile = JsonConvert.DeserializeObject <FileUploadEmployer>(employersJson);

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", true, true)
                         .AddEnvironmentVariables()
                         .Build();
            var sqlConnectionString = config.GetConnectionString("Sql");
            var fileUploadContext   = new FileUploadContext(sqlConnectionString);

            var getEmployerQuery = new GetEmployerQuery(fileUploadContext);
            var employerInSql    = await getEmployerQuery.Execute(employerFromFile.Account);

            var employer = EmployerMapper.Map(employerFromFile, employerInSql);

            if (employerInSql == null)
            {
                log.LogInformation($"{logPrefix} Creating Employer: {employerFromFile.Account}");
                var createEmployerCommand = new CreateEmployerCommand(fileUploadContext);
                await createEmployerCommand.Execute(employer);

                log.LogInformation($"{logPrefix} Created Employer: {employerFromFile.Account}");
            }
            else
            {
                var areEqual = employerInSql.Equals(employer);
                if (!areEqual)
                {
                    log.LogInformation($"{logPrefix} Updating Employer: {employerFromFile.Account}");

                    var updateEmployerCommand = new UpdateEmployerCommand(fileUploadContext);
                    await updateEmployerCommand.Execute(employer);

                    log.LogInformation($"{logPrefix} Updated Employer: {employerFromFile.Account}");
                }
            }

            log.LogInformation($"{logPrefix} Processed Employer: {employerFromFile.Account}");
        }
        public async Task <ActionResult> DownloadFiles(int engagementUploadFileID)
        {
            try
            {
                using (FileUploadContext dbContext = new FileUploadContext())
                {
                    EngagementUploadFile engUploadFile =
                        dbContext.EngagementUploadFile.Where(obj => obj.Id == engagementUploadFileID).FirstOrDefault();


                    return(File(new MemoryStream(engUploadFile.UploadedFile), engUploadFile.FileContentType, engUploadFile.FileName));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#13
0
        public void DeleteFile(string filename)
        {
            if (filename != null)
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), Constants.StoragePath, filename);

                File.Delete(path);
                Startup.fileUploadModels.RemoveAll(f => f.FileName == filename);

                using (var ctx = new FileUploadContext())
                {
                    FileUploadModel file = ctx.Files.Where(f => f.FileName == filename).FirstOrDefault();

                    ctx.Files.Remove(file);
                    ctx.SaveChanges();
                }
            }
        }
示例#14
0
        private static List <FileUploadModel> GetFiles()
        {
            List <FileUploadModel> files = new List <FileUploadModel>();

            List <FileUploadModel> fileUploads;

            using (var ctx = new FileUploadContext())
            {
                fileUploads = ctx.Files.AsEnumerable <FileUploadModel>().ToList();
            }

            string[] filesInDir = Directory.GetFiles("FileStorage");

            if (filesInDir.Length > 0)
            {
                foreach (string file in filesInDir)
                {
                    FileUploadModel fileUpload;

                    string fileName = file.Split('\\')[1];

                    if (fileUploads.Any(f => f.FileName == fileName))
                    {
                        fileUpload = fileUploads.Where(f => f.FileName == fileName).FirstOrDefault();
                    }
                    else
                    {
                        fileUpload = new FileUploadModel()
                        {
                            Id         = Guid.NewGuid(),
                            Author     = "System",
                            FileName   = fileName,
                            Created_At = DateTime.Now,
                            Downloads  = 0
                        };
                    }

                    files.Add(fileUpload);
                }
            }
            return(files);
        }
示例#15
0
        public async Task <FileUploadResult <Photo> > UploadPhoto(FileUploadContext context)
        {
            RawUploadResult result = new ImageUploadResult();

            using (context.Stream)
            {
                var @params = new ImageUploadParams()
                {
                    File   = new FileDescription(context.FileName, context.Stream),
                    Folder = Core.CLOUDINARY_BASE_FOLDER + "/" + context.Folder
                };

                result = await Cloudinary.UploadAsync(@params);
            }

            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return new FileUploadResult <Photo>
                       {
                           Success = false,
                           Message = $"Failed to upload image.\n{result.Error.Message}"
                       }
            }
            ;


            return(new FileUploadResult <Photo>
            {
                Entity = new Photo()
                {
                    Name = context.FileName,
                    Url = result.Uri.OriginalString,
                    Signature = result.Signature
                },
                Success = true,
                Url = result.Uri.OriginalString,
            });
        }

        #endregion
    }
示例#16
0
        public void UploadFiles(List <IFormFile> files, string name)
        {
            long size = files.Sum(f => f.Length);

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    // full path to file
                    var filePath = Path.Join(Constants.StoragePath, formFile.FileName);
                    //Save File Info
                    FileUploadModel fileUploadModel = new FileUploadModel()
                    {
                        Id         = Guid.NewGuid(),
                        Author     = name,
                        FileName   = formFile.FileName,
                        Created_At = DateTime.Now,
                        Downloads  = 0
                    };

                    if (!Startup.fileUploadModels.Any(f => f.FileName == fileUploadModel.FileName))
                    {
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            formFile.CopyTo(stream);
                        }

                        using (var ctx = new FileUploadContext())
                        {
                            ctx.Files.Add(fileUploadModel);
                            ctx.SaveChanges();
                        }

                        Startup.fileUploadModels.Add(fileUploadModel);
                    }
                }
            }
        }
示例#17
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="context">Db context</param>
 public FileStorageProvider(FileUploadContext context)
 {
     this.context = context;
 }
 public void DoAfterPostUploadWork(BlogFileUploader fileUploader, string postId)
 {
     foreach (ISupportingFile file in _fileList)
     {
         string uploadContext = fileUploader.DestinationContext;
         if (_uploadedFiles.ContainsKey(file.FileId))
         {
             ISupportingFileUploadInfo uploadInfo = file.GetUploadInfo(uploadContext);
             FileUploadContext fileUploadContext = new FileUploadContext(fileUploader, postId, file, uploadInfo, false);
             fileUploader.DoUploadWorkAfterPublish(fileUploadContext);
         }
     }
 }
示例#19
0
 public FileRepository(FileUploadContext context)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
 }
示例#20
0
 public OrdersController(FileUploadContext context)
 {
     _context = context;
 }
            public void DoUploadWork(string fileReference, BlogFileUploader fileUploader, bool isLightboxCloneEnabled)
            {
                // Get both strings into the same state which is unescaped
                string unescapedFileReference = new Uri(fileReference).ToString();
                ISupportingFile file = null;
                foreach (ISupportingFile supportingFile in _fileList)
                {
                    if (supportingFile.FileUri.ToString() == unescapedFileReference)
                    {
                        file = supportingFile;
                        break;
                    }
                }

                if (file == null)
                {
                    string listString = "";
                    foreach (ISupportingFile supportingFile in _fileList)
                    {
                        listString += supportingFile.FileUri + "\r\n";
                    }
                    Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Reference found to file that does not exist in SupportingFileService \r\nfileReference: {0}\r\n_fileList:\r\n{1}", fileReference, listString));
                    return;
                }

                string uploadContext = fileUploader.DestinationContext;

                ISupportingFileUploadInfo uploadInfo = file.GetUploadInfo(uploadContext);
                FileUploadContext fileUploadContext = new FileUploadContext(fileUploader, _postId, file, uploadInfo, isLightboxCloneEnabled);

                if (fileUploader.DoesFileNeedUpload(file, fileUploadContext))
                {
                    if (!_uploadedFiles.ContainsKey(file.FileId))
                    {
                        _uploadedFiles[file.FileId] = file;
                        Uri uploadUri = fileUploader.DoUploadWorkBeforePublish(fileUploadContext);
                        if (uploadUri != null)
                        {
                            file.MarkUploaded(uploadContext, uploadUri);
                            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "File Uploaded: {0}", file.FileName));
                        }
                    }
                    else
                    {
                        Trace.Fail("This file has already been uploaded during this publish operation: " + file.FileName);
                    }
                }

            }
 public SectionsController(FileUploadContext context)
 {
     _context = context;
 }
示例#23
0
 public FilesController(FileUploadContext context, IHostingEnvironment env)
 {
     _context = context;
     _env     = env;
 }