Пример #1
0
        /// <summary>
        /// Gets upload details.
        /// </summary>
        /// <param name="tenantId">Identifies tenant whose upload is returned.</param>
        /// <param name="uploadId">Identifies the upload to return.</param>
        /// <param name="unitOfWork">Unit of work.</param>
        /// <returns>Upload details (or null if upload not found).</returns>
        public Upload Read(long tenantId, long uploadId, IUnitOfWork unitOfWork = null)
        {
            IDatabaseManager dbm = _databaseManagerFactory.GetDatabaseManager(unitOfWork);

            try
            {
                Upload upload = null;
                dbm.SetStoredProcedure("cms.ReadUpload");
                dbm.AddParameter("@TenantId", FieldType.BigInt, tenantId);
                dbm.AddParameter("@UploadId", FieldType.BigInt, uploadId);
                dbm.ExecuteReader();
                if (dbm.Read())
                {
                    UploadType uploadType = (UploadType)(int)dbm.DataReaderValue("UploadType");
                    switch (uploadType)
                    {
                    case UploadType.Image:
                        upload = GetImageFromDatabaseManager(dbm);
                        break;

                    case UploadType.Upload:
                        upload = GetUploadFromDatabaseManager(dbm);
                        break;
                    }
                }
                return(upload);
            }
            finally
            {
                if (unitOfWork == null)
                {
                    dbm.Dispose();
                }
            }
        }
Пример #2
0
 public async Task Remove(string fileName, UploadType type, int id = 0)
 {
     using (var client = new HttpClient())
     {
         await client.DeleteAsync($"{ConstValues.MediaBaseUrl}{ConstValues.MediaRemove}/{(int)type}/{fileName}/{id}");
     }
 }
Пример #3
0
        public DateTimeOffset GetPreviousDone(UploadType type)
        {
            DateTimeOffset dto = _repoManager.UploadEntryRepository.GetLastUploadEntry(type).Timestamp;

            Console.WriteLine($"{type}: {dto}");
            return(dto);
        }
Пример #4
0
        /// <summary>
        /// copy文件到指定目录
        /// Created:2017.4.6(xuxb)
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="type"></param>
        /// <param name="projectId"></param>
        /// <param name="nodeId"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool CopyFile(string filePath, UploadType type, string projectId, string nodeId, string fileName)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    //文件已不存在
                    MessageHelper.ShowMsg(MessageID.W000000003, MessageType.Alert);
                    return(false);
                }
                else
                {
                    string path = GetWorkdir() + GetUploadPath(type, projectId, nodeId);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    File.Copy(filePath, path + fileName, true);

                    File.Delete(filePath);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex, LogType.ProjectManagement);
                MessageHelper.ShowMsg(MessageID.E000000002, MessageType.Alert);
                return(false);
            }
        }
Пример #5
0
        public static bool IsTeamType(UploadType type)
        {
            var v = (int)type;

            // Team admin can upload for player and team
            return((v >= 100 && v <= 199) || (v >= 200 && v <= 299));
        }
        public int MoveRejectedRecordsFromTemp(int processId, UploadType uploadType, AssetGroupType assetGroupType, int createdBy)
        {
            //UploadDao uploadDao = new UploadDao();

            UploadRejectsDao uploadRejectsDao = new UploadRejectsDao();

            try
            {
                return(uploadRejectsDao.MoveRejectedRecordsFromTemp(processId, uploadType, assetGroupType, createdBy));
            }
            catch (BaseApplicationException Ex)
            {
                throw Ex;
            }
            catch (Exception Ex)
            {
                BaseApplicationException exBase       = new BaseApplicationException(Ex.Message, Ex);
                NameValueCollection      FunctionInfo = new NameValueCollection();

                FunctionInfo.Add("MoveRejectedRecordsFromTemp", "UploadRejectsBo.cs:MoveRejectedRecordsFromTemp()");

                object[] objects = new object[4];
                objects[0] = processId;
                objects[1] = uploadType;
                objects[2] = assetGroupType;
                objects[3] = createdBy;

                FunctionInfo = exBase.AddObject(FunctionInfo, objects);
                exBase.AdditionalInformation = FunctionInfo;
                ExceptionManager.Publish(exBase);
                throw exBase;
            }
        }
Пример #7
0
        public object Upload([FromForm] IFormCollection formData, [FromQuery] UploadType uploadType)
        {
            if (uploadType == UploadType.UserPicture)
            {
                if (formData.Files.Count != 1)
                {
                    return(new { });
                }
                var      file       = formData.Files[0];
                var      extName    = file.FileName.GetFileExtName();
                string   targetPath = "/uploads/" + Guid.NewGuid().ToString().Replace("-", "") + extName;
                FileInfo fileInfo   = new FileInfo(Env.WebRootPath + targetPath);
                using (FileStream fs = new FileStream(fileInfo.ToString(), FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                var entity = new SysFile()
                {
                    Name = file.FileName, CreateTime = DateTime.Now, ExtName = fileInfo.Extension, Path = targetPath, UploadType = uploadType
                };
                SysFileService.Add(entity);
                return(new { fileId = entity.Id, url = UrlPrefix + targetPath });
            }

            return(new { });
        }
        /// <summary>
        /// 添加与编辑UploadType记录
        /// </summary>
        /// <param name="page">当前页面指针</param>
        /// <param name="model">UploadType表实体</param>
        /// <param name="content">更新说明</param>
        /// <param name="isCache">是否更新缓存</param>
        /// <param name="isAddUseLog">是否添加用户操作日志</param>
        public void Save(Page page, UploadType model, string content = null, bool isCache = true, bool isAddUseLog = true)
        {
            try {
                //保存
                model.Save();

                //判断是否启用缓存
                if (CommonBll.IsUseCache() && isCache)
                {
                    SetModelForCache(model);
                }

                if (isAddUseLog)
                {
                    if (string.IsNullOrEmpty(content))
                    {
                        content = "{0}" + (model.Id == 0 ? "添加" : "编辑") + "UploadType记录成功,ID为【" + model.Id + "】";
                    }

                    //添加用户访问记录
                    UseLogBll.GetInstence().Save(page, content);
                }
            }
            catch (Exception e) {
                var result = "执行UploadTypeBll.Save()函数出错!";

                //出现异常,保存出错日志信息
                CommonBll.WriteLog(result, e);
            }
        }
        /// <summary>
        /// 获取文件路径
        /// </summary>
        /// <param name="areaId"></param>
        /// <param name="comanpyId"></param>
        /// <param name="uploadType"></param>
        /// <returns></returns>
        public static string VirtualFilePath(string areaId, string comanpyId, UploadType uploadType = UploadType.Attachment)
        {
            var index = 0;
            var path  = areaId.Aggregate(string.Empty, (areaPath, next) =>
            {
                areaPath += next;
                index++;
                if (index % 2 == 0 && index < 7)
                {
                    areaPath += "/";
                }
                return(areaPath);
            });

            if (!string.IsNullOrWhiteSpace(comanpyId))
            {
                path += string.Format("/{0}", comanpyId);
            }

            if (uploadType == UploadType.Attachment)
            {
                return("wwwroot/attachments/" + path);
            }
            else if (uploadType == UploadType.Import)
            {
                return("wwwroot/import/" + path);
            }
            else
            {
                return("wwwroot/attachments/" + path);
            }
        }
Пример #10
0
        /// <summary>
        /// Iterate through specific dates and update the snapshot table.
        /// </summary>
        public void Upload(UploadType uploadType, AssetGroupType assetGroupType)
        {
            this.uploadType     = uploadType;
            this.assetGroupType = assetGroupType;


            GetStartDateAndEndDate();

            if (startDate == DateTime.MinValue)
            {
                StatusMessage.Append("Snapshot table contains no data.Please update the snapshot table.");
                return;
            }
            else if (endDate == DateTime.MinValue)
            {
                StatusMessage.Append("Download table does not contain data.");
                return;
            }

            StatusMessage.Append("<table class='tblMaroon'rules='All' style='font-size:12px;border:solid 1px black;'  cellpadding='10'>");
            StatusMessage.Append("<thead><tr style='background-image: url(../CSS/Images/PCGGridViewHeaderGlass2.jpg);color:White;'><th>Date</th><th>Xml Created</th><th>Snapshot Updated</th><th>History Upload</th><th>Rejected Records</th></tr></thead>");
            if (endDate.CompareTo(startDate) < 0)
            {
                isLatestDataAvailable = true;
                return;
            }

            for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
            {
                errorMessage = string.Empty;
                Upload(date);
            }
            StatusMessage.Append("</table>");
        }
Пример #11
0
        public UploadQueryStringBuilder SetUploadType(UploadType uploadType)
        {
            string uploadTypeString = uploadType.GetAttribute <StringValueAttribute, UploadType>().Text;

            SetParameter("uploadType", uploadTypeString);
            return(this);
        }
Пример #12
0
        public static List <ImgSizeCfg> GetImgSizeCfgList(UploadType type)
        {
            var result  = new List <ImgSizeCfg>();
            var cmdText = @"select * from ImgSizeCfg where Type=?Type;";
            List <MySqlParameter> parameters = new List <MySqlParameter>();

            parameters.Add(new MySqlParameter("?Type", (int)type));
            try
            {
                using (var conn = Utility.ObtainConn(Utility._gameDbConn))
                {
                    MySqlDataReader reader = MySqlHelper.ExecuteReader(conn, CommandType.Text, cmdText, parameters.ToArray());
                    while (reader.Read())
                    {
                        var item = new ImgSizeCfg();
                        item.Id         = reader.GetInt32(0);
                        item.Type       = (UploadType)reader["Type"];
                        item.IsOriginal = (int)reader["IsOriginal"];
                        item.Width      = (int)reader["Width"];
                        item.Height     = (int)reader["Height"];

                        result.Add(item);
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return(result);
        }
Пример #13
0
        /// <summary>
        /// Uploads a file on the quick stereo server
        /// </summary>
        /// <param name="bytes">File bytes sent to the server</param>
        /// <param name="filename">Name of the file sent</param>
        /// <param name="mimeType">Mime type of file sent</param>
        /// <param name="uploadType">Type of file sent</param>
        /// <returns></returns>
        private IEnumerator Upload(byte[] bytes, string filename, string mimeType, UploadType uploadType)
        {
            WWWForm form = new WWWForm();

            form.AddBinaryData("file", bytes, filename, mimeType);
            _info = filename;

            Debug.Log("Upload " + filename);
            using (UnityWebRequest www = UnityWebRequest.Post(UploadUrl, form))
            {
                yield return(www.SendWebRequest());

                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.Log("Upload error");
                    Debug.Log(www.error);
                    _info = " www error";
                    ResetSuccess();
                }
                else
                {
                    Debug.Log("Successfully sent " + filename);
                    Debug.Log(www.downloadHandler.text);
                    Debug.Log(uploadType + " = " + _success[(int)uploadType]);
                    _info = " sent " + filename;
                    _success[(int)uploadType] = true;
                }
            }
        }
Пример #14
0
        // [Authorize]
        public ActionResult Index(string MediaId, UploadType type)
        {
            switch (type)
            {
            case UploadType.Media:
                ViewBag.Name = "MediaUploadForm";
                break;

            default:
                ViewBag.Name = "MediaUploadForm";
                break;
            }
            ViewBag.autoUpload = true;
            ViewBag.multiple   = false;
            ViewBag.Type       = _type;
            _type = type;

            if (HttpContext.Session != null)
            {
                _currentMedia = (string)HttpContext.Session["CurrentMedia"];
            }
            //if (HttpContext.Session != null)
            //    HttpContext.Session["CurrentMedia"] = MediaId;

            return(View());
        }
Пример #15
0
        private string Exif(string newFile, string fileName, UploadType uploadType, int announcementId = 0)
        {
            var newDest = fileName.GetDestFileName();

            newDest = FilesUtilities.GetRelativePath(newDest, uploadType, announcementId);
            var newFilePath = Path.Combine(_webRootPath, newDest);
            var exist       = File.Exists(newFile);

            if (!exist)
            {
                return(null);
            }
            using (var current = new Bitmap(newFile.SlashConverter()))
            {
                current.ExifRotate();
                using (var writeStream = new FileStream(newFilePath, FileMode.Create))
                {
                    var ext = Path.GetExtension(newFilePath);
                    if (string.IsNullOrEmpty(ext) || !ext.ToLower().Contains("png"))
                    {
                        current.Save(writeStream, ImageFormat.Jpeg);
                    }
                    else
                    {
                        current.Save(writeStream, ImageFormat.Png);
                    }
                }
            }
            return(newFilePath);
        }
        /// <summary>
        /// 从IIS缓存中获取指定Id记录
        /// </summary>
        /// <param name="id">主键Id</param>
        /// <returns>DataAccess.Model.UploadType</returns>
        public DataAccess.Model.UploadType GetModelForCache(long id)
        {
            try
            {
                //从缓存中读取指定Id记录
                var model = GetModelForCache(x => x.Id == id);

                if (model == null)
                {
                    //从数据库中读取
                    var tem = UploadType.SingleOrDefault(x => x.Id == id);
                    if (tem == null)
                    {
                        return(null);
                    }
                    else
                    {
                        //对查询出来的实体进行转换
                        model = Transform(tem);
                        return(model);
                    }
                }
                else
                {
                    return(model);
                }
            }
            catch (Exception e)
            {
                //记录日志
                CommonBll.WriteLog("从IIS缓存中获取UploadType表记录时出现异常", e);

                return(null);
            }
        }
Пример #17
0
        public static string GetMaterialVirtualDirectoryPath(UploadType uploadType)
        {
            var uploadDirectoryName = string.Empty;

            if (uploadType == UploadType.Image)
            {
                uploadDirectoryName = "images";
            }
            else if (uploadType == UploadType.Audio)
            {
                uploadDirectoryName = "audio";
            }
            else if (uploadType == UploadType.Video)
            {
                uploadDirectoryName = "videos";
            }
            else if (uploadType == UploadType.File)
            {
                uploadDirectoryName = "files";
            }
            else if (uploadType == UploadType.Special)
            {
                uploadDirectoryName = "specials";
            }

            return($"/{DirectoryUtils.SiteFiles.DirectoryName}/{DirectoryUtils.SiteFiles.Library}/{uploadDirectoryName}/{DateTime.Now.Year}/{DateTime.Now.Month}");
        }
 /// <summary>
 /// 获取指定Id记录
 /// </summary>
 /// <param name="id">主键Id</param>
 /// <param name="isCache">是否从缓存中读取</param>
 /// <returns>DataAccess.Model.UploadType</returns>
 public DataAccess.Model.UploadType GetModel(long id, bool isCache = true)
 {
     //判断是否使用缓存
     if (CommonBll.IsUseCache() && isCache)
     {
         //从缓存中获取List
         var list = GetList();
         if (list == null)
         {
             return(null);
         }
         else
         {
             //在List查询指定主键Id的记录
             return(list.SingleOrDefault(x => x.Id == id));
         }
     }
     else
     {
         //从数据库中直接读取
         var model = UploadType.SingleOrDefault(x => x.Id == id);
         if (model == null)
         {
             return(null);
         }
         else
         {
             //对查询出来的实体进行转换
             return(Transform(model));
         }
     }
 }
        public bool Reprocess(int processId, UploadType uploadType, AssetGroupType assetGroupType, int currentUser, out int updatedSnapshots, out int updatedHistory)
        {
            try
            {
                UploadRejectsDao rejectsDao = new UploadRejectsDao();
                return(rejectsDao.Reprocess(processId, uploadType, assetGroupType, currentUser, out updatedSnapshots, out updatedHistory));
            }
            catch (BaseApplicationException Ex)
            {
                throw Ex;
            }
            catch (Exception Ex)
            {
                BaseApplicationException exBase       = new BaseApplicationException(Ex.Message, Ex);
                NameValueCollection      FunctionInfo = new NameValueCollection();

                FunctionInfo.Add("Reprocess()", "UploadRejectsDao.cs:Reprocess()");

                object[] objects = new object[1];
                objects[0] = processId;
                objects[1] = uploadType;
                objects[2] = assetGroupType;
                objects[3] = currentUser;

                FunctionInfo = exBase.AddObject(FunctionInfo, objects);
                exBase.AdditionalInformation = FunctionInfo;
                ExceptionManager.Publish(exBase);
                throw exBase;
            }
        }
Пример #20
0
        public async Task <bool> MultipleUpload(List <IFormFile> files, UploadType uploadType,
                                                AttachmentType announcementPhotoType, int announcementId = 0, bool isRelativeRequested = false)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ConstValues.MediaBaseUrl);
                client.DefaultRequestHeaders.TryAddWithoutValidation("announcementId", announcementId.ToString());
                client.DefaultRequestHeaders.TryAddWithoutValidation("announcementPhotoType", announcementPhotoType.ToString());
                var content = new MultipartFormDataContent();
                foreach (var file in files)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    using (var stream = file.OpenReadStream())
                    {
                        using (var br = new BinaryReader(stream))
                        {
                            var data  = br.ReadBytes((int)stream.Length);
                            var bytes = new ByteArrayContent(data);
                            content.Add(bytes, "files", fileName);
                        }
                    }
                }
                await client.PostAsync($"{ConstValues.MediaMultipleUpload}{(int)uploadType}/{isRelativeRequested}", content);

                return(true);
            }
        }
Пример #21
0
        public PolicyRecord GetLastUploadRecored(PurchaserType purchaser, UploadType uType)
        {
            PolicyRecord rec = new PolicyRecord();

            try
            {
                string        strSql = "select top 1 LastUpdateTime,LastPolicyId from UpLoadRecord where IsEnabled=1 and NotifyResult=1 and UploadType='" + uType.ToString() + "' and PurchaserType='" + purchaser.ToString() + "' and IsEnabled =1  ORDER BY CreateTime DESC";
                SqlDataReader reader = DbHelperSQL.ExecuteReader(strSql);
                bool          flag   = false;
                while (reader.Read())
                {
                    flag               = true;
                    rec.LastPolicyId   = long.Parse(reader["LastPolicyId"].ToString());
                    rec.LastUpdateTime = Convert.ToDateTime(reader["LastUpdateTime"]);
                }
                if (!flag)
                {
                    rec = new PolicyRecord()
                    {
                        LastUpdateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 0:00:00"), LastPolicyId = 0
                    };
                }
                reader.Close();
                reader = null;
            }
            catch (Exception ex)
            {
                rec = new PolicyRecord()
                {
                    LastUpdateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 0:00:00"), LastPolicyId = 0
                };
            }
            return(rec);
        }
Пример #22
0
        public async Task <string> Upload(IFormFile file, UploadType uploadType, int id = 0, bool isRelativeRequested = false)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ConstValues.MediaBaseUrl);
                var content = new MultipartFormDataContent();
                if (file.Length <= 0)
                {
                    return(null);
                }
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                content.Add(new StreamContent(file.OpenReadStream())
                {
                    Headers =
                    {
                        ContentLength = file.Length,
                        ContentType   = new MediaTypeHeaderValue(file.ContentType)
                    }
                }, "file", fileName);
                var response = await client.PostAsync($"{ConstValues.MediaUpload}{(int)uploadType}/{isRelativeRequested}/{id}", content);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(null);
                }
                var serialized = await response.Content.ReadAsStringAsync();

                var deserialized = JsonConvert.DeserializeObject <ServiceResult>(serialized);
                return(!deserialized.Success ? null : deserialized?.Data?.ToString());
            }
        }
Пример #23
0
 /// <summary>
 /// WBS节点文件路径下所有文件的移动
 /// Created:20170330(ChengMengjia)
 /// Updated:20170607(ChengMengjia)
 /// </summary>
 /// <param name="type"></param>
 /// <param name="CurrentNodeID">最新NodeID</param>
 public static void WBSMoveFloder(UploadType type, string CurrentNodeID)
 {
     try
     {
         WBSBLL wbsBll = new WBSBLL();
         if (CurrentNodeID.Length <= 36 || CurrentNodeID.Substring(37).Equals("1"))
         {
             return;//没有最新版本号
         }
         string oldNodeID = CurrentNodeID.Substring(0, 36) + "-" + (int.Parse(CurrentNodeID.Substring(37)) - 1).ToString();
         string oldPath   = GetWorkdir() + wbsBll.GetWBSPath(oldNodeID);
         string newPath   = GetWorkdir() + wbsBll.GetWBSPath(CurrentNodeID);
         if (oldPath.Equals(newPath) || !Directory.Exists(oldPath))
         {
             return;
         }
         if (Directory.Exists(newPath))
         {
             //需要先将目标路径删除否则无法移动
             Directory.Delete(newPath, true);
         }
         string[] newP = newPath.Split('\\');
         string   s    = newPath.Substring(0, newPath.Length - 2 - newP[newP.Count() - 2].Length);
         if (!Directory.Exists(s))
         {
             Directory.CreateDirectory(s);
         }
         Directory.Move(oldPath, newPath);
     }
     catch (Exception ex)
     {
         LogHelper.WriteException(ex, LogType.CommonDLL);
     }
 }
Пример #24
0
        /// <summary>
        /// 打开文件
        /// Created:2017.3.30(xuxb)
        /// </summary>
        /// <param name="type"></param>
        /// <param name="projectId"></param>
        /// <param name="nodeId"></param>
        /// <param name="fileName"></param>
        public static void OpenFile(UploadType type, string projectId, string nodeId, string fileName)
        {
            string path = GetFilePath(type, projectId, nodeId, fileName);

            if (!File.Exists(path))
            {
                MessageHelper.ShowMsg(MessageID.W000000005, MessageType.Alert);
                return;
            }

            //定义一个ProcessStartInfo实例
            System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
            //设定打开文件的目录
            info.WorkingDirectory = GetWorkdir() + GetUploadPath(type, projectId, nodeId);
            //设定打开文件名
            info.FileName = @fileName;
            //设定打开参数
            info.Arguments = "";

            try
            {
                //打开文件
                System.Diagnostics.Process.Start(info);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                LogHelper.WriteException(ex, LogType.ProjectManagement);
                MessageHelper.ShowMsg(MessageID.E000000002, MessageType.Alert);
            }
        }
Пример #25
0
 public static string CacheKeyGenerator(this string fileName, UploadType type, bool isBlur, int width = 0, int height = 0)
 {
     if (width != 0 && height != 0)
     {
         return($"Cache{fileName}/{type}/{width}/{height}/{isBlur}");
     }
     return($"Cache{fileName}/{type}/{isBlur}");
 }
Пример #26
0
 public UploadResult(string message, UploadType type = UploadType.SUCCESS)
 {
     Data = new Dictionary <string, string>()
     {
         { "type", type.GetHashCode().ToString() },
         { type == UploadType.ERROR ? "message" : "url", message }
     };
 }
Пример #27
0
 public IActionResult UploadMultiple(UploadType type, bool isRelativeRequested, [FromForm] MultipleFileUploadModel model)
 {
     HttpContext.Request.Headers.TryGetValue("announcementId", out var announcementIdValue);
     HttpContext.Request.Headers.TryGetValue("announcementPhotoType", out var announcementPhotoTypeValue);
     int.TryParse(announcementIdValue.FirstOrDefault(), out var announcementId);
     Enum.TryParse(announcementPhotoTypeValue.FirstOrDefault(), out AttachmentType announcementPhotoType);
     return(MakeActionCallWithModel(() => _service.MultipleFileUploader(model, type, announcementPhotoType, isRelativeRequested, announcementId), model));
 }
Пример #28
0
        public static string GetDestFileName(string name, UploadType uploadType)
        {
            var fileName = GetFileName(name);

            var fileNewName =
                $"{Path.GetFileNameWithoutExtension(fileName)}-{DateTime.Now.Ticks}{Path.GetExtension(fileName)}";

            return(fileNewName);
        }
Пример #29
0
        public void SetDone(UploadType type, DateTimeOffset timestamp, int count)
        {
            Console.WriteLine($"done {type}: {timestamp} {count}");

            _repoManager.UploadEntryRepository.Add(new UploadEntry()
            {
                Type = type, Timestamp = timestamp, Count = count
            });
        }
Пример #30
0
        /// <summary>
        ///     Returns a list of any orders that were recently updated.
        /// </summary>
        /// <param name="options">Valid options: Items, Marketgroups, Regions, Date, RowLimit</param>
        /// <param name="type"></param>
        /// <returns>A list of any orders that were recently updated.</returns>
        /// <exception cref="EveLibWebException">The request was invalid.</exception>
        public Task <EmdResponse <RecentUploads> > GetRecentUploadsAsync(EmdOptions options,
                                                                         UploadType type)
        {
            Contract.Requires(options != null, "Options cannot be null.");
            string relUri     = "/api/recent_uploads2." + Format.ToString().ToLower();
            string postString = getRecentUploadsQueryString(options, type);

            return(requestAsync <RecentUploads>(relUri, postString));
        }
Пример #31
0
    /// <summary>
    /// Upload a file and return a JSON result
    /// </summary>
    /// <param name="file">The file to upload.</param>
    /// <param name="fileCollection"></param>
    /// <param name="type"> type of upload</param>
    /// <returns>a FileUploadJsonResult</returns>
    /// <remarks>
    /// It is not possible to upload files using the browser's XMLHttpRequest
    /// object. So the jQuery Form Plugin uses a hidden iframe element. For a
    /// JSON response, a ContentType of application/json will cause bad browser
    /// behavior so the content-type must be text/html. Browsers can behave badly
    /// if you return JSON with ContentType of text/html. So you must surround
    /// the JSON in textarea tags. All this is handled nicely in the browser
    /// by the jQuery Form Plugin. But we need to overide the default behavior
    /// of the JsonResult class in order to achieve the desired result.
    /// </remarks>
    /// <seealso cref="http://malsup.com/jquery/form/#code-samples"/>
    //     [Authorize]
    public FileUploadJsonResult AjaxUpload(IEnumerable<HttpPostedFileBase> fileCollection, UploadType type, string uploadPath)
    {


        _type = type;
        // TODO: Add your business logic here and/or save the file
        //System.Threading.Thread.Sleep(2000); // Simulate a long running upload
        // Some browsers send file names with full path. This needs to be stripped.


        //string physicalPath = PathForUpload(file.FileName, 0);


        //// The files are not actually saved in this demo
        //file.SaveAs(physicalPath);
        //lastSavedFile.Add(ResolvePath(physicalPath));
        foreach (string file in Request.Files)
        {
            var postedFile = Request.Files[file];
            string thumbPath;
            TimeSpan aduration;
            string filetype;
            UploadRepository.StoreMediaTemp(HttpContext, postedFile, _type, out thumbPath, out uploadPath, out aduration, out filetype);
            // Return JSON
            if (postedFile != null)
            {
                if (Request.Url != null)
                {
                    var result=new FileUploadJsonResult
                    {
                        Data =
                        new
                        {
                            message =
                            string.Format("Uploaded {0} successfully.", postedFile.FileName),
                            thumbnail = _path +"/"+ thumbPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty),
                            type = !String.IsNullOrEmpty(filetype)?filetype : MimeExtensionHelper.FindMime(uploadPath, true),
                            text = MimeExtensionHelper.FindMime(uploadPath, true).Contains("text") ? thumbPath : "",
                            path = uploadPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty),
                            originalFileName = postedFile.FileName,
                            duration = aduration.ToString()
                        }
                    };
                    return result;
                }
            }
        }



        return new FileUploadJsonResult { Data = new { message = "Upload Failed" } };


    }
Пример #32
0
    public static string PathForUpload(HttpContextBase context,string path, string owner, string id, string filename,UploadType type, bool? isThumb = false) // 0 Media, 1 profile pic, 2 coupon
    {
        string fileName = Path.GetFileName(path);
        string physicalPath = null;
        if (fileName != null)
        {
            if (type == UploadType.Media)
            {
                if (!((bool) (isThumb)))
                {
                    physicalPath =
                  Path.Combine(context.Server.MapPath("~/Uploads/Media/" + owner + "/" + id), filename + Path.GetExtension(fileName));
                }
                else
                {
         //      if (ClassViewModelExtensions.Displayableurls.Contains(Path.GetExtension(path)))
                   // { 
                   physicalPath =
                  Path.Combine(context.Server.MapPath("~/Uploads/Media/" + owner + "/" + id),
                                "Thumb"  + filename + ".jpg");//Path.GetExtension(fileName));
                  //  }
               //else
               //{
               //    if(ClassViewModelExtensions.PowerpointExtensions.Contains(Path.GetExtension(path)))
               //    {
               //        physicalPath = Path.Combine(context.Server.MapPath("~/Content/Images/powerpoint.png"));
               //    }
               //}
                }
            }
              
            //else if (type == UploadType.Coupon)
            //{
            //    physicalPath =
            //   Path.Combine(context.Server.MapPath("~/Uploads/Coupons/" + owner + "/" + id),
            //            ((bool)isThumb ? "Thumb" : "") + filename + Path.GetExtension(fileName));
            //}
            //else if (type == UploadType.Logo)
            //{
            //    physicalPath =
            //   Path.Combine(context.Server.MapPath("~/Uploads/Logos/" + owner + "/" + id),
            //            ((bool)isThumb ? "Thumb" : "") + filename + Path.GetExtension(fileName));
            //}
            else if (type == UploadType.Profile)
            {
                physicalPath =
                    Path.Combine(context.Server.MapPath("~/Uploads/Profiles/" + owner + "/" + id),
                                 ((bool)isThumb ? "Thumb" : "") + filename + Path.GetExtension(fileName));
            }

        }
        return physicalPath;
    }
Пример #33
0
 public InboundRequest(List<IToaModel> models)
 {
     _uploadType = UploadType.Incremental;
     _uploadDate = DateTime.Now.ToString("yyyy-MM-dd");
     //_activitySettings = new ActivitySettingsModel();
     //_inventorySettings = new InventorySettingsModel();
     //_processingMode = ProcessingMode.None;
     //_allowChangeDate = AllowChangeDate.Yes;
     //_propertiesMode = PropertiesMode.None;
     //_transactionId = "";
     //_providerGroup = "";
     //_defaultAppointmentPool = "";
     _dataModels = models;
 }
Пример #34
0
        public static String CreateUploadToken(String accessKey, String secretKey, ServiceType serviceType, FileType fileType, UploadType uploadType, string fileName, string fileKey, Int64 fileSize, Int64 timeoutSec, string callbackUrl)
        {
            Dictionary<string, object> jsonObj = new Dictionary<string, object>();

            jsonObj.Add("uptype", (int)uploadType);
            jsonObj.Add("servicetype", (int)serviceType);
            jsonObj.Add("filekey", fileKey);
            jsonObj.Add("filename", fileName);
            jsonObj.Add("filesize", fileSize);
            jsonObj.Add("filetype", (int)fileType);
            jsonObj.Add("callbackurl", callbackUrl);

            return CreateToken(jsonObj, secretKey, accessKey, timeoutSec);
        }
Пример #35
0
 public IEnumerable<string> GetFiles(UploadType type = UploadType.Image)
 {
     var list = new List<string>();
     var exts = (type == UploadType.Image ? _config.ImageExts : _config.AttachExts).Split(',');
     foreach (var dir in GetDirectories())
     {
         var path = Path.Combine(_urlPath, dir);
         var info = new DirectoryInfo(_context.Server.MapPath(path));
         if (info.Exists)
         {
             list.AddRange(GetFiles(path, info, exts));
         }
     }
     return list;
 }
Пример #36
0
    // [Authorize]
    public ActionResult Index(string MediaId, UploadType type)
    {
        switch (type)
        {
        case UploadType.Media:
            ViewBag.Name = "MediaUploadForm";
            break;

        default:
            ViewBag.Name = "MediaUploadForm";
            break;
        }
        ViewBag.autoUpload = true;
        ViewBag.multiple = false;
        ViewBag.Type = _type;
        _type = type;

        if (HttpContext.Session != null)
            _currentMedia = (string)HttpContext.Session["CurrentMedia"];
        //if (HttpContext.Session != null)
        //    HttpContext.Session["CurrentMedia"] = MediaId;

        return View();
    }
Пример #37
0
        public UploadFilesToFrbServer(IResults results, UploadType uploadType)
            : base(
            @"Upload files to daily build location", results)
        {
            int number = 1;
            string fileName = "build_" + DateTime.Now.ToString("yyyy") + "_" + DateTime.Now.ToString("MM") + "_" +
                DateTime.Now.ToString("dd") + "_";

            switch (uploadType)
            {
                case UploadType.Monthly:
                    _deleteBeforeDate = DateTime.MinValue;
                    _ftpFolder += "MonthlyBackups/";
                    _backupFolder += "MonthlyBackups/";
                    break;
                case UploadType.Weekly:
                    _deleteBeforeDate = DateTime.Now.AddMonths(-1);
                    _ftpFolder += "WeeklyBackups/";
                    _backupFolder += "WeeklyBackups/";
                    break;
                default:
                    _deleteBeforeDate = DateTime.Now.AddDays(-7);
                    _ftpFolder += "DailyBackups/";
                    _backupFolder += "DailyBackups/";
                    _ftpCopyToFolder = "flatredball.com/content/FrbXnaTemplates/DailyBuild/";
                    break;
            }

            while (FolderExists(_ftpFolder + fileName + number.ToString("00")))
            {
                number++;
            }
            _ftpFolder += fileName + number.ToString("00") + "/";

            CleanUpBackups();
        }
Пример #38
0
        /// <summary>
        /// Uploads the while using async.
        /// </summary>
        public void UploadWhileUsingAsync()
        {
            if(this.uploadType != UploadType.WhileUsingAsync)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NetworkChange.NetworkAddressChanged +=
                        new NetworkAddressChangedEventHandler(networkChanged);
                });

                this.uploadType = UploadType.WhileUsingAsync;
            }

            this.uploadIntelligent();
        }
Пример #39
0
        /// <summary>
        /// Inits this instance.
        /// </summary>
        private void init(Guid applicationId, UploadType uploadType, string applicationVersion)
        {
            this.applicationId = applicationId;
            this.applicationVersion = applicationVersion;
            this.sessionId = Guid.NewGuid();

            this.iStorageDal = new StorageSql(connectonString);
            this.iUploadDal = new UploadWS(baseUrl);

            this.iDeviceInformation = new DeviceInformation();
            this.iDeviceDynamicInformation = new DeviceDynamicInformation();
            this.iPlatform = new Platform();

            try
            {
                this.initDatabase();

                this.databaseExists = true;
            }
            catch (ExceptionDatabaseLayer) { }

            if (this.databaseExists)
            {
                AppactsPlugin.Data.Model.ApplicationMeta applicationMeta = null;
                bool applicationInitialSetup = false;

                try
                {
                    applicationMeta = this.iStorageDal.GetApplication(this.applicationId);

                    if (applicationMeta == null)
                    {
                        applicationMeta = new ApplicationMeta(this.applicationId, ApplicationStateType.Close, DateTime.Now, OptStatusType.OptIn);

                        this.iStorageDal.Save(applicationMeta);
                        applicationInitialSetup = true;
                    }
                }
                catch (ExceptionDatabaseLayer ex)
                {
                    this.logSystemError(ex);
                }

                try
                {
                    this.optStatusType = applicationMeta.OptStatus;

                    if (applicationMeta.State == ApplicationStateType.Open)
                    {
                        this.iStorageDal.Save(new Crash(this.applicationId, applicationMeta.SessionId, this.applicationVersion));
                    }

                    this.iStorageDal.Save(new EventItem(this.applicationId, null, null,
                        EventType.ApplicationOpen, 0, this.sessionId, this.applicationVersion));

                    applicationMeta.SessionId = this.sessionId;
                    applicationMeta.State = ApplicationStateType.Open;

                    if (applicationMeta.Version == null || applicationMeta.Version != this.applicationVersion)
                    {
                        applicationMeta.Version = this.applicationVersion;
                        applicationMeta.Upgraded = !applicationInitialSetup;
                    }

                    this.iStorageDal.Update(applicationMeta);

                    //#if DEBUG
                   // throw new ExceptionDatabaseLayer(new Exception("Random test"));
                    //#endif
                }
                catch (ExceptionDatabaseLayer exceptionDatabaseLayer)
                {
                    this.logSystemError(exceptionDatabaseLayer);
                }
            }

            this.session = new Session();
        }
Пример #40
0
 public static string ParseUploadType(UploadType uploadType)
 {
     switch (uploadType)
     {
         case UploadType.Unknown:
             return "Unknown";
         case UploadType.Image:
             return "Image";
         case UploadType.Video:
             return "Video";
         case UploadType.Certificate:
             return "Certificate";
         default:
             return string.Empty;
     }
 }
Пример #41
0
 public static string GetString(UploadType uploadType)
 {
     string ret = "";
     switch (uploadType)
     {
         case UploadType.Full:
             ret = "full";
             break;
         case UploadType.Incremental:
             ret = "incremental";
             break;
         default:
             ret = "full";
             break;
     }
     return ret;
 }
Пример #42
0
 public Hashtable SaveFile(string dir = "", UploadType type = UploadType.Image)
 {
     if (_context == null || _context.Request.Files.Count == 0)
     {
         return new Hashtable {{"state", "请选择要上传的文件!"}, {"url", ""}};
     }
     if (!Directory.Exists(_basePath))
     {
         Directory.CreateDirectory(_basePath);
     }
     var file = _context.Request.Files[0];
     string fileName = file.FileName,
            ext = Path.GetExtension(fileName);
     var exts = (type == UploadType.Image ? _config.ImageExts : _config.AttachExts);
     var limit = (type == UploadType.Image ? _config.ImageSizeLimit : _config.AttachSizeLimit);
     if (string.IsNullOrEmpty(ext) || !exts.Contains(ext))
     {
         return new Hashtable
             {
                 {
                     "state",
                     string.Format("只能上传{0}格式的文件!", exts.Aggregate("", (c, t) => c + t + ",").TrimEnd(','))
                 },
                 {"url", ""}
             };
     }
     if (file.ContentLength >= limit*1024)
     {
         return new Hashtable
             {
                 {"state", string.Format("文件大小不能超过{0}k!", limit)},
                 {"url", ""}
             };
     }
     string basePath = _basePath,
            urlPath = _urlPath;
     if (!string.IsNullOrEmpty(dir))
     {
         basePath = Path.Combine(basePath, dir);
         if (!Directory.Exists(basePath))
             Directory.CreateDirectory(basePath);
         urlPath = Path.Combine(urlPath, dir);
     }
     string name = Format("fileNameFormat".Query(""), fileName),
            path = Path.Combine(basePath, name);
     var ai = 1;
     while (File.Exists(path))
     {
         path = Path.Combine(basePath, Path.GetFileNameWithoutExtension(name) + "_" + ai++ + ext);
     }
     _urlPath = Path.Combine(urlPath, Path.GetFileName(path) ?? "");
     if (type == UploadType.Image)
     {
         using (var img = new ImageCls(file.InputStream))
         {
             if (!img.ResizeImg(path, 90))
             {
                 return new Hashtable {{"state", "保存文件失败!"}, {"url", ""}};
             }
         }
     }
     else
     {
         file.SaveAs(path);
     }
     return new Hashtable
         {
             {"state", "SUCCESS"},
             {"url", _urlPath.Replace("\\", "/")},
             {"currentType", ext},
             {"originalName", fileName}
         };
 }
Пример #43
0
 public Uploads(String savePath, String newName, UploadType uploadType)
 {
     this.uploadType = uploadType;
     this.savePath = savePath;
     this.newName = newName;
 }
Пример #44
0
 private void btnUploadOne_Click(object sender, EventArgs e)
 {
     UploadState = UploadType.Single;
     this.Close();
 }
Пример #45
0
 private void btnUploadMany_Click(object sender, EventArgs e)
 {
     UploadState = UploadType.Many;
     this.Close();
 }
Пример #46
0
 private void cmdSave_Click(object sender, EventArgs e)
 {
     MissionUploadResult = UploadType.SaveMission;
 }
Пример #47
0
    public static string[] GetFileUrl(HttpContextBase context, string mediaID, string ownerID , UploadType type, out UploadedContent upload)
    {
        upload = null;
        try
        {


            if (context.Session != null)
            {
                var uploadedContents =
                    ((List<UploadedContent>) context.Session["SavedFileList"]);
                var guid = (UrlFriendlyGuid) context.Session["UploadGUID"];
                if (uploadedContents != null && uploadedContents.Count>0)
                {
                    UploadedContent thisContent = uploadedContents.Find(
                                                      content =>
                                                      content.MediaGuid == guid && content.Type == type);

                    upload = thisContent;

                    List<string> pictures = thisContent.
                                            Pictures;

                    string newPath = PathForUpload(context,
                                                   pictures[0],
                                                   ownerID,
                                                   mediaID,
                                                   guid
                                                   , type,
                                                   false);

                    string thumbPath = PathForUpload(context,
                                                     pictures[0],
                                                     ownerID,
                                                     mediaID,
                                                     guid
                                                     , type,
                                                     true);


                    FileUtilities.FolderCreate(Path.GetDirectoryName(newPath));
                    File.Copy(TempPathForUpload(context, pictures[0], type, guid),newPath);
                    try //Maybe No Thumbnail
                    {
                        if (!pictures[1].ToLower().Contains("Content\\".ToLower()))
                        {
                            File.Copy(TempPathForUpload(context, pictures[1], type, guid, true), thumbPath);
                        }
                        else
                        {
                            File.Copy(context.Server.MapPath("~/"+pictures[1]),thumbPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("No Thumbnail" + ex.Message);
                    }
                    uploadedContents.Remove(thisContent);

                    context.Session["SavedFileList"] = uploadedContents;

                    return new string[] { ResolvePath(context, newPath), ResolvePath(context, thumbPath) };
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);

        }
        return null;
    }
Пример #48
0
 private void cmdUpload_Click(object sender, EventArgs e)
 {
     MissionUploadResult = UploadType.UploadMission;
 }
Пример #49
0
    public static string StoreMediaTemp(HttpContextBase context, HttpPostedFileBase file, UploadType type, out string thumbPath, out string physicalPath, out TimeSpan duration, out string fileType)
    {
        duration = TimeSpan.Zero;
        fileType = "";
        if (context.Session != null)
        {
            UrlFriendlyGuid GUID = (UrlFriendlyGuid) context.Session["UploadGUID"];

            List<UploadedContent> lastSavedFile = new List<UploadedContent>();

            if (context.Session["SavedFileList"] != null)
                lastSavedFile = (List<UploadedContent>) context.Session["SavedFileList"];

            physicalPath = TempPathForUpload(context, file.FileName, type, GUID);
            thumbPath = TempPathForUpload(context, file.FileName, type, GUID, true);

            //Todo: Use mimes here instead of basic extension check
            if (ImageExtensions.Contains(Path.GetExtension(file.FileName).ToLower()))
            {
                var image = (Bitmap) Image.FromStream(file.InputStream);


                var fullImage =
                    (Bitmap) ImageUtilities.Resize(image, image.Width, image.Height, RotateFlipType.RotateNoneFlipNone); //No need to resize
                ImageUtilities.SaveImage(fullImage, physicalPath, ImageFormat.Jpeg, true);



                var thumbNail =
                    (Bitmap) ImageUtilities.Resize(image, 216, 132, RotateFlipType.RotateNoneFlipNone);
                ImageUtilities.SaveImage(thumbNail, thumbPath, ImageFormat.Jpeg, true);

                duration = new TimeSpan(0,0,10);

                fileType = "Image";
            }
            else
            {
                var extension = Path.GetExtension(file.FileName);
                if (extension != null && extension.ToLower()==(".txt"))
                {
                    FileUtilities.SaveStream(file.InputStream,physicalPath,false);
                    duration = new TimeSpan(0, 0, 20);
                    var text = new StreamReader(physicalPath).ReadToEnd();
                    var ssHot = CreateImage(text.Substring(0, text.Length>15?15:text.Length));
                    thumbPath = thumbPath.Replace(Path.GetExtension(thumbPath), ".jpg");
                    ssHot.Save(thumbPath);

                    fileType = "Marquee";
                }
                else
                {
                    var s = Path.GetExtension(file.FileName);
                    if (s != null && (s.ToLower() == (".ppt") || s.ToLower() == (".pps") || s.ToLower() == (".pptx") || s.ToLower() == (".odt"))) // Powerpoint presentation
                    {
                        string path = context.Server.MapPath("~/Logs/" + "serverlog.txt");

                        Logger.WriteLine(path, "UploadRepository:  Powerpoint");

                        FileUtilities.SaveStream(file.InputStream, physicalPath, false);

                        Logger.WriteLine(path, "UploadRepository:  Saved File @ " + physicalPath);
                        var finalPath = Path.ChangeExtension(physicalPath, "wmv");
                        Microsoft.Office.Interop.PowerPoint._Presentation objPres;
                        var objApp = new Microsoft.Office.Interop.PowerPoint.Application();

                        objApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
                        objApp.Activate();
                        try
                        {
                            objPres = objApp.Presentations.Open(physicalPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse); //Last value causes powerpoint to physically open
                            // Thread.Sleep(10000);
                            objPres.SaveAs(Path.GetFullPath(finalPath), Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsWMV);
                            Logger.WriteLine(path, "UploadRepository:  SaveCopy As Successfully Started @ " + physicalPath + " to "+ finalPath);
               
                            long len = 0;
                            do
                            {
                                System.Threading.Thread.Sleep(500);
                                try
                                {
                                    FileInfo f = new FileInfo(finalPath);
                                    len = f.Length;
                                    Logger.WriteLine(path, "UploadRepository:  SaveCopy Current Length  " + len);
               
                                }
                                catch
                                {
                                    //continue;
                                }
                            }
                            while (len == 0);
                            objPres.Close();
                            objApp.Quit();

                            Marshal.ReleaseComObject(objPres);
                            Marshal.ReleaseComObject(objApp);

                            objApp = null;
                            objPres = null;

                            GC.Collect();
                            GC.WaitForPendingFinalizers();
                            Logger.WriteLine(path, "UploadRepository:  SaveCopy Done, Creating Thumbnails  ");
           

                            thumbPath = thumbPath.Replace(Path.GetExtension(thumbPath), ".jpg");
                            // thumbPath = "Content\\Images\\powerpoint.jpg";
                            duration = VideoUtilities.GetVideoDuration(finalPath);
                            // duration = new TimeSpan(0, 0, 0,60);
                            VideoUtilities.GetVideoThumbnail(finalPath, thumbPath);

                            physicalPath = finalPath;
                            fileType = "Powerpoint";
                        }
                        catch (COMException exception)
                        {
              
                            Logger.WriteLine(path, "UploadRepository: " + exception.StackTrace + "\n" + exception.Message + " Powerpoint fin:" + finalPath +" phys:" +physicalPath);

                            //   Logger.WriteLine(path, greenlotsInfo.email);

                            //    throw exception;
                        }

                    }
                    else // Must Be Video
                    {
                        FileUtilities.SaveStream(file.InputStream, physicalPath, false);

                        thumbPath= thumbPath.Replace(Path.GetExtension(thumbPath), ".jpg");
                        duration = VideoUtilities.GetVideoDuration(physicalPath);

                        VideoUtilities.GetVideoThumbnail(physicalPath,thumbPath);

                        fileType = "Video";
                    }
                }
            }

            var uploadedContent = new UploadedContent
                                      {
                                          MediaGuid = GUID,
                                          Type = type,
                                          Pictures = new List<string>(2),
                                          Duration = duration
                                      };

            if (physicalPath != null)
                uploadedContent.Pictures.Add(ResolvePath(context, physicalPath));
            if (thumbPath != null)
                uploadedContent.Pictures.Add(ResolvePath(context, thumbPath));



            if (uploadedContent.Pictures.Count > 0)
                lastSavedFile.Add(uploadedContent);


            context.Session["SavedFileList"] = lastSavedFile;


            return "Upload Sucessful";
        }
        thumbPath = "";
        physicalPath = "";

        return "Failed To Upload File(s)";
    }
 public InventorySettingsModel()
 {
     _keyFields = new string[] {ActivityProperty.InvTypeLabel};
     _uploadType = UploadType.Full;
 }
Пример #51
0
 public Uploads(UploadType uploadType)
     : this(UploadPath.Temp, null, uploadType)
 {
 }
Пример #52
0
 public Validate(String fileName, UploadType uploadType)
 {
     this.uploadType = uploadType;
     this.fileName = fileName;
 }
Пример #53
0
    public static string TempPathForUpload(HttpContextBase context,string path, UploadType type, string _currentMedia, bool isThumb = false)
    {
        try
        {
            string fileName = Path.GetFileName(path);
            string physicalPath = null;
            if (fileName != null)
            {
                if (type == UploadType.Media)
                {


                    physicalPath =
                        Path.Combine(
                            context.Server.MapPath("~/Uploads/Temp/Media/"),
                            ((bool)isThumb ? "Thumb" : "") + _currentMedia + Path.GetExtension(fileName));
                }
                //else if (type == UploadType.Logo)
                //{
                //    physicalPath =
                //        Path.Combine(
                //            context.Server.MapPath("~/Uploads/Temp/Logos/" + AccountsRepository.MyAccountID),
                //            ((bool) isThumb ? "Thumb" : "") + _currentMedia + Path.GetExtension(fileName));
                //}
                else if (type == UploadType.Profile)
                {
                    //physicalPath =
                    //    Path.Combine(
                    //        context.Server.MapPath("~/Uploads/Temp/Profiles/" + AccountsRepository.MyAccountID),
                    //        ((bool) isThumb ? "Thumb" : "") + _currentMedia + Path.GetExtension(fileName));

                    physicalPath =
                        Path.Combine(
                            context.Server.MapPath("~/Uploads/Temp/Profiles/"),
                            ((bool)isThumb ? "Thumb" : "") + _currentMedia + Path.GetExtension(fileName));
                }

                //else if (type == UploadType.Coupon)
                //{
                //    physicalPath =
                //        Path.Combine(
                //            context.Server.MapPath("~/Uploads/Temp/Coupons/" + AccountsRepository.MyAccountID),
                //            ((bool) isThumb ? "Thumb" : "") + _currentMedia + Path.GetExtension(fileName));
                //}

            }
            return physicalPath;
        }
        catch (Exception)
        {

        }
        return "";
    }
Пример #54
0
        /// <summary>
        /// Starts the specified assembly.
        /// </summary>
        /// <param name="baseUrl">base url i.e. the url of the API http://yoursite.com/api/ </param>
        /// <param name="assembly">The assembly.</param>
        /// <param name="applicationId">The application id.</param>
        /// <param name="uploadType">Type of the upload.</param>
        public void Start(string baseUrl, Assembly assembly, string applicationId, UploadType uploadType)
        {
            if (!this.started)
            {
                if (String.IsNullOrEmpty(baseUrl))
                {
                    throw new Exception("You need to specify baseUrl, i.e. your server api url http://yoursite.com/api/");
                }

                this.baseUrl = baseUrl;

                string applicationVersion = null;
                try
                {
                    AssemblyName assemblyName = new AssemblyName(assembly.FullName);
                    applicationVersion = assemblyName.Version.ToString();
                }
                catch
                {
                    applicationVersion = "0";
                }

                this.init(new Guid(applicationId), uploadType, applicationVersion);

                this.threadUploadInterrupted = false;
                this.started = true;
                this.stopped = false;

                if (uploadType == UploadType.WhileUsingAsync)
                {
                    this.UploadWhileUsingAsync();
                }
            }
        }
Пример #55
0
 /// <summary>
 ///     Resolves UploadType to it's query string value.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public string UploadTypeToString(UploadType type)
 {
     switch (type) {
         case UploadType.Orders:
             return "o";
         case UploadType.History:
             return "h";
         case UploadType.Both:
             return "b";
         default:
             throw new NotImplementedException();
     }
 }
Пример #56
0
        public UploadFilesToFrbServer(IResults results, UploadType uploadType)
            : base(
            @"Upload files to daily build location", results)
        {
            int number = 1;
            string fileName = "build_" + DateTime.Now.ToString("yyyy") + "_" + DateTime.Now.ToString("MM") + "_" +
                DateTime.Now.ToString("dd") + "_";

            switch (uploadType)
            {
                case UploadType.Monthly:
                    _deleteBeforeDate = DateTime.MinValue;
                    _ftpFolder += "MonthlyBackups/";
                    _backupFolder += "MonthlyBackups/";
                    break;
                case UploadType.Weekly:
                    _deleteBeforeDate = DateTime.Now.AddMonths(-1);
                    _ftpFolder += "WeeklyBackups/";
                    _backupFolder += "WeeklyBackups/";
                    break;
                default:
                    _deleteBeforeDate = DateTime.Now.AddDays(-7);
                    _ftpFolder += "DailyBackups/";
                    _backupFolder += "DailyBackups/";
                    _ftpCopyToFolder = "files.flatredball.com/content/FrbXnaTemplates/DailyBuild/";
                    break;
            }

            while (FolderExists(_ftpFolder + fileName + number.ToString("00")))
            {
                number++;
            }
            _ftpFolder += fileName + number.ToString("00") + "/";

            // who cares about cleaning up backups? We have infinite storage, this takes time, and it's crashing as oif
            // December 12, 2015
            //CleanUpBackups();
        }