Наследование: System.Web.UI.Page
 public static Certificate Build(Upload upload)
 {
     return new Certificate
     {
         CertificateUrl = upload.Url
     };
 }
Пример #2
0
        public void StartWatching(Upload upload)
        {
            // only need to watch if the datasource is a spreadsheet
            if (upload.DataSourceType == DataSourceType.Spreadsheet)
            {
                // try and find an existing watcher
                FileWatchers result = _watcherList.Find(
                    delegate(FileWatchers fw)
                    {
                        return fw.Upload == upload;
                    }
                );

                if (result == null)
                {
                    // start new
                    FileWatchers fw = new FileWatchers();
                    fw.FileWatcher = StartWatching(upload.DataSource);
                    fw.Upload = upload;

                    _watcherList.Add(fw);
                }
                else
                {
                    // restart existing
                    result.Upload = upload;
                    result.FileWatcher.Dispose(); // releases any held resources from previous source
                    result.FileWatcher.Path = upload.DataSource; // update if user has made changes
                    result.FileWatcher.EnableRaisingEvents = true;
                }
            }
        }
Пример #3
0
 public Item(string uploadId, string remainder)
     : base(remainder)
 {
     int iUploadId;
     if(!int.TryParse(uploadId, out iUploadId)) {
         string[] parts = uploadId.Split('.');
         if(parts.Length != 2) throw new FLocalException("wrong url");
         if(parts[0].Substring(0, 4).ToLower() != "file") throw new FLocalException("wrong url");
         int rawFileNum = int.Parse(parts[0].Substring(4));
         switch(parts[1].ToLower()) {
             case "jpg":
                 iUploadId = rawFileNum;
                 break;
             case "gif":
                 iUploadId = 5000000 + rawFileNum;
                 break;
             case "png":
                 iUploadId = 6000000 + rawFileNum;
                 break;
             default:
                 throw new FLocalException("wrong url");
         }
     }
     this.upload = Upload.LoadById(iUploadId);
 }
Пример #4
0
        public ActionResult Index(FormCollection collection)
        {
            var item = new Upload();
            var whiteList = new string[] { "Artist", "Name", "Tab", "BookId" };
            if (TryUpdateModel(item, whiteList, collection.ToValueProvider()))
            {
                if (ModelState.IsValid)
                {
                    //_uploadService.Upload(item.Artist, item.Name, item.BookId, item.Tab, User.Identity.Name);

                    var tab = new Tab { Artist = item.Artist, Name = item.Name, Content = item.Tab, CreatedOn = DateTime.UtcNow, AuthorName = User.Identity.Name };
                    RavenSession.Store(tab);

                    if (item.BookId > 0)
                    {
                        var bookTasks = new BookService();
                        bookTasks.AddTabToBook(tab.Id, item.BookId.Value, RavenSession);
                    }

                    TempData.Add(Constants.TempDataMessage, "Upload successful, thanks!");

                    return RedirectToAction("Index", "Songs");
                }
            }
            return View();
        }
Пример #5
0
 public static Photo Build(Upload upload)
 {
     return new Photo
     {
         PhotoUrl = upload.Url,
         Index = upload.Index,
     };
 }
Пример #6
0
 public static Video Build(Upload upload)
 {
     return new Video
     {
         VideoUrl = upload.Url,
         VideoType = VideoType.Unknown
     };
 }
Пример #7
0
        /// <summary>
        /// Get a IList of Gene.
        /// </summary>
        /// <param name="iSession"></param>
        /// <returns></returns>
        public static IList<Gene> GetGeneList(ISession iSession, Upload upload)
        {
            IList<Gene> resultList = iSession.CreateCriteria(typeof(Gene))
                .Add(Restrictions.Eq("Upload", upload))
                .List<Gene>();

            return resultList;
        }
Пример #8
0
        public bool UpdateUpload(string landlordReference, string submittedPropertyReference, string uploadReference, Upload upload)
        {
            Check.If(landlordReference).IsNotNullOrEmpty();
            Check.If(submittedPropertyReference).IsNotNullOrEmpty();
            Check.If(uploadReference).IsNotNullOrEmpty();
            Check.If(upload).IsNotNull();

            return _uploadRepository.UpdateUpload(landlordReference, submittedPropertyReference, uploadReference, upload);
        }
Пример #9
0
        public string CreateUpload(string landlordReference, string submittedPropertyReference, Upload upload)
        {
            Check.If(landlordReference).IsNotNullOrEmpty();
            Check.If(submittedPropertyReference).IsNotNullOrEmpty();
            Check.If(upload).IsNotNull();

            var result = _uploadRepository.CreateUpload(landlordReference, submittedPropertyReference,
                upload.CreateReference(_referenceGenerator));

            return result ? upload.UploadReference : null;
        }
Пример #10
0
        public Response DispatchCommand()
        {
            var cmdName = Parameters["cmd"];

            if (string.IsNullOrEmpty(cmdName))
            {
                return new ErrorResponse("Command not set");
            }

            ICommand cmd = null;

            switch (cmdName)
            {
                case "open":
                    if (!string.IsNullOrEmpty(Parameters["init"]) && Parameters["init"] == "true")
                        cmd = new Init();
                    else
                    {
                        cmd = new Open(Parameters["target"]);
                    }
                    break;
                case "mkdir":
                    cmd = new MkDir(Parameters["current"], Parameters["name"]);
                    break;
                case "rm":
                    cmd = new Rm(Parameters["current"], Parameters["targets[]"]);
                    break;
                case "rename":
                    cmd = new Rename(Parameters["current"], Parameters["target"], Parameters["name"]);
                    break;
                case "upload":
                    cmd = new Upload(Parameters["current"], Files);
                    break;
                case "ping":
                    cmd = new Ping();
                    break;
                case "duplicate":
                    cmd = new Duplicate(Parameters["current"], Parameters["target"]);
                    break;
                case "paste":
                    cmd = new Paste(Parameters["src"], Parameters["dst"], Parameters["targets[]"], Parameters["cut"]);
                    break;
            }

            if (cmd == null)
            {
                return new ErrorResponse("Unknown command");
            }

            return cmd.Execute();

            return new ErrorResponse("Unknown error");
        }
Пример #11
0
        public object Deserialize(JObject obj, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (obj == null) return null;

            var upload = new Upload
            {
                ContentType = obj.Value<string>(RedmineKeys.CONTENT_TYPE),
                FileName = obj.Value<string>(RedmineKeys.FILENAME),
                Token = obj.Value<string>(RedmineKeys.TOKEN),
                Description = obj.Value<string>(RedmineKeys.DESCRIPTION)
            };

            return upload;
        }
Пример #12
0
        static void Main(string[] args)
        {

            using (Connection client = DFSClien.UP("SFD"))
            {
                client.write(data);
                client.Write(file);
                client.read();
                client.readto(file);
            }

            Upload up = new Upload(data);
            string file = up.exeute();
            System.Threading.Thread.Sleep(-1);
        }
Пример #13
0
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var upload = new Upload();

                upload.ContentType = dictionary.GetValue<string>("content_type");
                upload.FileName = dictionary.GetValue<string>("filename");
                upload.Token = dictionary.GetValue<string>("token");
                upload.Description = dictionary.GetValue<string>("description");
                return upload;
            }

            return null;
        }
Пример #14
0
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var upload = new Upload();

                upload.ContentType = dictionary.GetValue<string>(RedmineKeys.CONTENT_TYPE);
                upload.FileName = dictionary.GetValue<string>(RedmineKeys.FILENAME);
                upload.Token = dictionary.GetValue<string>(RedmineKeys.TOKEN);
                upload.Description = dictionary.GetValue<string>(RedmineKeys.DESCRIPTION);
                return upload;
            }

            return null;
        }
Пример #15
0
        void UploadButtonClick(object sender, EventArgs e)
        {
            ConsoleTextBox.Text = "";

            //crop the image
            Bitmap target = CropImage();

            MemoryStream fileData = new MemoryStream();

            target.Save(fileData, System.Drawing.Imaging.ImageFormat.Png);
            fileData.Seek(0, SeekOrigin.Begin);

            //add post-header
            NameValueCollection nvc = new NameValueCollection();

            nvc.Add("name", UsernameTextBox.Text);
            nvc.Add("pass", FStringHasher.ToMD5(PasswordTextBox.Text));
            nvc.Add("header", (UseAsHeaderCheckBox.Enabled && UseAsHeaderCheckBox.Checked).ToString().ToLower());
            nvc.Add("title", ScreenshotTitleTextBox.Text);
            nvc.Add("description", ScreenshotDescriptionTextBox.Text);

            using (WebResponse response = Upload.PostFile(CPictureUploadUri, nvc, fileData, ScreenshotTitleTextBox.Text + ".png", null, null, null, null))
            {
                // the stream returned by WebResponse.GetResponseStream
                // will contain any content returned by the server after upload

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string result = reader.ReadToEnd();
                    if (result.Contains("OK"))
                    {
                        ConsoleTextBox.Text = "Upload Successful.";
                    }
                    else if (result.Contains("LOGIN FAILED"))
                    {
                        ConsoleTextBox.Text = "Login failed!";
                    }
                    else if (result.Contains("SERVER BUSY"))
                    {
                        ConsoleTextBox.Text = "Server is busy, please try again later.";
                    }
                    else
                    {
                        ConsoleTextBox.Text = "ERROR: " + result;
                    }
                }
            }
        }
Пример #16
0
        public async Task <bool> PostUploadsAsync(IFormFile content, string filePath)
        {
            bool IsSuccess = false;

            try
            {
                string fileuploadPath = Path.Combine(Directory.GetCurrentDirectory(), filePath);

                if (!Directory.Exists(fileuploadPath))
                {
                    Directory.CreateDirectory(filePath);
                }

                Upload upload = new Upload();
                upload.Guid = Guid.NewGuid().ToString();

                var fileName = content.FileName;
                upload.LocalFileName = GetFileName(fileName) + "_" + upload.Guid + "." + GetFileExtension(fileName);

                upload.FileName = fileName;

                var fullPath = Path.Combine(fileuploadPath, upload.LocalFileName);
                upload.FilePath = Path.Combine(filePath, upload.LocalFileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    content.CopyTo(stream);
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        upload.FileBinary = br.ReadBytes((Int32)stream.Length);
                    }
                }

                upload.FileSize = content.Length;

                upload.UploadDate = DateTime.Now;

                _context.Uploads.Add(upload);
                await _context.SaveChangesAsync();

                IsSuccess = true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
            }

            return(IsSuccess);
        }
        public ICommandResult Handle(UploadFileCommand command)
        {
            try {
                var upload = new Upload(command.FileData.FileName, command.GroupId, command.Username);
                upload.UploadedPath = _fileStore.SaveUploadedFile(upload.UploadedFilename, command.FileData);
                _uploadRepository.SaveOrUpdate(upload);

                return(new UploadFileCommandResult(true));
            }
            catch (Exception ex) {
                return(new UploadFileCommandResult(false)
                {
                    Message = "A problem was encountered uploading the file: " + ex.Message
                });
            }
        }
Пример #18
0
        static Upload <Candlestick> GenerateCandlestickData(IEnumerable <TransactionLog> logs)
        {
            var ret = new Upload <Candlestick>();

            ret.values = new List <Candlestick>();
            foreach (var x in logs)
            {
                (ret.values as List <Candlestick>).Add(new Candlestick
                {
                    catalog = config.Log.CatalogPrefix + x.Bid.Quantity.Split(' ')[1],
                    price   = Convert.ToDouble(x.Bid.Quantity.Split(' ')[0]) / Convert.ToDouble(x.Ask.Quantity.Split(' ')[0]),
                    utcTime = DateTime.FromFileTimeUtc(x.Timestamp * 1000)
                });
            }
            return(ret);
        }
Пример #19
0
        static Task <Upload> CreateUpload(this IFormFile file, string path, string url) => Task.Run(() =>
        {
            var f = file.CreateSafeName(path);

            var upload = new Upload
            {
                File     = f,
                Name     = file.Name,
                Path     = $"{path}{f}",
                Url      = $"{url}{f}",
                FileType = file.ContentType,
                Size     = file.Length
            };

            return(upload);
        });
Пример #20
0
        public void Test5()
        {
            ArrayList           events         = new ArrayList();
            DummyConnection     connection     = new DummyConnection(events);
            DummyChoker         choker         = new DummyChoker(events);
            DummyStorageWrapper storageWrapper = new DummyStorageWrapper(events);
            Upload upload = new Upload(connection, choker, storageWrapper, 100, 20, 5);

            upload.Unchoke();
            upload.GetInterested();
            upload.GetRequest(0, 1, 3);
            upload.GetCancel(0, 1, 3);
            upload.GetCancel(0, 1, 2);
            upload.Flush();
            connection.Flushed = true;
        }
Пример #21
0
        // GET: Uploads/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Upload upload = db.Uploads.Find(id);

            if (upload == null)
            {
                return(HttpNotFound());
            }
            ViewBag.CategoryId    = new SelectList(db.Categories, "CategoryId", "CategoryName", upload.CategoryId);
            ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", upload.SubCategoryId);
            return(View(upload));
        }
        public ActionResult Index(Upload upload)
        {
            string nomeArquivo = @"e:\home\agilus\Temp\" + Path.GetRandomFileName().Replace(".", "");

            upload.arquivo.SaveAs(nomeArquivo);
            XlsFile excel    = new XlsFile(nomeArquivo);
            string  resposta = "";

            if (Utils.TextoCelula(excel, "B2").Equals("Relatório Produção Diária"))
            {
                resposta = SerializaProposta(excel);
            }

            System.IO.File.Delete(nomeArquivo);
            return(this.Content(resposta, "text/xml"));
        }
Пример #23
0
        public void ReAddT1AndU1()
        {
            ThumbnailFileHandlingTests.t1 = new Template("T1", null, TemplateMode.FolderBased, ThumbnailFileHandlingTests.t1RootFolder, null, templateList);
            ThumbnailFileHandlingTests.templateViewModel.AddTemplate(t1);

            ThumbnailFileHandlingTests.t1.ThumbnailFallbackFilePath = ThumbnailFileHandlingTests.thumbNailFallbackImage1SourceFilePath;
            Assert.IsTrue(File.Exists(ThumbnailFileHandlingTests.thumbNailFallbackImage1TargetFilePath));

            List <Upload> uploads = new List <Upload>();

            ThumbnailFileHandlingTests.u1 = new Upload(ThumbnailFileHandlingTests.t1RootVideo1FilePath);
            uploads.Add(ThumbnailFileHandlingTests.u1);

            ThumbnailFileHandlingTests.uploadListViewModel.AddUploads(uploads);
            Assert.IsTrue(ThumbnailFileHandlingTests.u1.ThumbnailFilePath == ThumbnailFileHandlingTests.thumbNailFallbackImage1TargetFilePath);
        }
Пример #24
0
        public async Task <Upload?> UpdateUpload(Upload upload)
        {
            var result = await _appDbContext.Uploads.FirstOrDefaultAsync(u => u.Id == upload.Id);

            if (result != null)
            {
                // Update existing upload
                _appDbContext.Entry(result).CurrentValues.SetValues(upload);
                await _appDbContext.SaveChangesAsync();
            }
            else
            {
                throw new KeyNotFoundException("Upload not found");
            }
            return(result);
        }
Пример #25
0
        public void Update(Upload model)
        {
            var std = GetById(model.Id);

            //std.StudentName = model.StudentName;
            //std.Surname = model.Surname;
            //std.Initials = model.Initials;
            //std.StudentNumber = model.StudentNumber;
            //std.Surname = model.Surname;
            //std.email = model.email;
            //std.Contact = model.Contact;
            //std.GroupId = model.GroupId;
            //std.Address = model.Address;
            //_dbContext.Entry(std).State = System.Data.Entity.EntityState.Modified;
            _repository.Update(std);
        }
Пример #26
0
        public void CreateUpload()
        {
            if (!Settings.ModifyTests)
            {
                return;
            }
            Vault  v           = Vault.GetVault(Api, Settings.TestProject, Settings.TestVault).Result;
            string file        = GetFile();
            string description = "Test upload " + (v.uploads_count + 1);
            Upload u           = RunTest(v.CreateUpload(Api, file, description));

            Assert.AreEqual(file, u.filename);
            Assert.AreEqual(description, u.description);
            Assert.AreEqual(v.id, u.parent.id);
            u.SetStatus(Api, Status.trashed).Wait();
        }
Пример #27
0
        /// <summary>
        ///     When overridden in a derived class, converts the provided dictionary into an object of the specified type.
        /// </summary>
        /// <param name="dictionary">
        ///     An <see cref="T:System.Collections.Generic.IDictionary`2" /> instance of property data stored
        ///     as name/value pairs.
        /// </param>
        /// <param name="type">The type of the resulting object.</param>
        /// <param name="serializer">The <see cref="T:System.Web.Script.Serialization.JavaScriptSerializer" /> instance.</param>
        /// <returns>
        ///     The deserialized object.
        /// </returns>
        public override object Deserialize(IDictionary <string, object> dictionary, Type type,
                                           JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var upload = new Upload();

                upload.ContentType = dictionary.GetValue <string>(RedmineKeys.CONTENT_TYPE);
                upload.FileName    = dictionary.GetValue <string>(RedmineKeys.FILENAME);
                upload.Token       = dictionary.GetValue <string>(RedmineKeys.TOKEN);
                upload.Description = dictionary.GetValue <string>(RedmineKeys.DESCRIPTION);
                return(upload);
            }

            return(null);
        }
Пример #28
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (Upload == null)
            {
                return(NotFound());
            }

            var file = Path.Combine(_env.ContentRootPath, _configuration["CalculatorSettings:ExcelFilePath"], Upload.FileName);

            using (var fileStream = new FileStream(file, FileMode.Create))
            {
                await Upload.CopyToAsync(fileStream);
            }

            return(RedirectToPage("./Index"));
        }
        public void UploadMultipleFilesToRemoteServer_Upload_SuccesfulResult()
        {
            //Arrange
            var mainRequest = new FtpHandler
            {
                url       = "ftp://13.59.40.218/",
                userName  = "******",
                securePwd = new NetworkCredential("", "Kamono123").SecurePassword
            };
            var upload = new Upload();
            //Act
            var response = upload.UploadMultipleToRemote(mainRequest, "SavedConnections.txt;410AgileCsharp.runtimeconfig.json");

            //Assert
            Assert.IsTrue(response);
        }
Пример #30
0
        protected async void DownloadBy(Upload model)
        {
            if (!string.IsNullOrEmpty(model.FileName))
            {
                byte[] fileBytes = await FileStorageManager.DownloadAsync(model.FileName, "");

                if (fileBytes != null)
                {
                    // DownCount
                    model.DownCount = model.DownCount + 1;
                    await UploadRepositoryAsyncReference.EditAsync(model);

                    await FileUtil.SaveAs(JSRuntime, model.FileName, fileBytes);
                }
            }
        }
Пример #31
0
        public void PostTweet(string status, List <string> imageUrls)
        {
            var webClient = new WebClient();

            var credentials = new TwitterCredentials(KEY, SECRET, TOKEN, TOKENSECRET);

            var tweet = Auth.ExecuteOperationWithCredentials(credentials, () =>
            {
                var images = imageUrls.Select(u => Upload.UploadImage(webClient.DownloadData(u))).ToList();

                return(Tweetinvi.Tweet.PublishTweet(status, new PublishTweetOptionalParameters
                {
                    Medias = images
                }));
            });
        }
Пример #32
0
        public ICommandResult Imagem([FromForm] IFormFile arquivo)
        {
            if (arquivo == null)
            {
                return(new GenericCommandResult(false, "Envie um arquivo!", null));
            }

            if (!arquivo.ContentType.Contains("image"))
            {
                return(new GenericCommandResult(false, "É necessário que o arquivo enviado seja uma imagem!", null));
            }

            var urlImagem = Upload.Imagem(arquivo);

            return(new GenericCommandResult(true, "Upload concluído com sucesso!", urlImagem));
        }
Пример #33
0
        public InlineImageViewModel(string contentType, Upload upload, IMessageBus bus, Func <string, IImageView> imageViewCreator) : base(upload)
        {
            _imageViewCreator        = imageViewCreator;
            ShowFullSizeImageCommand = new ReactiveCommand(
                this.ObservableForProperty(vm => vm.File).Select(c => c.Value != null));
            ShowFullSizeImageCommand.Subscribe(ViewImage);
            bus.Listen <FileDownloadedMessage>().Where(msg => msg.Url == Upload.FullUrl)
            .SubscribeUI(msg =>
            {
                File           = msg.File;
                ShowAnimated   = contentType.Equals("image/gif", StringComparison.OrdinalIgnoreCase);
                ShowUnanimated = !ShowAnimated;
            });

            bus.SendMessage(new RequestDownloadFileMessage(Upload.FullUrl));
        }
Пример #34
0
        public void DeviceFarmCreateUpload()
        {
            #region createupload-example-1470864711775

            var client   = new AmazonDeviceFarmClient();
            var response = client.CreateUpload(new CreateUploadRequest
            {
                Name       = "MyAppiumPythonUpload",
                Type       = "APPIUM_PYTHON_TEST_PACKAGE",
                ProjectArn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-projects CLI command.
            });

            Upload upload = response.Upload;

            #endregion
        }
Пример #35
0
        public ActionResult Index(Upload upload)
        {
            string nomeArquivo = @"e:\home\agilus\Temp\" + Path.GetRandomFileName().Replace(".", "");

            upload.arquivo.SaveAs(nomeArquivo);
            XlsFile excel    = new XlsFile(nomeArquivo);
            string  resposta = "";

            if (Utils.TextoCelula(excel, "C6") == "RELATÓRIO DE PROPOSTAS CADASTRADAS")
            {
                resposta = SerializaProposta(excel);
            }

            System.IO.File.Delete(nomeArquivo);
            return(this.Content(resposta, "text/xml"));
        }
Пример #36
0
        public UploadResponse GetUploadRequestResult()
        {
            if (_uploadedPictures.Count == 0)
            {
                throw new Exception("0 files have been uploaded.");
            }

            var aggregate = Upload.Create(_uploadedPictures.First().FolderName);

            foreach (var uploadedPicture in _uploadedPictures)
            {
                aggregate.AddUploadedFile(uploadedPicture.Name, uploadedPicture.OriginalPath, uploadedPicture.Size);
            }

            return(_mapper.Map <UploadResponse>(aggregate));
        }
Пример #37
0
        //Pre: File name
        //Post: Bool for whether file exists returned
        //Description: This method checks whether the specified file exists on the storage.
        public static bool CheckFileExists(string fileName)
        {
            bool exists = true;

            //The library throws an exception if the file does not exist, so I try to get the file and if an exception is thrown it doesn't exist
            try
            {
                Upload fileList = uploadService.GetFileByName(fileName);
            }
            catch (App42NotFoundException exp)
            {
                exists = false;
                Console.WriteLine(exp.Message);
            }
            return(exists);
        }
Пример #38
0
        public async Task SaveUploads(List <IFormFile> uploads, int productId)
        {
            try
            {
                var filePath = Path.Combine(_env.WebRootPath, "uploads", "products", productId.ToString());

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                foreach (var file in uploads)
                {
                    if (file.Length > 0)
                    {
                        var    name      = Path.GetFileNameWithoutExtension(file.FileName);
                        var    extension = Path.GetExtension(file.FileName);
                        string time      = Convert.ToInt32(DateTime.Now.TimeOfDay.TotalMilliseconds).ToString();

                        var fileName = name + "_" + time + extension;

                        using (var stream = new FileStream(Path.Combine(filePath, fileName), FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }


                        var upload = new Upload()
                        {
                            Path            = "~/uploads/products/" + productId + "/" + fileName,
                            FileName        = fileName,
                            ProductId       = productId,
                            CreatedOnDate   = DateTime.Now,
                            CreatedByUserId = _userManager.GetUserId(User),
                            IsCarousel      = false,
                            IsThumbnail     = false,
                            IsDeleted       = false
                        };
                        _uploadRepository.AddUpload(upload);
                    }
                }
                _uploadRepository.SaveChanges();
            }
            catch (Exception)
            {
            }
        }
Пример #39
0
        static void Main(string[] args)
        {
            var defparams =
                (Dictionary <string, DefConfigurationSectionRequest>)ConfigurationManager.GetSection("RunningParam");
            //RunCLS.RunAbutment(defparams);

            DownloadInterface downloadInterface = new DownloadInterface();

            Download download = new Download(downloadInterface, defparams,
                                             DateTime.Now.ToString("yyyyMMddHHmmss") + "Test");

            LogHelper.WriteLog(typeof(string), "--开始下载接口对接--", LogHelper.LogLevel.INFO);
            downloadInterface.StartDownload();
            LogHelper.WriteLog(typeof(string), "--结束下载接口对接--", LogHelper.LogLevel.INFO);


            DownloadInterface uploadInterface = new DownloadInterface();


            //ASNAccessor aSN = new ASNAccessor();
            //aSN.GetInbound_ASNHD();
            Upload upload = new Upload(uploadInterface, defparams,
                                       DateTime.Now.ToString("yyyyMMddHHmmss") + "Test");

            LogHelper.WriteLog(typeof(string), "--开始上传接口对接--", LogHelper.LogLevel.INFO);
            uploadInterface.StartDownload();
            LogHelper.WriteLog(typeof(string), "--结束上传接口对接--", LogHelper.LogLevel.INFO);

            //ASNAccessor aSN = new ASNAccessor();
            //aSN.GetInbound_ASNHD();

            //string msg = "";
            //string txtaddress = aSN.Create_RECHD_TXT1(null, null, out msg);
            //string txtaddress = aSN.Create_SHPTXT(null, null, out msg);

            //aSN.wms_receipt();
            //aSN.Create_SHPPK();
            //aSN.WMSAdjustment();
            //aSN.WMSInventory();

            //aSN.ExternTable("3400344248");

            //string txtaddress = aSN.GetInbound_ASNHD(null, out msg);


            //aSN.CreatIQC("210104002");
        }
Пример #40
0
        public override async Task <DownloadResult> DownloadAsync(Upload upload, RangeHeaderValue range, CancellationToken cancellationToken)
        {
            var blob = _blobContainerClient.GetBlobClient(upload.Id + upload.Extension);

            if (range == null)
            {
                return(new DownloadResult
                {
                    Stream = (await blob.DownloadAsync(cancellationToken)).Value.Content
                });
            }
            else
            {
                var offset = range.Ranges.FirstOrDefault()?.From.GetValueOrDefault() ?? 0;

                // Bound the to range to the maximum allowed download range so if the client requests an unbounded range (0-)
                // then we don't grab the potentially giant file from the backing store which then has to be relayed to the client.
                long?length = range.Ranges.FirstOrDefault()?.To;

                if (_maximumAllowedDownloadRangeFromBlobStoreInBytes > 0)
                {
                    if (length.HasValue)
                    {
                        length = Math.Min(
                            length.GetValueOrDefault() - offset,
                            Math.Min(
                                _maximumAllowedDownloadRangeFromBlobStoreInBytes,
                                upload.Length - offset));
                    }
                    else
                    {
                        // Grab the minimum out of the client requested to val
                        length = Math.Min(
                            _maximumAllowedDownloadRangeFromBlobStoreInBytes,
                            upload.Length - offset);
                    }
                }

                var response = await blob.DownloadAsync(new HttpRange(offset, length), cancellationToken : cancellationToken);

                return(new DownloadResult
                {
                    Stream = response.Value.Content,
                    ContentRange = response.GetRawResponse().Headers.FirstOrDefault(x => x.Name == "Content-Range").Value
                });
            }
        }
Пример #41
0
        public IActionResult Add(Employee item, List <IFormFile> Files)
        {
            if (ModelState.IsValid)
            {
                bool imgResult;

                string imgPath = Upload.ImageUpload(Files, _hostingEnvironment, out imgResult);



                if (imgResult)
                {
                    item.imageUrl       = imgPath;
                    TempData["Message"] = "Image Added";
                    _logger.LogInformation("Image added!!");
                }
                else
                {
                    item.imageUrl = "NULL";
                    _logger.LogWarning("Image cannot added!!");
                }



                bool result = _repository.Add(item);


                if (result == true)
                {
                    _repository.Save();
                    _logger.LogInformation("Employee Added " + item.ID + " " + DateTime.Now.ToString());
                    return(RedirectToAction("List", "Employee"));
                }
                else
                {
                    TempData["Message"] = $"Employee Add Operation Failed";
                    _logger.LogError("Employee Add Operation " + DateTime.Now.ToString());
                    return(View(item));
                }
            }
            else
            {
                TempData["Message"] = $"Employee Add Operation Failed";
                _logger.LogCritical("Employee Add Operation Failed " + DateTime.Now.ToString());
                return(View(item));
            }
        }
Пример #42
0
        protected void ButtonUpload_Click(object sender, EventArgs e)
        {
            var id = Convert.ToInt64(Session["ID"]);

            if (FileUpload1.HasFile && FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
            {
                HttpPostedFile file        = FileUpload1.PostedFile;//retrieve the HttpPostedFile object
                var            buffer      = new byte[file.ContentLength];
                int            bytesReaded = file.InputStream.Read(buffer, 0, FileUpload1.PostedFile.ContentLength);
                //the HttpPostedFile has InputStream porperty (using System.IO;)
                //which can read the stream to the buffer object,
                //the first parameter is the array of bytes to store in,
                //the second parameter is the zero index (of specific byte) where to start storing in the buffer,
                //the third parameter is the number of bytes you want to read (do u care about this?)
                if (bytesReaded > 0)
                {
                    try
                    {
                        var upload = new Upload()
                        {
                            name          = FileUpload1.FileName,
                            content_type  = FileUpload1.PostedFile.ContentType,
                            created_at    = DateTime.Now,
                            data          = buffer,
                            modified_at   = DateTime.Now,
                            user_id       = (int)id,
                            file_location = file.ContentLength.ToString()
                        };

                        _insendluEntities.Uploads.Add(upload);

                        var i = _insendluEntities.SaveChanges();

                        var filename = Page.Server.MapPath("~/Uploads/Tutorials/" + Path.GetFileName(file.FileName));
                        file.SaveAs(filename);
                    }
                    catch (Exception ex)
                    {
                        //Label1.Text = ex.Message;
                    }
                }
            }
            else
            {
                //Label1.Text = "Choose a valid video file";
            }
        }
Пример #43
0
        public async Task <IActionResult> OnPostAsync(long?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Upload = await _context.Uploads.FindAsync(id);

            if (Upload != null)
            {
                _context.Uploads.Remove(Upload);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Пример #44
0
        public UploadModel SalvarArquivo(Upload upload)
        {
            var contexto = InjectorManager.GetInstance <Contexto>();

            contexto.Uploads.Add(upload);

            contexto.SaveChanges();

            return(new UploadModel
            {
                ArquivoId = upload.Id,
                Nome = upload.NomeArquivo,
                MediaType = upload.MediaType,
                Width = upload.Width.Value,
                Height = upload.Height.Value
            });
        }
Пример #45
0
        public void SaveUpload(int id, UploadDTO file)
        {
            var currentProject = _projectRepo.Get(id).FirstOrDefault();

            // check if current project is null first
            if (currentProject != null) {
                var newUpload = new Upload() {
                    Name = file.Name,
                    Url = file.Url,
                    Project = currentProject,
                    Type = (Upload.Classification)Enum.Parse(typeof(Upload.Classification), file.Type)
                };

                _uploadRepo.Add(newUpload);
                _uploadRepo.SaveChanges();
            }
        }
Пример #46
0
        void Button1_Click(object sender, EventArgs e)
        {
            Upload up = new Upload();

            up.header = new Helper.Web.UploadSoapHeader();
            up.header.AppID = "1";
            up.header.Algorithm = "md5";
            up.header.Signature = up.CreateSignature(up.header.AppID + up.header.Algorithm + "key1", "md5", "key1");

            Helper.Web.UploadResult rs = up.Upload(new Helper.Web.UploadRequest()
            {
                SaveVirtualPath = "Styles",
                FileBytes = FileUpload1.FileBytes,
                FileName = FileUpload1.FileName

            });

            Response.Write(rs.Code + "," + rs.Msg + "," + rs.ReturnFilePath);
        }
Пример #47
0
        public bool CreateUpload(string landlordReference, string submittedPropertyReference, Upload upload)
        {
            var landlord = _propertiesContext.Landlords.Active()
                 .Include(l => l.SubmittedProperties)
                 .Include(l => l.SubmittedProperties.Select(s => s.Uploads))
                 .FirstOrDefault(l => l.LandlordReference == landlordReference);

            var property =
                landlord?.SubmittedProperties.Active()
                    .FirstOrDefault(s => s.SubmittedPropertyReference == submittedPropertyReference);

            if (property.IsNull())
                return false;

            property.Uploads.Add(upload);

            if (property.SubmissionStatus != SubmissionStatus.Pending)
            {
                property.MarkRevised();
            }

            return _propertiesContext.SaveChanges() > 0;
        }
    private string UploadFile(Upload upload, string filterXml)
    {
        // Process throws an exception if there is an error.
        upload.Process(XElement.Parse(filterXml));

        // Success!
        return string.Empty;
    }
Пример #49
0
 static string GradientName(Upload upload, Download download)
 {
     return "disconnected-" + upload + "-" + download;
 }
Пример #50
0
        static MvcHtmlString GradientDef(Upload upload, Download download)
        {
            return MvcHtmlString.Create(@"
<linearGradient id=""" + GradientName(upload, download) + @""" x1=""0%"" y1=""0%"" x2=""0%"" y2=""100%"">
    <stop offset=""0%"" style=""stop-color:"  + UploadColor(upload)  +  @""" />
    <stop offset=""100%"" style=""stop-color:" + DownloadColor(download) + @""" />
</linearGradient>");
        }
Пример #51
0
 public UploadLock(Upload upload)
 {
     this.upload = upload;
 }
 public UploadHtmlBuilderTests()
 {
     upload = UploadTestHelper.CreateUpload();
     builder = new UploadHtmlBuilder(upload);
 }
Пример #53
0
		/// <summary>
		/// Default constructor. Creates a new model.
		/// </summary>
		public EditModel() {
			Upload = new Upload();
		}
Пример #54
0
        /// <summary>
        /// Initializes a new instance of class.
        /// </summary>
        /// <param name="plugin">Plugin.</param>
        public UploadWindow(Upload plugin)
            : base(WindowType.Toplevel)
        {
            this.Build();
            this.plugin = plugin;

            try
            {
                this.Icon = IconTheme.Default.LoadIcon("glippy", 128, IconLookupFlags.GenericFallback);
            }
            catch (Exception ex)
            {
                Core.Tools.PrintInfo(ex, this.GetType());
            }

            if (!string.IsNullOrWhiteSpace(Core.Settings.Instance[SettingsKeys.PastebinUserKey].AsString()))
                this.useAccount.Sensitive = this.useAccount.Active = true;

            this.Destroyed += (s, e) => this.Purge();

            Core.Item item = Core.Clipboard.Instance.Items.FirstOrDefault();

            if (item == null)
            {
                radiobuttonImage.Sensitive = false;
            }
            else if (item.IsImage)
            {
                int width, height;

                if (item.Image.Width < item.Image.Height)
                {
                    if (item.Image.Height > MaxImageSize)
                    {
                        height = MaxImageSize;
                        width = MaxImageSize * item.Image.Width / item.Image.Height;
                    }
                    else
                    {
                        height = item.Image.Height;
                        width = item.Image.Width;
                    }
                }
                else
                {
                    if (item.Image.Width > MaxImageSize)
                    {
                        width = MaxImageSize;
                        height = MaxImageSize * item.Image.Height / item.Image.Width;
                    }
                    else
                    {
                        width = item.Image.Width;
                        height = item.Image.Height;
                    }
                }

                this.imageClip.Pixbuf = item.Image.ScaleSimple(width, height, Gdk.InterpType.Bilinear);
                this.image = new Gdk.Pixbuf(item.Image, 0, 0, item.Image.Width, item.Image.Height);

                this.radiobuttonImage.Active = true;
                this.SetItemsSensitivity(false);
                this.clipType.Page = 1;
            }
            else
            {
                TextBuffer buffer = new TextBuffer(null);

                if (item.IsData)
                    buffer.Text = item.Target == Core.Targets.Html ? Encoding.UTF8.GetString(item.Data) : Encoding.UTF8.GetString(item.DataText);
                else
                    buffer.Text = item.Text;

                this.textClip.Buffer = buffer;
                this.radiobuttonImage.Sensitive = false;
            }
        }
        /// <summary>
        /// Adds client templates for the specified Upload control.
        /// </summary>
        private static void AddUploadClientTemplates(Upload upload)
        {
            #region File input client template

            // Add client template for the file input section (includes input tag and browse and upload buttons).
            ClientTemplate uploadFileInputClientTemplate = new ClientTemplate();

            uploadFileInputClientTemplate.ID = "FileInputTemplate";

            uploadFileInputClientTemplate.Text = String.Format(CultureInfo.InvariantCulture, @"
            <div class=""file"">
            <div class='## DataItem.FileName ? ""filename"" : ""filename empty""; ##'>
            <input value='## DataItem.FileName ? DataItem.FileName : ""{0}""; ##'
            onfocus=""this.blur();"" /></div>
            <a href=""javascript:void(0);"" onclick=""this.blur();return false;"" class=""browse""
            title=""{1}"">{2}#$FileInputImage</a> <input type=""button"" onclick=""init_upload(Upload1);this.blur();return false;"" value=""{3}"" title=""{4}"" class=""upload"" />
            </div>
            ",
            Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_File_Input_Text,
            Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_File_Browse_Button_Tooltip,
            Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_File_Browse_Text,
            Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_File_Button_Text,
            Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_File_Button_Tooltip
            );

            upload.ClientTemplates.Add(uploadFileInputClientTemplate);

            #endregion

            #region Upload progress client template

            // Add client template for the progress section (includes input tag and browse and upload buttons).
            ClientTemplate uploadProgressClientTemplate = new ClientTemplate();

            uploadProgressClientTemplate.ID = "ProgressTemplate";

            uploadProgressClientTemplate.Text = String.Format(CultureInfo.InvariantCulture, @"
            <!-- Dialogue contents -->
            <div class=""con"">
            <div class=""stat"">
            <p class=""gsp_h3"" rel=""total"">
            {0} <span class=""red"">## DataItem.CurrentFile; ##</span></p>
            <div class=""prog"">
            <div class=""con"">
                <div class=""bar"" style=""width: ## get_percentage(DataItem.Progress) ##%;"">
                </div>
            </div>
            </div>
            <div class=""lbl"">
            <strong>## format_file_size(DataItem.ReceivedBytes) ##</strong> (## get_percentage(DataItem.Progress)
            ##%) {1}</div>
            </div>
            </div>
            <!-- /Dialogue contents -->
            <!-- Dialogue footer -->
            <div class=""ftr"">
            <div class=""ftr-l"">
            </div>
            <div class=""ftr-m"">
            <div class=""info"" id=""info1"">
            <span>{2} <strong>## format_time(DataItem.ElapsedTime); ##</strong></span>
            <span style=""padding-left: 8px;"">{3} <strong>## format_time(DataItem.ElapsedTime
                + DataItem.RemainingTime); ##</strong></span> <span style=""padding-left: 8px;"">{4}
                    <strong>## DataItem.Speed.toFixed(2) ## {5}</strong></span>
            </div>
            <div class=""btns"">
            <a onclick=""Upload1.abort();UploadDialog.close();this.blur();return false;"" href=""javascript:void(0);""
                rel=""cancel""><span class=""l""></span><span class=""m"" id=""btn1"">{6}</span>
                <span class=""r""></span></a>
            </div>
            </div>
            <div class=""ftr-r"">
            </div>
            </div>
            <!-- /Dialogue footer -->
            ",
                    Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_Filename_Label, // 0
                    Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_Bytes_Uploaded_Suffix, // 1
                    Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_Elapsed_Time_Label, // 2
                    Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_Estimated_Time_Label, // 3
                    Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_Speed_Label, // 4
                    Resources.GalleryServerPro.Site_KiloBytes_Per_Second_Abbreviation, // 5
                    Resources.GalleryServerPro.Admin_Backup_Restore_Restore_Tab_Upload_Cancel_Upload_Text // 6
                );

            upload.ClientTemplates.Add(uploadProgressClientTemplate);

            #endregion
        }
        private void AddUploadControlForFullTrust()
        {
            const string htmlBeforeUpload = @"<div class='sel gsp_addtopmargin5'>";
            const string htmlAfterUpload = @"</div>";

            Upload upload = new Upload();

            upload.ID = "Upload1";
            upload.MaximumFileCount = 1;
            upload.AutoPostBack = true;
            upload.TempFileFolder = AppSetting.Instance.TempUploadDirectory;
            upload.MaximumUploadSize = 2097151;
            upload.FileInputClientTemplateId = "FileInputTemplate";
            upload.FileInputImageUrl = Utils.GetUrl("/images/componentart/upload/transparent.gif");
            upload.FileInputHoverImageUrl = Utils.GetUrl("/images/componentart/upload/transparent.gif");
            upload.ProgressClientTemplateId = "ProgressTemplate";
            upload.ProgressDomElementId = "upload-progress";

            upload.Uploaded += Upload1_Uploaded;

            phUpload.Controls.Add(new LiteralControl(htmlBeforeUpload));
            phUpload.Controls.Add(upload);
            phUpload.Controls.Add(new LiteralControl(htmlAfterUpload));

            AddUploadClientTemplates(upload);

            AddUploadDialogClientTemplate();
        }
Пример #57
0
 private static string UploadColor(Upload upload)
 {
     switch (upload)
     {
         case Upload.None: return "#ccc";
         case Upload.New: return "green";
         case Upload.Subset: return "gold";
         default: throw new InvalidOperationException();
     }
 }
Пример #58
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Session["user"] == null)
            {
                Response.Redirect("~/pages/login.aspx");
            }
            int UserID = ((User)Session["user"]).ID;
            var item = _CongtyRepo.GetByMasothue(txtMasothue.Text);
            if (item != null)
            {
                var upload = new Upload();
                upload.CongtyID = item.ID;
                upload.NAM = Utils.CIntDef(ddlNam.SelectedItem.Value, 0);
                upload.KY = Utils.CIntDef(ddlKy.SelectedItem.Value, 0);
                upload.NGAYTAO = DateTime.Now;
                upload.UserID = UserID;

                _UploadRepo.Create(upload);

                string pathfile = Server.MapPath("/Files/" + item.MASOTHUE);
                if (!Directory.Exists(pathfile))
                {
                    Directory.CreateDirectory(pathfile);
                }
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        string filename = System.IO.Path.GetFileName(hpf.FileName);
                        string fullpathfile = pathfile + "/" + filename;
                        var file = new File();
                        file.UploadID = upload.ID;
                        file.Filename = filename;
                        _FileRepo.Create(file);

                        hpf.SaveAs(fullpathfile);
                    }
                }
            }
            else
            {
                item = new Congty();
                item.MASOTHUE = txtMasothue.Text;
                item.TENCONGTY = txtTencongty.Value;
                item.DIACHI = txtAddress.Value;
                item.NGAYTAO = DateTime.Now;
                item.UserID = UserID;

                _CongtyRepo.Create(item);

                var upload = new Upload();
                upload.CongtyID = item.ID;
                upload.NAM = Utils.CIntDef(ddlNam.SelectedItem.Value, 0);
                upload.KY = Utils.CIntDef(ddlKy.SelectedItem.Value, 0);
                upload.NGAYTAO = DateTime.Now;
                upload.UserID = UserID;

                _UploadRepo.Create(upload);

                string pathfile = Server.MapPath("/Files/" + item.MASOTHUE);
                if (!Directory.Exists(pathfile))
                {
                    Directory.CreateDirectory(pathfile);
                }
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        string filename = System.IO.Path.GetFileName(hpf.FileName);
                        string fullpathfile = pathfile + "/" + filename;
                        var file = new File();
                        file.UploadID = upload.ID;
                        file.Filename = filename;
                        _FileRepo.Create(file);

                        hpf.SaveAs(fullpathfile);
                    }
                }
            }
            Response.Write("<script>alert('Lưu thành công!');location.href='giao_nhan.aspx'</script>");
        }
Пример #59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UploadHtmlBuilder" /> class.
 /// </summary>
 /// <param name="component">The Upload component.</param>
 public UploadHtmlBuilder(Upload component)
 {
     upload = component;
 }