public override void OnProcessRequest(HttpContext context)
        {
            try
            {
                var request = new ChunkedRequestHelper(context.Request);

                if (!TryAuthorize(request))
                {
                    WriteError(context, "Can't authorize given initiate session request or session with specified upload id already expired");
                    return;
                }

                if (CoreContext.TenantManager.GetCurrentTenant().Status != TenantStatus.Active)
                {
                    WriteError(context, "Can't perform upload for deleted or transfering portals");
                    return;
                }

                switch (request.Type)
                {
                case ChunkedRequestType.Abort:
                    FileUploader.AbortUpload(request.UploadId);
                    WriteSuccess(context, null);
                    return;

                case ChunkedRequestType.Initiate:
                    var createdSession = FileUploader.InitiateUpload(request.FolderId, request.FileId, request.FileName, request.FileSize, request.Encrypted);
                    WriteSuccess(context, ToResponseObject(createdSession, true));
                    return;

                case ChunkedRequestType.Upload:
                    var resumedSession = FileUploader.UploadChunk(request.UploadId, request.ChunkStream, request.ChunkSize);

                    if (resumedSession.BytesUploaded == resumedSession.BytesTotal)
                    {
                        WriteSuccess(context, ToResponseObject(resumedSession.File), (int)HttpStatusCode.Created);
                        FilesMessageService.Send(resumedSession.File, context.Request, MessageAction.FileUploaded, resumedSession.File.Title);
                    }
                    else
                    {
                        WriteSuccess(context, ToResponseObject(resumedSession));
                    }
                    return;

                default:
                    WriteError(context, "Unknown request type.");
                    return;
                }
            }
            catch (FileNotFoundException error)
            {
                Global.Logger.Error(error);
                WriteError(context, FilesCommonResource.ErrorMassage_FileNotFound);
            }
            catch (Exception error)
            {
                Global.Logger.Error(error);
                WriteError(context, error.Message);
            }
        }
Beispiel #2
0
        private void uploadFiles(List <FileItem> filesToUpload)
        {
            this.uploadedBytes.Clear();
            ManualResetEvent[] doneEvents = null;
            int taskMax = filesToUpload.Count;

            doneEvents       = new ManualResetEvent[taskMax];
            this.uploadInfos = new UploadInfo[taskMax];
            for (int taskId = 0; taskId < taskMax; taskId++)
            {
                this.uploadInfos[taskId] = new UploadInfo();
                doneEvents[taskId]       = new ManualResetEvent(false);
                FileUploader uploader = new FileUploader(this.syncSetting, doneEvents[taskId], this, taskId);
                ThreadPool.QueueUserWorkItem(new WaitCallback(uploader.uploadFile), filesToUpload[taskId]);
            }

            try
            {
                WaitHandle.WaitAll(doneEvents);
            }
            catch (Exception ex)
            {
                Log.Error("wait for job to complete error, " + ex.Message);
            }
        }
        public ImageDetectionResult scoreSingleImage(string imagePath)
        {
            byte[] data = File.ReadAllBytes(imagePath);

            // Generate post objects
            Dictionary <string, object> postParameters = new Dictionary <string, object>();

            postParameters.Add("filename", "Image.jpg");
            postParameters.Add("fileformat", "jpg");
            postParameters.Add("file", new FileUploader.FileParameter(data, "Image.jpg", "image/jpeg"));

            // Create request and receive response
            try
            {
                HttpWebResponse webResponse = FileUploader.MultipartFormDataPost(_serviceUrl, "Prometheus", postParameters);

                if (webResponse != null)
                {
                    // Process response
                    StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                    string       fullResponse   = responseReader.ReadToEnd();
                    webResponse.Close();

                    return(JsonConvert.DeserializeObject <ImageDetectionResult>(fullResponse));
                }

                ServiceRunning = false;
                return(null);
            }
            catch (SocketException ex)
            {
                ServiceRunning = false;
                return(null);
            }
        }
        public ActionResult UploadReResolvedChecksFile(FileViewModel model)
        {
            if (ModelState.IsValid)
            {
                var postedFile = Request.Files["File"];

                string fname = postedFile.FileName;

                if (!fname.EndsWith("xlsx"))
                {
                    ModelState.AddModelError("ReresolvedChecksError", "This is not an Excel xlsx file.");
                    return(View("Merge", model));
                }

                List <string> docfiles = FileUploader.UploadFile(postedFile);
                TempData["UploadedFile"]    = fname;
                TempData["FileType"]        = "ReresolvedChecks";
                ViewData["UploadedRRCFile"] = string.Format("Uploaded File: {0}", fname);

                return(View("MistakenlyResolved", model));
            }

            ModelState.AddModelError("ReresolvedChecksError", "Please supply a file name.");
            return(View("Merge", model));
        }
Beispiel #5
0
        public ActionResult ChangeCover(String userId, HttpPostedFileBase image)
        {
            var service = this.Service <IAspNetUserService>();

            ResponseModel <String> response = null;

            FileUploader uploader = new FileUploader();

            try
            {
                String path = null;

                if (image != null)
                {
                    path = uploader.UploadImage(image, userImagePath);
                }


                String result = service.ChangeCover(userId, path);

                response = new ResponseModel <String>(true, "Ảnh bìa của bạn đã được cập nhật!", null, result);
            }
            catch (Exception)
            {
                response = ResponseModel <String> .CreateErrorResponse("Ảnh bìa của bạn chưa được cập nhật!", systemError);
            }

            return(Json(response));
        }
        public ActionResult MergeAncientChecksFile(FileViewModel model)
        {
            if (ModelState.IsValid)
            {
                var postedFile = Request.Files["File"];

                string fname = postedFile.FileName;

                if (!fname.EndsWith("xlsx"))
                {
                    ModelState.AddModelError("AncientChecksFileError", "This is not an Excel xlsx file.");
                    return(View("Rebuild", model));
                }

                List <string> docfiles = FileUploader.UploadFile(postedFile);
                string        pathToAncientChecksFile = string.Format("~/Uploads/{0}", fname);
                string        mappedPath = HttpContext.Server.MapPath(pathToAncientChecksFile);

                Merger.PerformMerge(mappedPath, "AncientChecksFile");

                ViewData["MergedAncientChecksFile"] = string.Format("Merged File: {0}", fname);
                return(View("Rebuild", model));
            }

            ModelState.AddModelError("AncientChecksFileError", "Please supply a file name.");
            return(View("Rebuild", model));
        }
        public ActionResult RestoreResearchTable(FileViewModel model)
        {
            if (!CheckManager.ResearchTableIsEmpty())
            {
                ModelState.AddModelError("", "The Research Table must be empty before a restore is performed.");
                return(View("ResearchTable", model));
            }

            if (ModelState.IsValid)
            {
                var postedFile = Request.Files["File"];

                if (!postedFile.FileName.EndsWith("xlsx"))
                {
                    ModelState.AddModelError("", "This is not an Excel xlsx file.");
                    return(View("ResearchTable", model));
                }

                List <string> docfiles = FileUploader.UploadFile(postedFile);

                CheckManager.RestoreResearchTable(postedFile.FileName);

                return(View("RecentChecks", model));
            }

            return(View(model));
        }
Beispiel #8
0
        // 上传状态改变时触发
        protected override void OnUploadStatusChanged(object sender, EventArgs e)
        {
            FileUploader fu = sender as FileUploader;

            if (fu.UploadStatus == UploadStatus.Complete)
            {
                if (!String.IsNullOrEmpty(fu.CompletedFileString) && UploadedFilesString.IndexOf(fu.CompletedFileString) < 0)
                {
                    UploadedFilesString += fu.CompletedFileString + ",";
                }

                if (IsUploading)
                {
                    UploadFile();
                }
            }
            else if (fu.UploadStatus == UploadStatus.Removed)
            {
                m_files.Remove(fu);

                if (IsUploading)
                {
                    UploadFile();
                }
            }
            else if (fu.UploadStatus == UploadStatus.Uploading && m_files.Count(f => f.UploadStatus == UploadStatus.Uploading) < MaxConcurrentUploads)
            {
                UploadFile();
            }
        }
        public async Task <News> CreateNews(NewsViewModel model, string userId, HttpPostedFileBase file = null)
        {
            var filePath = string.Empty;

            if (file != null)
            {
                var directoryPath = HttpContext.Current.Server.MapPath(Constants.NewsImagesPath);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                //upload file
                filePath = Path.Combine($"{model.CompanyId}{DateTime.Now.Millisecond}{Path.GetFileName(file.FileName)}");
                var fullPath = Path.Combine(directoryPath, filePath);
                FileUploader.UploadFile(file.InputStream, fullPath);
            }

            var news = new News
            {
                Title       = model.Title,
                CreatedAt   = DateTime.Now,
                Description = model.Content,
                ImagePath   = filePath,
                UserId      = userId,
                CompanyId   = model.CompanyId
            };

            _db.News.Add(news);
            await _db.SaveChangesAsync();

            return(_db.News.OrderByDescending(n => n.Id)?.FirstOrDefault());
        }
Beispiel #10
0
        public static void T()
        {
            FileUploader loader = new FileUploader();

            loader.FileUploaded += Progress;
            loader.Upload();
        }
Beispiel #11
0
 public UsuarioController(RepositoryJugadores repo, FileUploader uploader, ServiceEquipos service, ServiceStorageFile storageFile)
 {
     this.repo        = repo;
     this.uploader    = uploader;
     this.service     = service;
     this.storageFile = storageFile;
 }
        private void AssertPostFileComposesMultiPartRequest <TResponse>(IReturn <TResponse> requestDto)
        {
            var postUrl        = $"http://somehost{requestDto.ToPostUrl()}";
            var queryString    = QueryStringSerializer.SerializeToString(requestDto);
            var isImport       = FileUploader.IsImportServiceUpload(postUrl);
            var streamToUpload = CreateMemoryStream(_mockFileSize);

            _uploader.PostFileWithRequest(postUrl, streamToUpload, _mockFilename, requestDto);

            var expectedUri = new UriBuilder(postUrl)
            {
                Query = queryString
            }.ToString();

            if (isImport)
            {
                _mockRestClient
                .Received(1)
                .Post <TResponse>(Arg.Is(expectedUri), Arg.Is <object>(content => IsImportServiceContent(content)));
            }
            else
            {
                _mockRestClient
                .Received(1)
                .Post <TResponse>(Arg.Is(expectedUri), Arg.Is <object>(content => IsFineUploaderContent(content)));
            }
        }
Beispiel #13
0
        private string UploadFile(string base64Path, string directoryPath)
        {
            try
            {
                if (base64Path.Contains(DBO.Common.Constants.UserImagePath))
                {
                    return(base64Path);
                }

                var path         = string.Empty;
                var base64String = base64Path.Split(';')[1].Split(',')[1];
                var extension    = base64Path.Split(';')[0].Split(':')[1].Split('/')[1];
                var fileBytes    = Convert.FromBase64String(base64String);
                using (var ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
                {
                    if (!Directory.Exists(DBO.Common.Constants.UserImagePath))
                    {
                        Directory.CreateDirectory(DBO.Common.Constants.UserImagePath);
                    }

                    //upload file
                    var filePathGuid = $"{Guid.NewGuid().ToString()}.{extension}";
                    var fullPath     = Path.Combine(directoryPath, filePathGuid);

                    FileUploader.UploadFile(ms, fullPath);

                    path = $"{DBO.Common.Constants.UserImagePath}{filePathGuid}";
                }
                return(path);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #14
0
    protected void UploadButton_Click(object sender, EventArgs e)
    {
        if (FileUploader.HasFile)
        {
            try
            {
                FileUploader.SaveAs(Server.MapPath("../news_image//") +
                                    FileUploader.FileName);
                Label8.Text = "File name: " +

                              FileUploader.PostedFile.FileName + "<br>" +
                              //FileUploader.PostedFile.ContentLength + " kb<br>" +

                              "Content type: " +
                              FileUploader.PostedFile.ContentType + "<br><b>Uploaded Successfully";

                Label2.Text = "~/news_image/" + FileUploader.PostedFile.FileName;
            }
            catch (Exception ex)
            {
                Label8.Text = "ERROR: " + ex.Message.ToString();
            }
        }
        else
        {
            Label8.Text = "You have not specified a file.";
        }
    }
Beispiel #15
0
 public ActionResult Registration(UserAccount useraccount, HttpPostedFileBase file)
 {
     try
     {
         if (ModelState.IsValid)
         {
             //string ImageName = System.IO.Path.GetFileName(file.FileName);
             //string physicalPath = Server.MapPath("~/Content/Image/User/" + ImageName);
             //file.SaveAs(physicalPath);
             var fileName = FileUploader.FileUpload(this.ControllerContext, "Content/Image/User/").FirstOrDefault();
             if (fileName != null)
             {
                 useraccount.UserImage = fileName;
                 db.UserAccounts.Add(useraccount);
                 db.SaveChanges();
             }
             return(RedirectToAction("Registration"));
         }
     }
     catch (RetryLimitExceededException /* dex */)
     {
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
     }
     return(View(useraccount));
 }
Beispiel #16
0
        public void ReturnExpectedImageName_WhenImageIsUploadedSuccesfully()
        {
            // Arrange
            var postedFileMock = new Mock <HttpPostedFileBase>();

            using (var stream = new MemoryStream())
                using (var bmp = new Bitmap(1, 1))
                {
                    var graphics = Graphics.FromImage(bmp);
                    graphics.FillRectangle(Brushes.Black, 0, 0, 1, 1);
                    bmp.Save(stream, ImageFormat.Jpeg);

                    postedFileMock.Setup(pf => pf.InputStream).Returns(stream);
                    postedFileMock.Setup(pf => pf.ContentLength).Returns((int)stream.Length);
                    postedFileMock.Setup(pf => pf.FileName).Returns("TestImage");
                }

            var           dataMock      = new Mock <IPickAndBookData>();
            IFileUploader fileUploader  = new FileUploader(new TestPathProvider());
            string        path          = "/Test";
            string        expectedImage = Path.Combine(path, "TestImage");

            // Act
            string uploadedImage = fileUploader.UploadFile(postedFileMock.Object, path);

            // Assert
            Assert.AreEqual(expectedImage, uploadedImage);
        }
        public ActionResult Edit(EditDocumentViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var document = db.Documents.Include(x => x.Images).FirstOrDefault(x => x.Id == model.Id);

            if (document == null)
            {
                throw new HttpException(404, "Не найдено");
            }

            document.DocumentName = model.DocumentName;

            //Загружаем изображение, если есть
            if (model.UploadedImage != null && model.UploadedImage.ContentLength > 0)
            {
                var image = new DocumentImage()
                {
                    ImageUrl = FileUploader.UploadFile(model.UploadedImage)
                };
                document.Images.Add(image);
            }

            //Сохраняем изменения
            db.Entry(document).State = EntityState.Modified;
            db.SaveChanges();
            return(RedirectToAction("Edit", "AdminDocuments", new { id = model.Id }));
        }
        private void SaveUploaderImage()
        {
            if (FileUploader.HasFile)
            {
                var extension = Path.GetExtension(FileUploader.FileName) ?? string.Empty;

                var allowedExtensions = Utilities.GetImageExtensions();

                if (allowedExtensions.Contains(extension.ToLower()) && int.TryParse(Request.QueryString["ID"], out _movieId))
                {
                    var fullName       = FileUploader.FileName.ToAZ09Dash(true, true);
                    var resultFilePath = Server.MapPath(ConfigAssistant.ImageFolderRelativePath) + fullName;

                    FileUploader.SaveAs(resultFilePath);

                    _movieFile.TSP_MovieFiles_Image(0, null, _movieId, fullName);

                    Session[Master.SessionShowSuccess] = true;
                }
                else
                {
                    Session[Master.SessionShowError] = new KeyValuePair <bool, string>(true, "Allowed extensions are: .jpg, .jpeg, .gif, .png");
                }

                Response.Redirect(Request.Url.AbsoluteUri);
            }
        }
 public ChunkedUploaderHandlerService(
     IOptionsMonitor <ILog> optionsMonitor,
     TenantManager tenantManager,
     FileUploader fileUploader,
     FilesMessageService filesMessageService,
     AuthManager authManager,
     SecurityContext securityContext,
     SetupInfo setupInfo,
     EntryManager entryManager,
     InstanceCrypto instanceCrypto,
     ChunkedUploadSessionHolder chunkedUploadSessionHolder,
     ChunkedUploadSessionHelper chunkedUploadSessionHelper)
 {
     TenantManager              = tenantManager;
     FileUploader               = fileUploader;
     FilesMessageService        = filesMessageService;
     AuthManager                = authManager;
     SecurityContext            = securityContext;
     SetupInfo                  = setupInfo;
     EntryManager               = entryManager;
     InstanceCrypto             = instanceCrypto;
     ChunkedUploadSessionHolder = chunkedUploadSessionHolder;
     ChunkedUploadSessionHelper = chunkedUploadSessionHelper;
     Logger = optionsMonitor.CurrentValue;
 }
Beispiel #20
0
        // 加载缩略图
        protected virtual void LoadImage(FileUploader fileUploader)
        {
            if (fileUploader != null && fileUploader.DisplayThumbnail && (fileUploader.FileName.ToLower().EndsWith("jpg") || fileUploader.FileName.ToLower().EndsWith("png")))
            {
                if (!m_isImageSet)
                {
                    BitmapImage imageSource = new BitmapImage();

                    try
                    {
                        imageSource.SetSource(fileUploader.File.OpenRead());
                        imagePreview.Source     = imageSource;
                        m_isImageSet            = true;
                        imagePreview.Visibility = Visibility.Visible;
                    }
                    catch (Exception e)
                    {
                        string message = e.Message;
                    }
                }
                else
                {
                    imagePreview.Visibility = Visibility.Visible;
                }
            }
            else
            {
                imagePreview.Visibility = Visibility.Collapsed;
            }
        }
        private void UploadData(object stateInfo)
        {
            var thread = new Thread(() =>
            {
                if (!Monitor.TryEnter(FileUploader.FileUploadLock, FileUploader.fileUploadLockTimeout))
                {
                    Log.Debug("Skipping file upload as it is already in progress.");
                    return;
                }

                try
                {
                    FileUploader.Start((IOutput)stateInfo, options.ProcessedFilestTTL, options.StorageLimit);
                }
                catch (Exception e)
                {
                    Log.Error(e, "Error while uploading data to insight server.");
                }
                finally
                {
                    Monitor.Exit(FileUploader.FileUploadLock);
                }
            });

            thread.IsBackground = true;
            thread.Start();
        }
Beispiel #22
0
        /// <summary>
        /// 创建一个附件
        /// </summary>
        /// <param name="validationErrors">返回的错误信息</param>
        /// <param name="db">数据库上下文</param>
        /// <param name="entity">一个附件</param>
        /// <returns></returns>
        public bool Create(ref ValidationErrors validationErrors, SysEntities db, FileUploader entity)
        {
            int count = 1;

            foreach (string item in entity.SysPersonId.GetIdSort())
            {
                SysPerson sys = new SysPerson {
                    Id = item
                };
                db.SysPerson.Attach(sys);
                entity.SysPerson.Add(sys);
                count++;
            }

            repository.Create(db, entity);
            if (count == repository.Save(db))
            {
                return(true);
            }
            else
            {
                validationErrors.Add("创建出错了");
            }
            return(false);
        }
Beispiel #23
0
        public void TestGetFileNameWithoutPart_withSequence()
        {
            var expected = "countersamples-2016-05-23--13-15-15.csv.gz";
            var actual   = FileUploader.GetFileNameWithoutPart("countersamples-2016-05-23--13-15-15--seq0000--part0000.csv.gz");

            Assert.AreEqual(expected, actual);
        }
Beispiel #24
0
        public string CreateLoginHistoryReport()
        {
            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            string fileUrl;

            var to   = DateTime.UtcNow;
            var from = to.AddMonths(-6);

            var events     = LoginEventsRepository.Get(CurrentTenant, from, to);
            var reportPath = AuditReportCreator.CreateXlsxReport(events);

            try
            {
                var reportName = string.Format(AuditReportResource.LoginHistoryReportName + ".xlsx", from.ToString("MM.dd.yyyy"), to.ToString("MM.dd.yyyy"));
                using (var stream = new FileStream(reportPath, FileMode.Open))
                {
                    var file = FileUploader.Exec(Global.FolderMy.ToString(), reportName, stream.Length, stream, true);
                    fileUrl = FilesLinkUtility.GetFileWebEditorUrl((int)file.ID);
                }
            }
            finally
            {
                AuditReportCreator.DeleteReport(reportPath);
            }

            MessageService.Send(context, MessageAction.LoginHistoryReportDownloaded);

            return(fileUrl);
        }
Beispiel #25
0
        public override View Draw(FormMode Mode, NetworkMode Network)
        {
            XamControl = new FileUploader(this);
            XControl   = XamControl;

            return(base.Draw(Mode, Network));
        }
Beispiel #26
0
        public void TestGetFileNameWithoutPart_csvgz()
        {
            var expected = "http_requests-2016-03-22--07-42-20.csv.gz";
            var actual   = FileUploader.GetFileNameWithoutPart("http_requests-2016-03-22--07-42-20--part0000.csv.gz");

            Assert.AreEqual(expected, actual);
        }
        public JsonResult ProductAddPhoto(int id)
        {
            var file     = Request.Files.Get("myfile");
            var uploader = new FileUploader(file);

            var result = new
            {
                filename      = uploader.Name,
                contentType   = uploader.ContentType,
                contentLength = uploader.ContentLength,
                newFilename   = uploader.UniqueName
            };

            try
            {
                uploader.Save("products");
                _productImageRepository.Save(new ProductImage()
                {
                    ProductId = id,
                    Link      = uploader.UniqueName
                });
            }
            catch (Exception)
            {
                return(Json(new { status = "fail" }, "text/html"));
            }
            return(Json(result, "text/html"));
        }
Beispiel #28
0
        public static string CreateCsvReport(IEnumerable <AuditEvent> events, string reportName)
        {
            try
            {
                using (var stream = new MemoryStream())
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvWriter(writer))
                        {
                            csv.Configuration.RegisterClassMap <AuditEventMap>();

                            csv.WriteHeader <AuditEvent>();
                            foreach (var evt in events)
                            {
                                csv.WriteRecord(evt);
                            }

                            writer.Flush();

                            var file    = FileUploader.Exec(Global.FolderMy.ToString(), reportName, stream.Length, stream, true);
                            var fileUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl((int)file.ID));

                            fileUrl += string.Format("&options={{\"delimiter\":{0},\"codePage\":{1}}}",
                                                     (int)FileUtility.CsvDelimiter.Comma,
                                                     Encoding.UTF8.CodePage);
                            return(fileUrl);
                        }
            }
            catch (Exception ex)
            {
                Log.Error("Error while generating audit report: " + ex);
                throw;
            }
        }
Beispiel #29
0
        public string CreateCsvReport <TEvent>(IEnumerable <TEvent> events, string reportName) where TEvent : BaseEvent
        {
            try
            {
                using (var stream = new MemoryStream())
                    using (var writer = new StreamWriter(stream, Encoding.UTF8))
                        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                        {
                            csv.Configuration.RegisterClassMap(new BaseEventMap <TEvent>());

                            csv.WriteHeader <TEvent>();
                            csv.NextRecord();
                            csv.WriteRecords(events);
                            writer.Flush();

                            var file    = FileUploader.Exec(GlobalFolderHelper.FolderMy, reportName, stream.Length, stream, true);
                            var fileUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                            fileUrl += string.Format("&options={{\"delimiter\":{0},\"codePage\":{1}}}",
                                                     (int)FileUtility.CsvDelimiter.Comma,
                                                     Encoding.UTF8.CodePage);
                            return(fileUrl);
                        }
            }
            catch (Exception ex)
            {
                Log.Error("Error while generating login report: " + ex);
                throw;
            }
        }
Beispiel #30
0
        //
        // GET: /Upload/

        public ActionResult Index(string dir)
        {
            FileUploader uploader = null;
            string       status   = "";

            try
            {
                if (Request.QueryString["qqfile"] != null)
                {
                    uploader = new XhrFileUploader();
                }
                else if (Request.Files["qqfile"] != null)
                {
                    uploader = new FormFileUploader();
                }

                string uploadBasePath = Server.MapPath(dir);

                if (uploader != null)
                {
                    uploader.Save(uploadBasePath + "\\" + uploader.Name);
                    status = "OK";
                }
                else
                {
                    status = "Couldn't find file in request";
                }
            }
            catch (Exception ex)
            {
                status = ex.Message;
            }

            return(Content("{ 'success' : \"" + status.Replace("\"", "'") + "\" }"));
        }
        public void SetUp() {
            _strategy = A.Fake<IUploadProtocol>();
            A.CallTo(() => _strategy.Schemes)
                .Returns(new[] {"http"});

            var authProvider = A.Fake<IAuthProvider>();
            A.CallTo(() => authProvider.HandleUri(new Uri(TestUrl)))
                .Returns(new Uri(TestUrl));

            _uploader = new FileUploader(new[] {_strategy}, authProvider);
        }
Beispiel #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Email" /> class.
 /// </summary>
 public Email()
 {
     tbFromName = new RockTextBox();
     tbFromAddress = new RockTextBox();
     tbReplyToAddress = new RockTextBox();
     tbSubject = new RockTextBox();
     htmlMessage = new HtmlEditor();
     tbTextMessage = new RockTextBox();
     hfAttachments = new HiddenField();
     fuAttachments = new FileUploader();
 }
        public async Task<JsonResult> Upload()
        {
            try
            {
                foreach (string file in Request.Files)
                {
                    var fileContent = Request.Files[file];
                    if (fileContent != null && fileContent.ContentLength > 0)
                    {
                        var uploader = new FileUploader(fileContent, "files");
                        var uploadedFile = await uploader.Upload();
                    }
                }
            }
            catch (Exception)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json("Upload failed");
            }

            return Json("File uploaded successfully");
        }
Beispiel #34
0
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            Controls.Clear();

            tbFromName = new RockTextBox();
            tbFromName.ID = string.Format( "tbFromName_{0}", this.ID );
            tbFromName.Label = "From Name";
            Controls.Add( tbFromName );

            lFromName = new RockLiteral();
            lFromName.ID = string.Format( "lFromName_{0}", this.ID );
            lFromName.Label = "From Name";
            Controls.Add( lFromName );

            ebFromAddress = new EmailBox();
            ebFromAddress.ID = string.Format( "ebFromAddress_{0}", this.ID );
            ebFromAddress.Label = "From Address";
            Controls.Add( ebFromAddress );

            lFromAddress = new RockLiteral();
            lFromAddress.ID = string.Format( "lFromAddress_{0}", this.ID );
            lFromAddress.Label = "From Address";
            Controls.Add( lFromAddress );

            ebReplyToAddress = new EmailBox();
            ebReplyToAddress.ID = string.Format( "ebReplyToAddress_{0}", this.ID );
            ebReplyToAddress.Label = "Reply To Address";
            Controls.Add( ebReplyToAddress );

            tbSubject = new RockTextBox();
            tbSubject.ID = string.Format( "tbSubject_{0}", this.ID );
            tbSubject.Label = "Subject";
            tbSubject.Help = "<span class='tip tip-lava'></span>";
            Controls.Add( tbSubject );

            htmlMessage = new HtmlEditor();
            htmlMessage.ID = string.Format( "htmlMessage_{0}", this.ID );
            //htmlMessage.AdditionalConfigurations = "autoParagraph: false,";
            htmlMessage.Help = "<span class='tip tip-lava'></span> <span class='tip tip-html'>";
            this.AdditionalMergeFields.ForEach( m => htmlMessage.MergeFields.Add( m ) );
            htmlMessage.Label = "Message";
            htmlMessage.Height = 600;
            Controls.Add( htmlMessage );

            tbTextMessage = new RockTextBox();
            tbTextMessage.ID = string.Format( "tbTextMessage_{0}", this.ID );
            tbTextMessage.Label = "Message (Text Version)";
            tbTextMessage.TextMode = TextBoxMode.MultiLine;
            tbTextMessage.Rows = 5;
            tbTextMessage.CssClass = "span12";
            Controls.Add( tbTextMessage );

            hfAttachments = new HiddenField();
            hfAttachments.ID = string.Format( "hfAttachments_{0}", this.ID );
            Controls.Add( hfAttachments );

            fuAttachments = new FileUploader();
            fuAttachments.ID = string.Format( "fuAttachments_{0}", this.ID );
            fuAttachments.Label = "Attachments";
            fuAttachments.FileUploaded += fuAttachments_FileUploaded;
            Controls.Add( fuAttachments );
        }
Beispiel #35
0
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            Controls.Clear();

            tbFromName = new RockTextBox();
            tbFromName.ID = string.Format( "tbFromName_{0}", this.ID );
            tbFromName.Label = "From Name";
            Controls.Add( tbFromName );

            tbFromAddress = new RockTextBox();
            tbFromAddress.ID = string.Format( "tbFromAddress_{0}", this.ID );
            tbFromAddress.Label = "From Address";
            Controls.Add( tbFromAddress );

            tbReplyToAddress = new RockTextBox();
            tbReplyToAddress.ID = string.Format( "tbReplyToAddress_{0}", this.ID );
            tbReplyToAddress.Label = "Reply To Address";
            Controls.Add( tbReplyToAddress );

            tbSubject = new RockTextBox();
            tbSubject.ID = string.Format( "tbSubject_{0}", this.ID );
            tbSubject.Label = "Subject";
            Controls.Add( tbSubject );

            htmlMessage = new HtmlEditor();
            htmlMessage.ID = string.Format( "htmlMessage_{0}", this.ID );
            htmlMessage.AdditionalConfigurations = "autoParagraph: false,";
            htmlMessage.MergeFields.Clear();
            htmlMessage.MergeFields.Add( "GlobalAttribute" );
            htmlMessage.MergeFields.Add( "Rock.Model.Person" );
            htmlMessage.MergeFields.Add( "UnsubscribeOption" );
            this.AdditionalMergeFields.ForEach( m => htmlMessage.MergeFields.Add( m ) );
            htmlMessage.Label = "Message";
            htmlMessage.Height = 600;
            Controls.Add( htmlMessage );

            tbTextMessage = new RockTextBox();
            tbTextMessage.ID = string.Format( "tbTextMessage_{0}", this.ID );
            tbTextMessage.Label = "Message (Text Version)";
            tbTextMessage.TextMode = TextBoxMode.MultiLine;
            tbTextMessage.Rows = 5;
            tbTextMessage.CssClass = "span12";
            Controls.Add( tbTextMessage );

            hfAttachments = new HiddenField();
            hfAttachments.ID = string.Format( "hfAttachments_{0}", this.ID );
            Controls.Add( hfAttachments );

            fuAttachments = new FileUploader();
            fuAttachments.ID = string.Format( "fuAttachments_{0}", this.ID );
            fuAttachments.Label = "Attachments";
            fuAttachments.FileUploaded += fuAttachments_FileUploaded;
            Controls.Add( fuAttachments );
        }
    protected void Upload(object sender, EventArgs e)
    {
		RobotTableAdapters.documents_attachmentTableAdapter robotAttachment = new RobotTableAdapters.documents_attachmentTableAdapter();
        string filename = new FileUploader().uploadFile(FileUpload1); int documentId = 0;
        int collateralId = Convert.ToInt32(Request.QueryString["collateralId"]); 
        if ((hiddenDocID.Text) != null & (hiddenDocID.Text != ""))
        {
            //return;
            documentId = Convert.ToInt32(hiddenDocID.Text);
            robotAttachment.proc_AllocateFileToDocument(filename, documentId, collateralId);
            TextBox1.Text = documentId.ToString();
        }
        else
        {
            robotAttachment.proc_AllocateFileToDocument(filename, Convert.ToInt32(TextBox1.Text), collateralId);         
        } 
    }
Beispiel #37
0
 private void FillFieldTypeOptions()
 {
     ContentTypeInfo contentTypeInfo = _contentTypeProvider.Select(ContentTypeId, ErrorList);
     if (contentTypeInfo != null)
     {
         FieldInfo info = FieldInfo.GetFieldArray(contentTypeInfo.FieldsXml).FirstOrDefault(x => x.Name == Id);
         pnlCustomControlOptions.Controls.Clear();
         switch (FormHelper.GetFieldTypeByCode(drlFieldType.SelectedValue))
         {
             case FormFieldType.TextBoxControl:
                 TextBoxControl control = new TextBoxControl();
                 control.ViewMode = FormControlViewMode.Development;
                 control.ID = FormFieldTypeCode.TEXTBOX;
                 if (info != null)
                     control.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(control);
                 break;
             case FormFieldType.DatePickerControl:
                 DatePicker datepicker = new DatePicker();
                 datepicker.ViewMode = FormControlViewMode.Development;
                 datepicker.ID = FormFieldTypeCode.DATEPICKER;
                 if (info != null)
                     datepicker.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(datepicker);
                 break;
             case FormFieldType.DateTimePickerControl:
                 DateTimePicker datetimepicker = new DateTimePicker();
                 datetimepicker.ViewMode = FormControlViewMode.Development;
                 datetimepicker.ID = FormFieldTypeCode.DATETIMEPICKER;
                 if (info != null)
                     datetimepicker.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(datetimepicker);
                 break;
             case FormFieldType.YesNoSelector:
                 YesNoSelector yesnoselector = new YesNoSelector();
                 yesnoselector.ViewMode = FormControlViewMode.Development;
                 yesnoselector.ID = FormFieldTypeCode.YESNOSELECTOR;
                 if (info != null)
                     yesnoselector.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(yesnoselector);
                 break;
             case FormFieldType.FileUpload:
                 FileUploader fuploader = new FileUploader();
                 fuploader.ViewMode = FormControlViewMode.Development;
                 fuploader.ID = FormFieldTypeCode.FILEUPLOAD;
                 if (info != null)
                     fuploader.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(fuploader);
                 break;
             case FormFieldType.YearSelector:
                 YearSelector yearselector = new YearSelector();
                 yearselector.ViewMode = FormControlViewMode.Development;
                 yearselector.ID = FormFieldTypeCode.YEARSELECTOR;
                 if (info != null)
                     yearselector.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(yearselector);
                 break;
             case FormFieldType.CaptchaControl:
                 AbstractBasicUserControl captcha =
                     (AbstractBasicUserControl)
                     this.Page.LoadControl("~/");
                 captcha.ViewMode = FormControlViewMode.Development;
                 captcha.ID = FormFieldTypeCode.CAPTCHA;
                 if (info != null)
                     captcha.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(captcha);
                 break;
             case FormFieldType.GuidGenerator:
                 GuidGeneratorControl guidcontrol = new GuidGeneratorControl();
                 guidcontrol.ViewMode = FormControlViewMode.Development;
                 pnlCustomControlOptions.Controls.Add(guidcontrol);
                 break;
             case FormFieldType.FckEditor:
                 FckEditorControl fckeditor = new FckEditorControl();
                 fckeditor.ID = FormFieldTypeCode.FCKEDITOR;
                 fckeditor.ViewMode = FormControlViewMode.Development;
                 if (info != null)
                     fckeditor.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(fckeditor);
                 break;
             case FormFieldType.ListLookUp:
                 ListLookUp listLookUp = new ListLookUp();
                 listLookUp.ViewMode = FormControlViewMode.Development;
                 listLookUp.ID = FormFieldTypeCode.LISTLOOKUP;
                 if (info != null)
                     listLookUp.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(listLookUp);
                 break;
             case FormFieldType.ContentTypeLookUp:
                 ContentTypeLookUp contentTypeLookUp = new ContentTypeLookUp();
                 contentTypeLookUp.ViewMode = FormControlViewMode.Development;
                 contentTypeLookUp.ID = FormFieldTypeCode.CONTENTTYPELOOKUP;
                 if (info != null)
                     contentTypeLookUp.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(contentTypeLookUp);
                 break;
             case FormFieldType.ParameterGetter:
                 ParameterGetterControl parameterGetterControl = new ParameterGetterControl();
                 parameterGetterControl.ID = FormFieldTypeCode.PARAMETERGETTER;
                 parameterGetterControl.ViewMode = FormControlViewMode.Development;
                 if (info != null)
                     parameterGetterControl.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(parameterGetterControl);
                 break;
             case FormFieldType.UserProfileGetter:
                 FromUserProfileControl userProfileControl = new FromUserProfileControl();
                 userProfileControl.ID = FormFieldTypeCode.USERPROFILEGETTER;
                 userProfileControl.ViewMode = FormControlViewMode.Development;
                 if (info != null)
                     userProfileControl.Value = info.Options;
                 pnlCustomControlOptions.Controls.Add(userProfileControl);
                 break;
             //Load Custom Form control
             default:
                 //AbstractBasicUserControl abstarctcontrol =
                 //    this.CreateCustomFormControl(ddlFieldType.SelectedItem.Value);
                 //abstarctcontrol.Value = info.Options;
                 //pnlCustomControlOptions.Controls.Add(abstarctcontrol);
                 break;
         }
     }
 }
 protected void Upload(object sender, EventArgs e)
 {
     RobotTableAdapters.documents_attachmentTableAdapter robotAttachment = new RobotTableAdapters.documents_attachmentTableAdapter();
     string filename = new FileUploader().uploadFile(FileUpload1); int documentId = 0;
     int collateralId = Convert.ToInt32(Request.QueryString["collateralId"]); 
     int CollateralTypeId = Convert.ToInt32(Request.QueryString["CollateralTypeId"]);
     int CollateralDetailsId = Convert.ToInt32(hiddenDetailsId.Text);
     
     if ((hiddenDocID.Text) != null & (hiddenDocID.Text != ""))
     {
         //return;
         documentId = Convert.ToInt32(hiddenDocID.Text);
         //robotAttachment.Insert(filename, documentId, collateralId);
         robotAttachment.proc_AllocateFileToDocument(filename, documentId, collateralId, CollateralDetailsId, CollateralTypeId,Smart.GetEmployeeID());         
         
         TextBox1.Text = documentId.ToString();
     }
     else
     {
         
         robotAttachment.proc_AllocateFileToDocument(filename, Convert.ToInt32(TextBox1.Text), collateralId, CollateralDetailsId, CollateralTypeId, Smart.GetEmployeeID());
     } 
     UpdateDocumentCategory();
 docGrid.DataBind();
 }
Beispiel #39
0
        public bool AddVM(VMDetails VMData)
        {

            var FP = VMData.UtilFileLocation;
            var FU = new FileUploader();
            var blob = FU.UploadFileToStorage(FP, true);
            var comm = new MLCommunicator();
            var result = comm.GetUtilDataFromFile(blob);
            var d = result.Result;
            var UtilData = new UtilizationCalculator();
            var UD = UtilData.getUtilPattern(d);

            AddVMInDB(VMData, blob, UD);

            // now we need to insert this data in SQL Azure for the given VM

            foreach (var u in UD)
            {
                Console.WriteLine(u.UtilizationType);
                foreach (var tr in u.TimeRanges)
                {
                    Console.WriteLine("{0}, {1}", tr.StartTime, tr.StopTime);
                }
            }
            //  populateTreeView();
            return true;

            // return Json(true, JsonRequestBehavior.AllowGet);

        }