private void SavePostedFile(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
                return ;

            var fileOriginalName = uploadedFile.FileName;

            int index;
                for (index = 0; index < UploadControlBudges.UploadedFiles.Length; index++)
                {
                    if (UploadControlBudges.UploadedFiles[index].FileName == fileOriginalName)
                    {
                        break;
                    }
                }
            if (index == 0)
            {
                _fileGroupId = _dal.RegisterNewBadgesFileGroup(tbBadgeGroupName.Text, tbMessage.Text, TbDescription.Text, cbImageType.Text, Convert.ToInt32(cbGrantRule.SelectedItem.Value));
            }

            var guid = Guid.NewGuid();

            string fileName = Path.Combine(MapPath(UploadDirectory), guid.ToString() + ".png");
            uploadedFile.SaveAs(fileName, true);
            _dal.RegisterNewBadgeInFileGroup(_fileGroupId, guid, index);
        }
    public override Stream GetOutputStream(UploadedFile file)
    {
        FileStream fileS = null;
        ZipOutputStream zipS = null;

        try
        {
            string outputPath = GetZipPath(file);

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            fileS = File.OpenWrite(outputPath);
            zipS = new ZipOutputStream(fileS);

            zipS.SetLevel(5);

            zipS.PutNextEntry(new ZipEntry(file.ClientName));

            file.LocationInfo[FileNameKey] = outputPath;

            return zipS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();

            if (zipS != null)
                zipS.Dispose();

            return null;
        }
    }
        public override void InsertFile(UploadedFile file)
        {
            UploadStorageDataContext db = new UploadStorageDataContext(ConfigurationManager.ConnectionStrings[this.ConnectionStringName].ConnectionString);

            Table<LinqUploadedFile> files = db.GetTable<LinqUploadedFile>();

            file.ApplicationName = this.ApplicationName;

            files.InsertOnSubmit(new LinqUploadedFile(file));

            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException ex)
            {
                Trace.TraceError(ex.Message);

                // All database values overwrite current values.
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                    occ.Resolve(RefreshMode.OverwriteCurrentValues);
            }
            catch (DbException ex)
            {
                Trace.TraceError(ex.Message);
            }
        }
Exemplo n.º 4
0
        protected void upload_button_click(object sender, EventArgs e)
        {
            if (file_upload_control.HasFile)
            {
                try
                {
                    UploadedFile uf = new UploadedFile(file_upload_control.PostedFile);

                    foreach (PropertyInfo info in uf.GetType().GetProperties())
                    {
                        TableRow row = new TableRow();

                        TableCell[] cells = new TableCell[] {new TableCell(),new TableCell(),new TableCell()};
                        cells[0].Controls.Add(new LiteralControl(info.PropertyType.ToString()));
                        cells[1].Controls.Add(new LiteralControl(info.Name));
                        cells[2].Controls.Add(new LiteralControl(info.GetValue(uf).ToString()));
                        row.Cells.AddRange(cells);

                        file_upload_details_table.Rows.Add(row);
                    }

                    status_label.Text = "Status: OK!";
                }
                catch (Exception ex)
                {
                    status_label.Text = "Status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
        }
Exemplo n.º 5
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid) return;
        if (!Permission.Check("file.create", false)) return;

        string fileName = Resources.Moo.File_UploadPath + Path.GetRandomFileName() + "." + fileUpload.FileName.Split('.').Last();
        fileUpload.SaveAs(fileName);
        int fileID;
        using (MooDB db = new MooDB())
        {
            User currentUser = ((SiteUser)User.Identity).GetDBUser(db);
            UploadedFile file = new UploadedFile()
            {
                Name = txtName.Text,
                Description = txtDescription.Text,
                Path = fileName,
                CreatedBy=currentUser
            };
            db.UploadedFiles.AddObject(file);
            db.SaveChanges();
            fileID = file.ID;

            Logger.Info(db, "创建文件#" + fileID);
        }

        PageUtil.Redirect("创建成功", "~/File/?id=" + fileID);
    }
	private UploadedFile.ExportTranslationState ExportOneSkyTranslationWithRetry(UploadedFile OneSkyFile, string Culture, MemoryStream MemoryStream)
	{
		const int MAX_COUNT = 3;

		long StartingMemPos = MemoryStream.Position;
		int Count = 0;
		for (;;)
		{
			try
			{
				return OneSkyFile.ExportTranslation(Culture, MemoryStream).Result;
			}
			catch (Exception)
			{
				if (++Count < MAX_COUNT)
				{
					MemoryStream.Position = StartingMemPos;
					Console.WriteLine("ExportOneSkyTranslation attempt {0}/{1} failed. Retrying...", Count, MAX_COUNT);
					continue;
				}

				Console.WriteLine("ExportOneSkyTranslation attempt {0}/{1} failed.", Count, MAX_COUNT);
				break;
			}
		}

		return UploadedFile.ExportTranslationState.Failure;
	}
Exemplo n.º 7
0
        public int InsertImage(UploadedFile file, int userID)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TelerikConnectionString35"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string cmdText = "INSERT INTO AsyncUploadImages VALUES(@ImageData, @ImageName, @UserID) SET @Identity = SCOPE_IDENTITY()";
                SqlCommand cmd = new SqlCommand(cmdText, conn);

                byte[] imageData = GetImageBytes(file.InputStream);

                SqlParameter identityParam = new SqlParameter("@Identity", SqlDbType.Int, 0, "ImageID");
                identityParam.Direction = ParameterDirection.Output;

                cmd.Parameters.AddWithValue("@ImageData", imageData);
                cmd.Parameters.AddWithValue("@ImageName", file.GetName());
                cmd.Parameters.AddWithValue("@UserID", userID);

                cmd.Parameters.Add(identityParam);

                conn.Open();
                cmd.ExecuteNonQuery();

                return (int)identityParam.Value;
            }
        }
Exemplo n.º 8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Permission.Check("file.read", true)) return;

        if (!Page.IsPostBack)
        {
            using (MooDB db = new MooDB())
            {
                if (Request["id"] != null)
                {
                    int fileID = int.Parse(Request["id"]);
                    file = (from f in db.UploadedFiles
                            where f.ID == fileID
                            select f).SingleOrDefault<UploadedFile>();
                }

                if (file == null)
                {
                    PageUtil.Redirect(Resources.Moo.FoundNothing, "~/");
                    return;
                }

                Page.DataBind();
            }
        }
    }
		/// <summary>
		/// Load all files stored in Storage
		/// </summary>
		/// <returns></returns>
		public static List<UploadedFile> LoadFilesForTesting()
		{
			List<UploadedFile> files = new List<UploadedFile>();
			// In design mode, HttpContext will be null
			if (HttpContextNull())
			{
				return files;
			}

			string[] configFiles = Directory.GetFiles(HttpContext.Current.Server.MapPath(appDataPath), "*" + configExtension);
			foreach (string config in configFiles)
			{
				FileInfo configFile = new FileInfo(config);
				string fileId = configFile.Name.Substring(0, configFile.Name.LastIndexOf("."));
				FileInfo originalFile = new FileInfo(FileId2FullName(fileId));

				if (originalFile.Exists)
				{
					UploadedFile fileItem = new UploadedFile();
					fileItem.Id = fileId;
					fileItem.Filename = File.ReadAllText(config);
					fileItem.Size = originalFile.Length;
					fileItem.LastModified = originalFile.LastWriteTime;

					files.Add(fileItem);
				}
			}
			return files;
		}
    public override Stream GetInputStream(UploadedFile file)
    {
        FileStream fileS = null;
        ZipInputStream zipS = null;

        try
        {
            string path = GetZipPath(file);

            fileS = File.OpenRead(path);
            zipS = new ZipInputStream(fileS);

            zipS.GetNextEntry();

            return zipS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();

            if (zipS != null)
                zipS.Dispose();

            return null;
        }
    }
        /// <inheritdoc />
        /// <summary>
        /// Overridden. <inherited />
        /// </summary>
        public override void CloseWriteStream(UploadedFile file, Stream stream, bool isComplete)
        {
            if (!isComplete)
                stream.Dispose();

            // We actually want to leave the stream open so we can read from it later if it is complete
            stream.Seek(0, SeekOrigin.Begin);
        }
Exemplo n.º 12
0
 public override async Task<object> ReadFromStreamAsync(Type type,
                                                        Stream readStream,
                                                        HttpContent content,
                                                        IFormatterLogger formatterLogger,
                                                        CancellationToken cancellationToken)
 {
     var uf = new UploadedFile(StrHelper.UnquoteToken(content.Headers.ContentDisposition.FileName),
                               await content.ReadAsStreamAsync());
     return uf;
 }
Exemplo n.º 13
0
        protected override IAsyncUploadResult Process(UploadedFile file, HttpContext context, IAsyncUploadConfiguration configuration, string tempFileName)
        {
            telerikAsyncUploadResult result = CreateDefaultUploadResult<telerikAsyncUploadResult>(file);
            string folderType = "temp";
            DocAccess objDoc = new DocAccess();

            result.DocumentID = 0;
            result.DocumentID = objDoc.saveFiles(file, folderType, Convert.ToInt32(context.Session["ClientID"]), Convert.ToInt32(context.Session["UserID"]), 0, Convert.ToInt32(context.Session["WebinarID"]));
            return result;
        }
        /// <inheritdoc />
        /// <summary>
        /// Overridden. <inherited />
        /// </summary>
        public override void RemoveOutput(UploadedFile file)
        {
            // Upload was cancelled or errored, so we need to remove and dispose the stream
            MemoryStream s = (MemoryStream)HttpContext.Current.Application[file.ServerLocation];

            if (s != null)
                s.Dispose();

            HttpContext.Current.Application.Remove(file.ServerLocation);
        }
Exemplo n.º 15
0
 public static string SavePostedFile(UploadedFile uploadedFile)
 {
     string ret = "";
     if (uploadedFile.IsValid)
     {
         string fileToSave = FileUtils.GetUploadedFileLocalName(uploadedFile.FileName);
         uploadedFile.SaveAs(fileToSave);
         ret = fileToSave;
     }
     return ret;
 }
Exemplo n.º 16
0
    //private void LooongMethodWhichUpdatesTheProgressContext(UploadedFile file)
    //{
    //    const int total = 100;

    //    RadProgressContext progress = RadProgressContext.Current;

    //    for (int i = 0; i < total; i++)
    //    {
    //        progress["PrimaryTotal"] = total.ToString();
    //        progress["PrimaryValue"] = i.ToString();
    //        progress["PrimaryPercent"] = i.ToString();
    //        progress["CurrentOperationText"] = file.GetName() + " is being processed...";

    //        if (!Response.IsClientConnected)
    //        {
    //            //Cancel button was clicked or the browser was closed, so stop processing
    //            break;
    //        }

    //        //Stall the current thread for 0.1 seconds
    //        System.Threading.Thread.Sleep(100);
    //    }
    //}

    public void ProcessVideo(UploadedFile VideoFile)
    {
        litCompleted.Text = "";
        try
        {
            member = (Member)Session["Member"];
            bool ValidExtention = true;
            string VideoTitle = string.Empty;
            string Ext = string.Empty;

            Video video = new Video();

            video.Title = (txtTitle.Text != "") ? txtTitle.Text : "New video";
            video.Description = (txtCaption.Text != "") ? txtCaption.Text : "No Description"; 

            try
            {
                Ext = VideoFile.GetExtension();
            }
            catch
            {
                Ext = "xxx";
                ValidExtention = false;
            }

            Ext = Ext.Replace(".", "");

            // upload the flv
            if (IsVideo(Ext))
            {
                if (VideoFile.ContentLength > 150000)
                {
                    Video.QueueVideoForEncoding(video, VideoFile.InputStream, Ext, member, VideoTitle);
                    litCompleted.Text = "<script>parent.location.href='MyVideoGallery.aspx?p=1';</script><img src='images/check.gif'/>&nbsp;&nbsp; Your video was successfully uploaded ";
                }
                else
                {
                    litCompleted.Text = "<img src='images/na.gif'/>&nbsp;&nbsp;Your video must be at least 2 seconds long";
                }
            }
            else
            {
                if (ValidExtention)
                    litCompleted.Text = "<img src='images/na.gif'/>&nbsp;&nbsp;Videos with the extention <strong>" + Ext + "</strong> arent supported";
                else
                    litCompleted.Text = "<img src='images/na.gif'/>&nbsp;&nbsp;Videos files must have an extention name. For example: .avi or .mov";
            }
        }
        catch(Exception ex)
        {
            string MachineName = Environment.MachineName;
            Next2Friends.Data.Trace.Tracer(ex.ToString(), "RadVideoUpload");
        }
    }
        /// <inheritdoc />
        /// <summary>
        /// Overridden. <inherited />
        /// </summary>
        public override Stream GetReadStream(UploadedFile file)
        {
            MemoryStream s = (MemoryStream)HttpContext.Current.Application[file.ServerLocation];

            // Remove the stream from application state. This means GetReadStream can only be called once per file, but ensures that
            // app state remains clean

            HttpContext.Current.Application.Remove(file.ServerLocation);

            return s;
        }
Exemplo n.º 18
0
        public void AddFile(UploadedFile file, string fileUploadContext)
        {
            string folder = GetUploadPath(fileUploadContext);
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);

            FileStream fs = File.Create(Path.Combine(folder, file.FileName), file.ContentLength);
            byte[] buffer = new byte[(int)file.InputStream.Length];
            file.InputStream.Read(buffer, 0, (int)file.InputStream.Length);
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();
        }
        /// <inheritdoc />
        /// <summary>
        /// Overridden. <inherited />
        /// </summary>
        public override Stream GetWriteStream(UploadedFile file)
        {
            // Create a stream
            MemoryStream s = new MemoryStream();
            string key = Guid.NewGuid().ToString();

            // Store it for later
            file.ServerLocation = key;
            HttpContext.Current.Application[file.ServerLocation] = s;

            return s;
        }
Exemplo n.º 20
0
 /// <summary>
 /// Returns the object name to use for a given <see cref="UploadedFile" />.
 /// </summary>
 /// <param name="file">The <see cref="UploadedFile" /> for which to generate an object name.</param>
 /// <returns>The generated object name.</returns>
 public virtual string GetObjectName(UploadedFile file)
 {
     switch (_objectNameMethod)
     {
         default:
         case ObjectNameMethod.Client:
             return file.ClientName;
         case ObjectNameMethod.Guid:
             return Guid.NewGuid().ToString("n");
         case ObjectNameMethod.GuidWithExtension:
             return Guid.NewGuid().ToString("n") + Path.GetExtension(file.ClientName);
     }
 }
        /// <inheritdoc />
        /// <summary>
        /// Overridden. <inherited />
        /// </summary>
        public override string InsertRecord(UploadedFile file, IDbConnection cn, IDbTransaction t)
        {
            using (SqlCommand cmd = (SqlCommand)cn.CreateCommand())
            {
                StringBuilder insertCommand = new StringBuilder();

                insertCommand.Append("INSERT INTO ");
                insertCommand.Append(Table);
                insertCommand.Append(" (");
                insertCommand.Append(DataField);

                if (FileNameField != null)
                {
                    insertCommand.Append(",");
                    insertCommand.Append(FileNameField);
                }

                insertCommand.Append(") OUTPUT INSERTED." + KeyField);
                insertCommand.Append(" VALUES (CAST('' AS varbinary(MAX))");

                if (FileNameField != null)
                {
                    insertCommand.Append(",@fileName");

                    SqlParameter fileNameParm = cmd.CreateParameter();

                    fileNameParm.ParameterName = "@fileName";
                    fileNameParm.DbType = DbType.String;
                    fileNameParm.Value = file.ClientName;

                    cmd.Parameters.Add(fileNameParm);
                }
                insertCommand.Append(");");

                cmd.CommandText = insertCommand.ToString();
                cmd.Transaction = t as SqlTransaction;

                try
                {
                    if (cn.State != ConnectionState.Open)
                        cn.Open();

                    return cmd.ExecuteScalar().ToString();
                }
                finally
                {
                    if (t == null)
                        cn.Close();
                }
            }
        }
        public override void InsertFile(UploadedFile entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            entity.ApplicationName = this.ApplicationName;

            using (var db = new SqlUploadStorageContext(this.ConnectionStringName))
            {
                db.UploadedFiles.Add(entity);

                db.SaveChanges();
            }
        }
Exemplo n.º 23
0
        private string SavePostedFile(UploadedFile uploadedFile)
        {
            Session["ImageUploadedFile"] = "";
            string fileName = "";
            if (uploadedFile.IsValid)
            {
                Random random = new Random();
                //string _MenuGroupId = Session["MenuGroupId"].ToString();
                string dateString = String.Format("{0}{1}{2}", System.DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                string timeString = String.Format("{0}{1}{2}", System.DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                fileName = String.Format("{0}-{1}-{2}-{3}", dateString, timeString, random.Next(), uploadedFile.FileName);
                if (Tools.IsImage(uploadedFile.FileBytes))
                {
                    Session["ImageUploadedFile"] = fileName;
                    //uploadedFile.SaveAs(Server.MapPath("~/ContentData/MenuImages/") + fileName, true);
                    //byte[] thumb = Tools.CreateThumb(uploadedFile.FileBytes, 32, true);
                    //MemoryStream stream = new MemoryStream(thumb);
                    int width = 300;
                    using (MemoryStream ms = new MemoryStream(uploadedFile.FileBytes, 0, uploadedFile.FileBytes.Length))
                    {
                        ms.Write(uploadedFile.FileBytes, 0, uploadedFile.FileBytes.Length);
                        using (System.Drawing.Image CroppedImage = System.Drawing.Image.FromStream(ms, true))
                        {
                            if (width > CroppedImage.Width)
                                width = CroppedImage.Width;
                        }
                    }
                   byte []thumb = Tools.CreateThumb(uploadedFile.FileBytes, width, false);
                    FileStream stream = new FileStream(Server.MapPath(BusinessLogicLayer.Common.ConferenceContentPath) + fileName, FileMode.Create);
                    stream.Write(uploadedFile.FileBytes, 0, uploadedFile.FileBytes.Length);
                    stream.Flush();
                    stream.Close();
                }
                else
                {
                    BusinessLogicLayer.Components.UserMonitorLogic monitorLogic = new BusinessLogicLayer.Components.UserMonitorLogic();
                    string ipMain = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    string IpForwardedFor = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    string ip = String.Format("{0}-{1}", ipMain, IpForwardedFor);
                    int userid = 0;
                    if (SecurityManager.isLogged(this.Page))
                        userid = SecurityManager.getUser(this.Page).BusinessEntityId;
                    monitorLogic.Insert(userid, false, ip, fileName, DateTime.Now);
                    fileName = "";
                }

            }
            return fileName;
        }
        public override void UpdateFile(UploadedFile entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            using (var db = new SqlUploadStorageContext(this.ConnectionStringName))
            {
                db.UploadedFiles.Attach(entity);

                var entry = db.Entry(entity);
                entry.State = EntityState.Modified;

                db.SaveChanges();
            }
        }
        public override void DeleteFile(UploadedFile entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            using (var db = new SqlUploadStorageContext(this.ConnectionStringName))
            {
                var item = db.UploadedFiles.Find(entity.ID);

                if (item == null)
                    return;

                db.UploadedFiles.Remove(item);

                db.SaveChanges();
            }
        }
Exemplo n.º 26
0
    public void DeleteFile(UploadedFile item)
    {
        UploadedFile file = _gallery.Files.Find(delegate(UploadedFile match)
        {
            if (match.ID.Equals(item.ID))
                return true;
            return false;
        });

        if (file != null)
        {
            // Removes the image from the current list.
            file.Delete();
            file.Save();

            _gallery.RemoveFile(file);
        }
    }
Exemplo n.º 27
0
        private string SavePostedFile(UploadedFile uploadedFile)
        {
            Session["UploadedFile"] = null;
            string fileName = "";
            if (uploadedFile.IsValid)
            {
                Random random = new Random();
                //string _MenuGroupId = Session["MenuGroupId"].ToString();
                string dateString = String.Format("{0}{1}{2}", System.DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                string timeString = String.Format("{0}{1}{2}", System.DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                fileName = String.Format("{0}-{1}-{2}-{3}", dateString, timeString, random.Next(), uploadedFile.FileName);
                Session["UploadedFile"] = fileName;
                FileStream stream = new FileStream(Server.MapPath(BusinessLogicLayer.Common.ConferenceScheduleDocPath) + fileName, FileMode.Create);
                stream.Write(uploadedFile.FileBytes, 0, uploadedFile.FileBytes.Length);
                stream.Flush();
                stream.Close();

            }
            return fileName;
        }
Exemplo n.º 28
0
 private string SavePostedFile(UploadedFile uploadedFile)
 {
     Session["UploadedFile"] = null;
     string fileName = "";
     if (uploadedFile.IsValid)
     {
         Random random = new Random();
         //string _MenuGroupId = Session["MenuGroupId"].ToString();
         string dateString = String.Format("{0}{1}{2}", System.DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
         string timeString = String.Format("{0}{1}{2}", System.DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
         fileName = String.Format("{0}-{1}-{2}-{3}", dateString, timeString, random.Next(), uploadedFile.FileName);
         Session["UploadedFile"] = fileName;
         //uploadedFile.SaveAs(Server.MapPath("~/ContentData/MenuImages/") + fileName, true);
         byte[] thumb = Tools.CreateThumb(uploadedFile.FileBytes, 32, true);
         //MemoryStream stream = new MemoryStream(thumb);
         FileStream stream = new FileStream(Server.MapPath(BusinessLogicLayer.Common.ConferenceContentPath) + fileName, FileMode.Create);
         stream.Write(thumb, 0, thumb.Length);
         stream.Flush();
         stream.Close();
     }
     return fileName;
 }
Exemplo n.º 29
0
    private void LooongMethodWhichUpdatesTheProgressContext(UploadedFile file)
    {
        const int total = 100;

        RadProgressContext progress = RadProgressContext.Current;

        for (int i = 0; i < total; i++)
        {
            progress["SecondaryTotal"] = total.ToString();
            progress["SecondaryValue"] = i.ToString();
            progress["SecondaryPercent"] = i.ToString();
            progress["CurrentOperationText"] = file.GetName() + " is being processed...";

            if (!Response.IsClientConnected)
            {
                //Cancel button was clicked or the browser was closed, so stop processing
                break;
            }

            //Stall the current thread for 0.1 seconds
            System.Threading.Thread.Sleep(100);
        }
    }
Exemplo n.º 30
0
        public override void UpdateFile(UploadedFile file)
        {
            if (file == null)
                throw new ArgumentNullException("file");

            UploadStorageDataContext db = new UploadStorageDataContext(ConfigurationManager.ConnectionStrings[this.ConnectionStringName].ConnectionString);

            Table<LinqUploadedFile> files = db.GetTable<LinqUploadedFile>();

            // BusinessBase inherited clases will have a downside effect with a ChangeConflictException 
            // as it has changed LastUpdated row version in the call stack.
            UploadedFile f = SelectFile(file.ID, false);

            if (f != null)
                file.LastUpdated = f.LastUpdated;

            // Assume that "file" has been sent by client.
            // Attach with "true" to the change tracker to consider the entity modified
            // and it can be checked for optimistic concurrency because
            // it has a column that is marked with "RowVersion" attribute
            files.Attach(new LinqUploadedFile(file), true);

            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException)
            {
                // All database values overwrite current values.
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                    occ.Resolve(RefreshMode.OverwriteCurrentValues);
            }
            catch (DbException ex)
            {
                Trace.TraceError(ex.Message);
            }
        }
Exemplo n.º 31
0
 public void Push(UploadedFile file)
 {
     Package.AddStream(file.InputStream, file.GetName());
 }
Exemplo n.º 32
0
        public static CFuJian Upload(UploadedFile file, string UCProcessType, string UCProcessID, string UCWorkItemID)
        {
            CFuJian cFuJian = new CFuJian();

            OA_DocumentService api = MossObject.GetMOSSAPI();

            string[] fileInfo = GetUploadFileInfo(UCProcessType, file.FileName);

            cFuJian.Type = System.IO.Path.GetExtension(file.FileName); //文件类型 扩展名
            if (cFuJian.Type.IndexOf('.') > -1)
            {
                cFuJian.Type = cFuJian.Type.Substring(1);
            }
            cFuJian.Alias = file.FileName.Substring(0, file.FileName.Length - cFuJian.Type.Length - 1); //别名
            //ff.Title = ff.Alias + "." + ff.Type;
            cFuJian.Title = fileInfo[3];
            if (cFuJian.Type.Length == 0)//没有扩展名
            {
                cFuJian.Alias = file.FileName;
            }
            cFuJian.Alias = cFuJian.Alias.Replace(" ", "");

            cFuJian.FolderName = fileInfo[2];

            cFuJian.FileName = fileInfo[3];

            cFuJian.Size        = MossObject.ToFileSize(file.ContentLength); //文件大小
            cFuJian.ProcessType = UCProcessType;
            cFuJian.WorkItemID  = UCWorkItemID;

            string[] saveUrl;

            #region DLL
            if (OAConfig.GetConfig("MOSS认证", "是否启用DLL") == "1")
            {
                #region 更新栏位
                List <System.Collections.DictionaryEntry> lst = new List <System.Collections.DictionaryEntry>();
                System.Collections.DictionaryEntry        de  = new System.Collections.DictionaryEntry();
                de.Key   = "流程实例";
                de.Value = UCProcessID;
                lst.Add(de);

                de       = new System.Collections.DictionaryEntry();
                de.Key   = "别名";
                de.Value = cFuJian.Alias;
                lst.Add(de);

                de       = new System.Collections.DictionaryEntry();
                de.Key   = "上次修改者";
                de.Value = CurrentUserInfo.DisplayName;
                lst.Add(de);
                #endregion

                System.Collections.DictionaryEntry[] result = DocumentManager.ConvertToDE(lst.ToArray());

                if (file.ContentLength <= MossObject.middleFileSize * 1024 * 1024)
                {
                    saveUrl = DocumentManager.Upload(fileInfo, MossObject.StreamToBytes(file.InputStream), result, false);
                }
                else
                {
                    string strFileTemp = "D:\\FileTemp\\";

                    if (System.IO.Directory.Exists(strFileTemp) == false)
                    {
                        System.IO.Directory.CreateDirectory(strFileTemp);
                    }

                    string fileTemp = strFileTemp + "OA" + Current.UserName + Path.GetFileNameWithoutExtension(file.TmpFile.Name);

                    string filePath = fileTemp + file.FileName;

p1:
                    if (System.IO.File.Exists(filePath))
                    {
                        filePath = fileTemp + new Random(1).Next(100).ToString() + file.FileName;
                        goto p1;
                    }
                    else
                    {
                        file.TmpFile.MoveTo(filePath);
                    }

                    saveUrl = DocumentManager.Upload(fileInfo, filePath, result, false);

                    File.Delete(filePath);
                }

                ////int ret = api.CopyTo(fileInfo, "322.doc", true);
                //file.TmpFile.Delete(); //删除临时文件
                //cFuJian.fullURL = saveUrl[0]; //全路径
                //cFuJian.URL = saveUrl[1];//文件夹+/文件名
                //cFuJian.Encode = "";//文件编码
                //return cFuJian;
            }
            #endregion

            #region webservice
            else
            {
                #region 更新栏位
                List <DictionaryEntry> lst = new List <DictionaryEntry>();
                DictionaryEntry        de  = new DictionaryEntry();
                de.Key   = "流程实例";
                de.Value = UCProcessID;
                lst.Add(de);

                de       = new DictionaryEntry();
                de.Key   = "别名";
                de.Value = cFuJian.Alias;
                lst.Add(de);

                de       = new DictionaryEntry();
                de.Key   = "上次修改者";
                de.Value = CurrentUserInfo.DisplayName;
                lst.Add(de);
                #endregion

                DictionaryEntry[] result = api.ConvertToDE(lst.ToArray());

                if (file.ContentLength <= MossObject.middleFileSize * 1024 * 1024)
                {
                    //上传到文档库
                    saveUrl = api.Upload(fileInfo, MossObject.StreamToBytes(file.InputStream), result, false);
                }
                else
                {
                    string strFileTemp = "D:\\FileTemp\\";

                    if (System.IO.Directory.Exists(strFileTemp) == false)
                    {
                        System.IO.Directory.CreateDirectory(strFileTemp);
                    }

                    string fileTemp = strFileTemp + "OA" + Current.UserName + Path.GetFileNameWithoutExtension(file.TmpFile.Name);

                    string filePath = fileTemp + file.FileName;

p1:
                    if (System.IO.File.Exists(filePath))
                    {
                        filePath = fileTemp + new Random(1).Next(100).ToString() + file.FileName;
                        goto p1;
                    }
                    else
                    {
                        file.TmpFile.MoveTo(filePath);
                    }

                    saveUrl = api.Upload_New(fileInfo, filePath, result, false);

                    File.Delete(filePath);
                }
            }

            #endregion

            file.TmpFile.Delete();        //删除临时文件

            cFuJian.fullURL = saveUrl[0]; //全路径
            cFuJian.URL     = saveUrl[1]; //文件夹+/文件名
            cFuJian.Encode  = "";         //文件编码
            return(cFuJian);
        }
Exemplo n.º 33
0
 public void Delete(UploadedFile uploadedFile)
 {
     _uploadedFileRepository.Delete(uploadedFile);
 }
Exemplo n.º 34
0
        private bool AddFile(out bool blZeroBalance, out bool blFileSizeExceeded)
        {
            // If the upload type is file
            // We need to see if the adviser has a folder in Repository folder
            // Case 1: If not, then encode the adviser id and create a folder with the encoded id
            // then create a folder for the repository category within the encoded folder
            // then store the encoded adviserID + GUID + file name
            // Case 2: If folder exists, check if the category folder exists.
            // If not then, create a folder with the category code and store the file as done above.
            // If yes, then just store the file as done above.
            // Once this is done, store the info in the DB with the file path.
            strRepositoryPath = Server.MapPath(strRepositoryPath) + "\\advisor_" + advisorVo.advisorId;
            AdvisorBo advBo = new AdvisorBo();

            repoBo = new RepositoryBo();
            bool blResult = false;

            blZeroBalance      = false;
            blFileSizeExceeded = false;

            try
            {
                // Reading File Upload Control
                if (radUploadRepoItem.UploadedFiles.Count != 0)
                {
                    // Put this part under a transaction scope
                    using (TransactionScope scope1 = new TransactionScope())
                    {
                        UploadedFile file     = radUploadRepoItem.UploadedFiles[0];
                        float        fileSize = float.Parse(file.ContentLength.ToString()) / 1048576; // Converting bytes to MB

                        // If space is there to upload file
                        if (fStorageBalance >= fileSize)
                        {
                            if (fileSize <= 20)   // If upload file size is less than 10 MB then upload
                            {
                                // Check if directory for advisor exists, and if not then create a new directoty
                                if (!Directory.Exists(strRepositoryPath))
                                {
                                    Directory.CreateDirectory(strRepositoryPath);
                                }
                                strGuid = Guid.NewGuid().ToString();
                                string newFileName = SaveFileIntoServer(file, strGuid, strRepositoryPath);
                                repoVo              = new RepositoryVo();
                                repoVo.AdviserId    = advisorVo.advisorId;
                                repoVo.CategoryCode = ddlRCategory.SelectedValue;
                                repoVo.Description  = txtDescription.Text.Trim();
                                repoVo.HeadingText  = txtHeadingText.Text.Trim();
                                repoVo.IsFile       = true;
                                repoVo.Link         = newFileName;
                                if (Request.QueryString["NCDProspect"] != null)
                                {
                                    issueId = Convert.ToInt32(Request.QueryString["issueId"].ToString());
                                }
                                blResult = repoBo.AddRepositoryItem(repoVo, issueId);

                                if (blResult)
                                {
                                    // Once the adding of repository is a success, then update the balance storage in advisor subscription table
                                    fStorageBalance = UpdateAdvisorStorageBalance(fileSize, 0, fStorageBalance);
                                }
                            }
                            else
                            {
                                blFileSizeExceeded = true;
                            }
                        }
                        else
                        {
                            blZeroBalance = true;
                        }

                        scope1.Complete();   // Commit the transaction scope if no errors
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "pageloadscript", "alert('Please select a file to upload!');", true);
                }
            }
            catch (BaseApplicationException Ex)
            {
                throw Ex;
            }
            catch (Exception Ex)
            {
                object[] objects = new object[2];
                objects[0] = repoVo;
                objects[1] = repoBo;
                PageException(objects, Ex, "ManageRepository.ascx:AddClick()");
            }
            return(blResult);
        }
    private void ExportOneSkyFileToDirectory(UploadedFile OneSkyFile, DirectoryInfo DestinationDirectory, string DestinationFilename, IEnumerable <string> Cultures, bool bUseCultureDirectory)
    {
        foreach (var Culture in Cultures)
        {
            var CultureDirectory = (bUseCultureDirectory) ? new DirectoryInfo(Path.Combine(DestinationDirectory.FullName, Culture)) : DestinationDirectory;
            if (!CultureDirectory.Exists)
            {
                CultureDirectory.Create();
            }

            using (var MemoryStream = new MemoryStream())
            {
                var ExportTranslationState = OneSkyFile.ExportTranslation(Culture, MemoryStream).Result;
                if (ExportTranslationState == UploadedFile.ExportTranslationState.Success)
                {
                    var ExportFile = new FileInfo(Path.Combine(CultureDirectory.FullName, DestinationFilename));

                    // Write out the updated PO file so that the gather commandlet will import the new data from it
                    {
                        var ExportFileWasReadOnly = false;
                        if (ExportFile.Exists)
                        {
                            // We're going to clobber the existing PO file, so make sure it's writable (it may be read-only if in Perforce)
                            ExportFileWasReadOnly = ExportFile.IsReadOnly;
                            ExportFile.IsReadOnly = false;
                        }

                        MemoryStream.Position = 0;
                        using (Stream FileStream = ExportFile.OpenWrite())
                        {
                            MemoryStream.CopyTo(FileStream);
                            Console.WriteLine("[SUCCESS] Exporting: '{0}' as '{1}' ({2})", OneSkyFile.Filename, ExportFile.FullName, Culture);
                        }

                        if (ExportFileWasReadOnly)
                        {
                            ExportFile.IsReadOnly = true;
                        }
                    }

                    // Also update the back-up copy so we can diff against what we got from OneSky, and what the gather commandlet produced
                    {
                        var ExportFileCopy = new FileInfo(Path.Combine(ExportFile.DirectoryName, String.Format("{0}_FromOneSky{1}", Path.GetFileNameWithoutExtension(ExportFile.Name), ExportFile.Extension)));

                        var ExportFileCopyWasReadOnly = false;
                        if (ExportFileCopy.Exists)
                        {
                            // We're going to clobber the existing PO file, so make sure it's writable (it may be read-only if in Perforce)
                            ExportFileCopyWasReadOnly = ExportFileCopy.IsReadOnly;
                            ExportFileCopy.IsReadOnly = false;
                        }

                        ExportFile.CopyTo(ExportFileCopy.FullName, true);

                        if (ExportFileCopyWasReadOnly)
                        {
                            ExportFileCopy.IsReadOnly = true;
                        }

                        // Add/check out backed up POs from OneSky.
                        if (P4Enabled)
                        {
                            UE4Build.AddBuildProductsToChangelist(OneSkyDownloadedPOChangeList, new List <string>()
                            {
                                ExportFileCopy.FullName
                            });
                        }
                    }
                }
                else if (ExportTranslationState == UploadedFile.ExportTranslationState.NoContent)
                {
                    Console.WriteLine("[WARNING] Exporting: '{0}' ({1}) has no translations!", OneSkyFile.Filename, Culture);
                }
                else
                {
                    Console.WriteLine("[FAILED] Exporting: '{0}' ({1})", OneSkyFile.Filename, Culture);
                }
            }
        }
    }
Exemplo n.º 36
0
 /// <summary>
 /// Returns a <see cref="SqlClientOutputStream" /> of the file data that was uploaded for the specified location info.
 /// </summary>
 /// <param name="file">The <see cref="UploadedFile" /> for which to get a <see cref="SqlClientOutputStream" />.</param>
 /// <returns>A <see cref="SqlClientOutputStream" /> of the file data that was uploaded.</returns>
 public override Stream GetInputStream(UploadedFile file)
 {
     return(new OracleBlobOutputStream(_connectionString, _table, _dataField, file.LocationInfo[WhereCriteriaKey]));
 }
Exemplo n.º 37
0
 public string CreateContent(UploadedFile uploadedFile)
 {
     return(null);
 }
Exemplo n.º 38
0
        private List <string> joinCurrPicsAndPictureAddresses(List <string> pictureAddresses, List <string> currPcs)
        {
            if (!currPcs.IsNullOrEmpty())
            {
                currPcs.Remove(UploadedFile.DefaultBlankPictureLocation());
            }

            if (!pictureAddresses.IsNullOrEmpty())
            {
                pictureAddresses.Remove(UploadedFile.DefaultBlankPictureLocation());
            }

            if (currPcs.IsNullOrEmpty())
            {
                if (pictureAddresses.IsNullOrEmpty())
                {
                }
                else
                {
                    pictureAddresses = pictureAddresses.Concat(currPcs).ToList();
                }
            }
            else
            {
                if (pictureAddresses.IsNullOrEmpty())
                {
                    pictureAddresses = currPcs;
                }
                else
                {
                    //remove currPcs from pictureAddress
                    //remove duplicates from CurrPic
                    int returnNoOfPictures = MenuPath1.MaxNumberOfPicturesInMenu() + 1;
                    currPcs = new HashSet <string>(currPcs).ToList();

                    if (!currPcs.IsNullOrEmpty())
                    {
                        foreach (string currPic in currPcs)
                        {
                            pictureAddresses.Remove(currPic);
                        }
                    }

                    if (pictureAddresses.IsNullOrEmpty())
                    {
                        return(currPcs);
                    }

                    //now currPcs has its own pics
                    //and picture address has its own


                    if (currPcs.Count >= returnNoOfPictures)
                    {
                        return(currPcs.GetRange(0, returnNoOfPictures));
                    }
                    else
                    {
                        int noOfPicsRequried = returnNoOfPictures - currPcs.Count;

                        //if there are more pics in picture address than required....
                        if (pictureAddresses.Count >= noOfPicsRequried)
                        {
                            pictureAddresses = getRandomPictures(pictureAddresses);
                            pictureAddresses = pictureAddresses.GetRange(0, noOfPicsRequried);
                        }

                        pictureAddresses = pictureAddresses.Concat(currPcs).ToList();
                        pictureAddresses = new HashSet <string>(pictureAddresses).ToList();
                    }
                }
            }

            return(pictureAddresses);
        }
Exemplo n.º 39
0
 public override void RemoveOutput(UploadedFile file)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 40
0
    protected void DosyalariSistemeUygunBicimdeYukle()
    {
        try
        {
            //new Aspose.Pdf.License().SetLicense(LicenseHelper.License.LStream);
            UploadedFile file     = ctlFileUpl.UploadedFiles[0];
            EFDal        e        = new EFDal();
            Guid         DosyaAdi = Guid.NewGuid();
            var          usr      = UserManager.GetCurrentUser();
            string       usrName  = usr.Identity.Name;

            int BolgeKodu = e.kal_BolgeKoduDon(usrName);

            string dosyaYolu = Server.MapPath("~/DosyaSistemi/");
            dosyaYolu += BolgeKodu.ToString();
            dosyaYolu += '\\' + DateTime.Now.Year.ToString() + '\\' + DosyaAdi.ToString() + file.GetExtension();

            string DosyaAdiveUzantisiOlmadandosyaYolu = Server.MapPath("~/DosyaSistemi/") + BolgeKodu.ToString() + '\\' +
                                                        DateTime.Now.Year.ToString() + '\\';



            //string targetFolder = dosyaYolu;
            //string targetFileName = Path.Combine(targetFolder, DosyaAdi + file.GetExtension());
            string targetFileName = dosyaYolu;
            file.SaveAs(targetFileName);
            //Şimdi veritabanına kaydı işle..
            EFDal ed      = new EFDal();
            bool  basarim = ed.IstekDokumanlariAdd(IstId, dosyaYolu, ImzaliDokumanTipleriId,
                                                   ed.UserNamedenPersonelUNDon(Context.User.Identity.Name), DateTime.Now, false, txtAciklama.Text.Trim());

            ////Dosya yüklendiği orijinal hali ile sitemde su anda, bu dosyayı pdf e çevirmemiz gerekli şimdi
            //switch (file.GetExtension())
            //{
            //    case ".doc":
            //        PDFCevirici.WordToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
            //        break;
            //    case ".docx":
            //        PDFCevirici.DOCXToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
            //        break;
            //    case ".xls":
            //        PDFCevirici.ExcelToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
            //        break;
            //    case ".xlsx":
            //        PDFCevirici.ExcelToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
            //        break;

            //    case ".pdf":
            //        //Hiçbirşey yapma
            //        break;
            //}

            ////string kapakPDFDosyasi = e.IstIddenKapakPDFninPathiniDon(Convert.ToInt32(Request["IstId"]));
            //string veriSayfalariIcinSonucDosyaAdresi = DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf";

            ////Aspose.Pdf.Document pdfKapak = new Aspose.Pdf.Document(kapakPDFDosyasi);
            //Aspose.Pdf.Document pdfVeri = new Aspose.Pdf.Document(veriSayfalariIcinSonucDosyaAdresi);

            ////pdfKapak.Pages.Add(pdfVeri.Pages);
            ////pdfKapak.Save(kapakPDFDosyasi);

            //lblUplUyari.ForeColor = System.Drawing.Color.LimeGreen;
            ////Şimdi gönderilen sertifika verisi dosyasını veritabanına işlemek için path ve dosyaadi bilgisini oluştur.
            ////string bak = dosyaYolu;
            ////2 nolu dokuman Sertifika verisine karsilik geliyor

            ////Burada gridi yeniden bağlamak gerekiyor

            //File.Delete(DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + file.GetExtension());
            //File.Delete(veriSayfalariIcinSonucDosyaAdresi);//veri sayfalarından oluşan pdf i de sil
            //e.spImzaliDosyalaraEkle(Convert.ToInt32(Request["IstId"]), DosyaAdi + ".pdf", 2, Guid.Empty,
            //   e.UserNamedenUserIdDon(usrName), dosyaYolu, ".pdf");
            ////Şİmdi bu dosya kal. yapan ve müdür tarafından e-imza bekliyor. Bu yızden bunu imzabekleyenler tablosuna ekle
            //int imzaliDosyaId = e.IstIddenSertifikaKapagininImzaliDosyalarIdsiniDon(Convert.ToInt32(Request["IstId"]));
            //e.spImzaBekleyenDokumanlaraEkle(imzaliDosyaId, e.UserNamedenPersonelUNDon(Context.User.Identity.Name), false, true, Convert.ToInt32(Request["IstId"]));
            lblUplUyari.ForeColor = System.Drawing.Color.Green;
            lblUplUyari.Text      = "Dosya başarıyla yüklenmiştir...";
        }
        catch (Exception exc)
        {
            // UploadedFile file = upl.UploadedFiles[0];
            lblUplUyari.ForeColor = System.Drawing.Color.Red;
            lblUplUyari.Text      =
                "Dosya yüklenemedi! Dosya boyutu 10 MB'dan büyük olamaz. Lütfen kontrol ediniz.<br>Hata:" + exc.Message;
        }
    }
Exemplo n.º 41
0
        private bool ParseOrThrow()
        {
            origPreloadedBody = OrigWorker.GetPreloadedEntityBody();
            string contentTypeHeader      = OrigWorker.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);
            string contentLengthHeader    = OrigWorker.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength);
            string transferEncodingHeader = OrigWorker.GetKnownRequestHeader(HttpWorkerRequest.HeaderTransferEncoding);

            if (contentLengthHeader != null)
            {
                origContentLength = Int64.Parse(contentLengthHeader);
            }

            if (Config.Current.DebugDirectory != null)
            {
                string logEntityBodyBaseName = Path.Combine(Config.Current.DebugDirectory.FullName,
                                                            DateTime.Now.Ticks.ToString());
                LogEntityBodyStream      = File.Create(logEntityBodyBaseName + ".body");
                LogEntityBodySizesStream = File.CreateText(logEntityBodyBaseName + ".sizes");
                LogEntityBodySizesStream.WriteLine(contentTypeHeader);
                LogEntityBodySizesStream.WriteLine(contentLengthHeader);
                if (origPreloadedBody != null)
                {
                    LogEntityBodyStream.Write(origPreloadedBody, 0, origPreloadedBody.Length);
                    LogEntityBodySizesStream.WriteLine(origPreloadedBody.Length);
                }
                else
                {
                    LogEntityBodySizesStream.WriteLine(0);
                }
            }

            FieldNameTranslator translator = new FieldNameTranslator();

            if (MultiRequestControlID == null && UploadState != null)
            {
                UploadState.BytesTotal += origContentLength;
            }
            if (log.IsDebugEnabled)
            {
                log.Debug("=" + contentLengthHeader + " -> " + origContentLength);
            }

            boundary = System.Text.Encoding.ASCII.GetBytes("--" + GetAttribute(contentTypeHeader, "boundary"));
            if (log.IsDebugEnabled)
            {
                log.Debug("boundary=" + System.Text.Encoding.ASCII.GetString(boundary));
            }

            string charset = GetAttribute(contentTypeHeader, "charset");

            if (charset != null)
            {
                try
                {
                    System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(charset);
                    ContentEncoding = encoding;
                }
                catch (NotSupportedException)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Ignoring unsupported charset " + charset + ".  Using utf-8.");
                    }
                }
            }
            else
            {
                ContentEncoding = HttpContext.Current.Response.ContentEncoding;
            }
            preloadedEntityBodyStream = new MemoryStream();
            Hashtable storageConfigStreamTable = new Hashtable();
            Stream    postBackIDStream         = null;

            outputStream = preloadedEntityBodyStream;
            readPos      = writePos = parsePos = 0;
            while (CopyUntilBoundary())
            {
                // If we were writing to a file, close it
                if (outputStream == fileStream && outputStream != null)
                {
                    UploadState.Files.Add(controlID, uploadedFile);
                    outputStream.Close();
                }

                // If we were receiving the value generated by the HiddenPostBackID control, set the postback ID.
                if (postBackIDStream != null)
                {
                    postBackIDStream.Seek(0, System.IO.SeekOrigin.Begin);
                    StreamReader sr = new System.IO.StreamReader(postBackIDStream);
                    translator.PostBackID = sr.ReadToEnd();
                    postBackIDStream      = null;
                }

                // parse the headers
                string name = null, fileName = null, contentType = null;
                if (boundary[0] != (byte)'\r')
                {
                    byte[] newBoundary = new byte[boundary.Length + 2];
                    Buffer.BlockCopy(boundary, 0, newBoundary, 2, boundary.Length);
                    newBoundary[0] = (byte)'\r';
                    newBoundary[1] = (byte)'\n';
                    boundary       = newBoundary;
                }
                else
                {
                    GetLine();             // Blank line
                }
                GetLine();                 // boundary line
                string header;
                while (null != (header = GetLine()))
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("header=" + header);
                    }
                    int colonPos = header.IndexOf(':');
                    if (colonPos < 0)
                    {
                        break;
                    }
                    string headerName = header.Substring(0, colonPos);
                    if (String.Compare(headerName, "Content-Disposition", true) == 0)
                    {
                        name     = GetAttribute(header, "name");
                        fileName = GetAttribute(header, "filename");
                    }
                    else if (String.Compare(headerName, "Content-Type", true) == 0)
                    {
                        contentType = header.Substring(colonPos + 1).Trim();
                    }
                }
                if (log.IsDebugEnabled)
                {
                    log.Debug("name = " + name);
                }
                if (log.IsDebugEnabled)
                {
                    log.Debug("fileName = " + fileName);
                }
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("name = " + name);
                }
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("fileName = " + fileName);
                }
                controlID = null;
                if (name == Config.Current.PostBackIDQueryParam && postBackIDStream == null)
                {
                    postBackIDStream = outputStream = new System.IO.MemoryStream();
                    readPos          = parsePos;            // Skip past the boundary and headers
                }
                else if (name != null &&
                         null != (controlID = translator.ConfigFieldNameToControlID(name)))
                {
                    storageConfigStreamTable[controlID] = outputStream = new System.IO.MemoryStream();
                    readPos = parsePos;                     // Skip past the boundary and headers
                }
                else if (name != null &&
                         null != (controlID = translator.FileFieldNameToControlID(name)))
                {
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("name != null && controlID != null");
                    }
                    if (UploadState == null)
                    {
                        UploadState = UploadStateStore.OpenReadWriteOrCreate(translator.FileFieldNameToPostBackID(name));
                        if (transferEncodingHeader != "chunked")
                        {
                            UploadState.Status = UploadStatus.NormalInProgress;
                        }
                        else
                        {
                            UploadState.Status = UploadStatus.ChunkedInProgress;
                        }
                        UploadState.BytesTotal += origContentLength;
                        UploadState.BytesRead  += grandTotalBytesRead;
                    }

                    UploadStorageConfig storageConfig = null;

                    if (UploadState.MultiRequestObject != null)
                    {
                        string secureStorageConfigString = UploadState.MultiRequestObject as string;
                        if (secureStorageConfigString != null)
                        {
                            storageConfig = UploadStorage.CreateUploadStorageConfig();
                            storageConfig.Unprotect(secureStorageConfigString);
                            if (log.IsDebugEnabled)
                            {
                                log.DebugFormat("storageConfig[tempDirectory]={0}", storageConfig["tempDirectory"]);
                            }
                        }
                    }
                    string       configID            = translator.FileIDToConfigID(controlID);
                    MemoryStream storageConfigStream = storageConfigStreamTable[configID] as MemoryStream;
                    if (storageConfigStream != null)
                    {
                        storageConfigStream.Seek(0, System.IO.SeekOrigin.Begin);
                        StreamReader sr = new System.IO.StreamReader(storageConfigStream);
                        string       secureStorageConfigString = sr.ReadToEnd();
                        if (log.IsDebugEnabled)
                        {
                            log.Debug("storageConfigStream = " + secureStorageConfigString);
                        }
                        storageConfig = UploadStorage.CreateUploadStorageConfig();
                        storageConfig.Unprotect(secureStorageConfigString);

                        // Write out a part for the config hidden field
                        if (log.IsDebugEnabled)
                        {
                            log.DebugFormat("Calling WriteReplacementFormField({0}, {1})", configID, secureStorageConfigString);
                        }
                        WriteReplacementFormField(configID, secureStorageConfigString);
                        // Remove the stream from the table, so we don't write the replacement field again.
                        storageConfigStreamTable.Remove(configID);
                    }

                    if (fileName != null)
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.DebugFormat("filename != null");
                        }
                        if (log.IsDebugEnabled)
                        {
                            log.Debug("Calling UploadContext.Current.CreateUploadedFile(" + controlID + "...)");
                        }
                        UploadContext tempUploadContext = new UploadContext();
                        tempUploadContext._ContentLength = origContentLength;
                        uploadedFile
                            = UploadStorage.CreateUploadedFile(tempUploadContext, controlID, fileName, contentType, storageConfig);
                        if (MultiRequestControlID == null)
                        {
                            UploadStorage.DisposeAtEndOfRequest(uploadedFile);
                        }
                        outputStream = fileStream = uploadedFile.CreateStream();
                        UploadState.CurrentFileName = uploadedFile.FileName;
                        readPos = parsePos; // Skip past the boundary and headers

                        // If the client-specified content length is too large, we set the status to
                        // RejectedRequestTooLarge so that progress displays will stop.  We do this after
                        // having created the UploadedFile because that is necessary for the progress display
                        // to find the uploadContext.
                        if (origContentLength > UploadHttpModule.MaxRequestLength)
                        {
                            if (log.IsDebugEnabled)
                            {
                                log.Debug("contentLength > MaxRequestLength");
                            }
                            throw new UploadTooLargeException(UploadHttpModule.MaxRequestLength, origContentLength);
                        }

                        // Write out a replacement part that just contains the filename as the value.
                        WriteReplacementFormField(controlID, fileName);
                    }
                    else
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.DebugFormat("filename == null");
                        }
                        // Since filename==null this must just be a hidden field with a name that
                        // looks like a file field.  It is just an indication that when this request
                        // ends, the associated uploaded files should be disposed.
                        if (MultiRequestControlID == null)
                        {
                            if (log.IsDebugEnabled)
                            {
                                log.DebugFormat("MultiRequestControlID == null");
                            }
                            RegisterFilesForDisposal(controlID);
                        }
                        outputStream = preloadedEntityBodyStream;
                    }
                }
                else
                {
                    outputStream = preloadedEntityBodyStream;
                }
            }
            if (log.IsDebugEnabled)
            {
                log.Debug("Done parsing.");
            }
            outputStream.WriteByte(10);
            outputStream.Close();
            preloadedEntityBody       = preloadedEntityBodyStream.ToArray();
            preloadedEntityBodyStream = null;
            if (grandTotalBytesRead < origContentLength)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 42
0
 public override void AddEntityRecordIntoUpload(UploadedFile uploadFile, FileDoc filedoc, IUserHasUploadsTypeENUM iuserHasUploadsTypeEnum)
 {
     uploadFile.FileDoc   = filedoc;
     uploadFile.FileDocId = filedoc.Id;
 }
Exemplo n.º 43
0
        protected void btnFromPcUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (!filePcUpload.HasFile)
                {
                    AddError("No file is selected!");
                    return;
                }
                using (var db = new UploadDb())
                {
                    var fileName    = Path.GetFileName(filePcUpload.PostedFile.FileName);
                    var extension   = Path.GetExtension(fileName);
                    var sizeInBytes = filePcUpload.PostedFile.ContentLength;
                    var user        = UserManager.GetUser();
                    var isPublic    = txtVisibility.Value == "1";

                    var newName = txtNewName.Text.Trim();
                    if (newName.Length > 0)
                    {
                        fileName = newName;
                    }

                    var newFile = new UploadedFile
                    {
                        Comment        = txtRemoteComment.Text,
                        Extension      = extension,
                        Filename       = fileName,
                        Downloaded     = 0,
                        FileSize       = sizeInBytes,
                        LastDownload   = null,
                        UploadDate     = DateTime.Now.ToUniversalTime(),
                        UserId         = (user != null) ? user.UserID : (int?)null,
                        UploadedFileID = 0,
                        IsPublic       = isPublic
                    };

                    try
                    {
                        db.Files.Add(newFile);
                        db.SaveChanges();

                        var filePath = UploadedFileManager.MapToPhysicalPath(newFile);
                        filePcUpload.PostedFile.SaveAs(filePath);

                        Response.Redirect("file.aspx?id=" + newFile.UploadedFileID);
                    }
                    catch (ThreadAbortException ex)
                    {
                    }
                    catch (Exception ex)
                    {
                        if (newFile.UploadedFileID > 0)
                        {
                            db.Files.Remove(newFile);

                            db.SaveChanges();
                        }

                        AddError("An unhandled error occured.");
                        AddError(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                AddError(ex.Message);
            }
        }
 public UploadedFile Add(UploadedFile uploadedFile)
 {
     return(_context.UploadedFile.Add(uploadedFile));
 }
Exemplo n.º 45
0
 public void Delete(UploadedFile uploadedFile)
 {
     _context.UploadedFile.Remove(uploadedFile);
 }
Exemplo n.º 46
0
 /// <Summary>Read file</Summary>
 public override Stream GetReadStream(UploadedFile file)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 47
0
        /// <summary>
        /// Returns a <see cref="SqlClientInputStream" /> to which to write the file as it is uploaded.
        /// </summary>
        /// <param name="file">The <see cref="UploadedFile" /> for which to get a <see cref="Stream" />.</param>
        /// <returns>A <see cref="SqlClientInputStream" /> to which to write the <see cref="UploadedFile" />.</returns>
        public override Stream GetOutputStream(UploadedFile file)
        {
            string whereCriteria;

            if (_criteriaMethod == CriteriaMethod.Sequence || _criteriaMethod == CriteriaMethod.SequenceTrigger)
            {
                using (IDbConnection cn = CreateConnection(_connectionString))
                    using (IDbCommand cmd = cn.CreateCommand())
                    {
                        StringBuilder insertCommand = new StringBuilder();

                        insertCommand.Append("INSERT INTO ");
                        insertCommand.Append(_table);
                        insertCommand.Append(" (");
                        insertCommand.Append(_dataField);

                        if (_criteriaMethod == CriteriaMethod.Sequence)
                        {
                            insertCommand.Append(",");
                            insertCommand.Append(_keyField);
                        }

                        if (_fileNameField != null)
                        {
                            insertCommand.Append(",");
                            insertCommand.Append(_fileNameField);
                        }

                        insertCommand.Append(") VALUES (NULL");

                        if (_criteriaMethod == CriteriaMethod.Sequence)
                        {
                            insertCommand.Append(",\"");
                            insertCommand.Append(_sequenceName);
                            insertCommand.Append("\".nextval");
                        }

                        if (_fileNameField != null)
                        {
                            insertCommand.Append(",:fileName");

                            IDataParameter fileNameParm = cmd.CreateParameter();

                            fileNameParm.ParameterName = ":fileName";
                            fileNameParm.DbType        = DbType.String;
                            fileNameParm.Value         = file.ClientName;

                            cmd.Parameters.Add(fileNameParm);
                        }

                        IDataParameter returnedIdParm = cmd.CreateParameter();

                        returnedIdParm.ParameterName = ":returnedId";
                        returnedIdParm.DbType        = DbType.Decimal;
                        returnedIdParm.Direction     = ParameterDirection.Output;

                        cmd.Parameters.Add(returnedIdParm);

                        insertCommand.Append(") RETURNING " + _keyField + " INTO :returnedId");

                        cmd.CommandText = insertCommand.ToString();

                        cn.Open();

                        cmd.ExecuteNonQuery();

                        string id = returnedIdParm.Value.ToString();

                        file.LocationInfo[SequenceValueKey] = id;

                        whereCriteria = _keyField + "=" + id;
                    }
            }
            else
            {
                whereCriteria = _criteriaGenerator.GenerateCriteria(file);
            }

            try
            {
                file.LocationInfo[WhereCriteriaKey] = whereCriteria;

                return(new OracleBlobInputStream(_connectionString, _table, _dataField, whereCriteria));
            }
            catch
            {
                RemoveOutput(file);

                file.LocationInfo.Clear();

                throw;
            }
        }
Exemplo n.º 48
0
        private void SavePage()
        {
            if (SecurityContextManager.Current.CurrentURL.Contains("/edit"))
            {
                this.CurrentPage.IsExternal     = cbIsExternal.Checked;
                this.CurrentPage.IsActive       = cbOnline.Checked;
                this.CurrentPage.ChangedBy      = SecurityContextManager.Current.CurrentUser.ID;
                this.CurrentPage.DisplayName    = tbName.Text;
                this.CurrentPage.ExternalURL    = tbExternalURL.Text;
                this.CurrentPage.LastUpdated    = DateTime.Now;
                this.CurrentPage.Name           = tbName.Text.Replace("&", "").Replace("'", "").Replace("?", "").Replace("@", "").Replace("$", "").Replace("#", "");
                this.CurrentPage.SEODescription = tbSeoDescription.Text;
                this.CurrentPage.SEOKeywords    = tbSeoKeywords.Text;
                this.CurrentPage.SEOTitle       = tbSeoTitle.Text;

                if (radAsyncUpload.UploadedFiles.Count > 0)
                {
                    UploadedFile file     = radAsyncUpload.UploadedFiles[0];
                    string       filePath = DateTime.Now.Ticks.ToString() + "_" +
                                            file.FileName;
                    //string filePath = file.FileName;
                    file.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["IMAGEURL"]) + filePath, false);
                    this.CurrentPage.HeaderImagePath = ConfigurationManager.AppSettings["IMAGEURL"] + filePath;
                }

                var content = new PageContentServices().GetByPageID(this.CurrentPage.ID);
                content.PageData    = reContent.Content;
                content.Title       = tbTitle.Text;
                content.SubTitle    = tbSubTitle.Text;
                content.LastUpdated = DateTime.Now;
                content.ChangedBy   = SecurityContextManager.Current.CurrentUser.ID;

                new PageServices().Save(this.CurrentPage);
                new PageContentServices().Save(content);
                Response.Redirect(SecurityContextManager.Current.CurrentURL);
            }
            else
            {
                var p = new IdeaSeedCMS.Core.Domain.Page();
                p.IsActive    = cbOnline.Checked;
                p.AccessLevel = 0;
                p.ChangedBy   = SecurityContextManager.Current.CurrentUser.ID;
                p.DateCreated = DateTime.Now;
                p.DisplayName = tbName.Text;
                p.EnteredBy   = SecurityContextManager.Current.CurrentUser.ID;
                p.ExternalURL = tbExternalURL.Text;
                if (radAsyncUpload.UploadedFiles.Count > 0)
                {
                    UploadedFile file     = radAsyncUpload.UploadedFiles[0];
                    string       filePath = DateTime.Now.Ticks.ToString() + "_" +
                                            file.FileName;
                    //string filePath = file.FileName;
                    file.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["IMAGEURL"]) + filePath, false);
                    p.HeaderImagePath = ConfigurationManager.AppSettings["IMAGEURL"] + filePath;
                }
                p.IsExternal        = cbIsExternal.Checked;
                p.LastUpdated       = DateTime.Now;
                p.MarkedForDeletion = false;
                p.Name       = tbName.Text.Replace("&", "").Replace("'", "").Replace("?", "").Replace("@", "").Replace("$", "").Replace("#", "");
                p.PageTypeID = (int)PageType.PROFILE;
                if (SecurityContextManager.Current.CurrentURL.Contains("/add"))
                {
                    p.ParentID         = ((IdeaSeedCMS.Core.Domain.Page)SecurityContextManager.Current.CurrentPage).ID;
                    p.NavigationTypeID = (int)NavigationType.NONE;
                }
                else
                {
                    p.NavigationTypeID = (int)NavigationType.MAIN;
                }
                p.SEODescription = tbSeoDescription.Text;
                p.SEOKeywords    = tbSeoKeywords.Text;
                p.SEOTitle       = tbSeoTitle.Text;
                p.URLRoute       = "/Default.aspx";
                p.ApplicationID  = Convert.ToInt16(SecurityContextManager.Current.CurrentManagedApplication.ID);
                new PageServices().Save(p);

                var pav = new PageApplicationView();
                pav.ApplicationViewID = Convert.ToInt16(ConfigurationManager.AppSettings["DEFAULTAPPLICATIONVIEWID"]);
                pav.PageID            = p.ID;
                pav.ViewLayout        = ApplicationViewLayout.MAIN;
                pav.SortOrder         = 0;
                new PageViewServices().Save(pav);

                var content = new PageContent();
                content.PageData    = reContent.Content;
                content.Title       = tbTitle.Text;
                content.SubTitle    = tbSubTitle.Text;
                content.LastUpdated = DateTime.Now;
                content.ChangedBy   = SecurityContextManager.Current.CurrentUser.ID;
                content.DateCreated = DateTime.Now;
                content.EnteredBy   = SecurityContextManager.Current.CurrentUser.ID;
                content.PageID      = p.ID;
                new PageContentServices().Save(content);

                Response.Redirect(SecurityContextManager.Current.CurrentURL.Replace("New", p.ID.ToString() + "/edit"));
            }
            //HttpContext.Current.Cache.Remove(ResourceStrings.Cache_PrimaryPublicNavData);
            //Context.Cache.Insert(ResourceStrings.Cache_PrimaryPublicNavData, new PageServices().GetByNavigationTypeID(1, Convert.ToInt16(ConfigurationManager.AppSettings["APPLICATIONID"])));
        }
Exemplo n.º 49
0
        private bool UpdateFile(out bool blZeroBalance, out bool blFileSizeExceeded)
        {
            repoBo = new RepositoryBo();
            bool blResult = false;

            blZeroBalance      = false;
            blFileSizeExceeded = false;

            try
            {
                // Reading File Upload Control
                int intUploadedFileCount = radUploadRepoItem.UploadedFiles.Count;

                if (intUploadedFileCount == 0)
                {
                    // normal update
                    repoVo.Description = txtDescription.Text.Trim();
                    repoVo.HeadingText = txtHeadingText.Text.Trim();
                    repoVo.Link        = String.Empty;
                    blResult           = repoBo.UpdateRepositoryItem(repoVo);
                }
                else
                {
                    // delete existing file and update new file

                    // Put this part under a transaction scope
                    using (TransactionScope scope2 = new TransactionScope())
                    {
                        /* Perform transactional work here */

                        UploadedFile file        = radUploadRepoItem.UploadedFiles[0];
                        float        fileSize    = float.Parse(file.ContentLength.ToString()) / 1048576; // Converting bytes to MB
                        float        oldFileSize = 0.0F;

                        if (fileSize <= 2)
                        {
                            // If file size is less than 2 MB then upload

                            // Get the Repository Path in solution
                            string    strFilePath     = Server.MapPath(strRepositoryPath) + "\\advisor_" + advisorVo.advisorId + "\\" + repoVo.Link;
                            float     fStorageBalance = advisorVo.SubscriptionVo.StorageBalance;
                            AdvisorBo advBo           = new AdvisorBo();

                            // Delete file if it exists
                            if (File.Exists(strFilePath))
                            {
                                // Get the file size of the old file to calculate the balance storagee size
                                FileInfo f     = new FileInfo(strFilePath);
                                long     lSize = f.Length;
                                oldFileSize = (lSize / (float)1048576);
                                float flRemainingBal = fStorageBalance + oldFileSize;

                                if (flRemainingBal >= fileSize)
                                {
                                    File.Delete(strFilePath);
                                }
                                else
                                {
                                    blZeroBalance = true;
                                }
                            }

                            if (!blZeroBalance)
                            {
                                // Add new file
                                strRepositoryPath = Server.MapPath(strRepositoryPath) + "\\advisor_" + advisorVo.advisorId;
                                strGuid           = Guid.NewGuid().ToString();

                                // Reading File Upload Control
                                string newFileName = SaveFileIntoServer(file, strGuid, strRepositoryPath);

                                // Update the DB with new details
                                repoVo.Description = txtDescription.Text.Trim();
                                repoVo.HeadingText = txtHeadingText.Text.Trim();
                                repoVo.Link        = newFileName;

                                blResult = repoBo.UpdateRepositoryItem(repoVo);

                                if (blResult)
                                {
                                    // Once updating the repository is a success, then update the balance storage in advisor subscription table
                                    fStorageBalance = UpdateAdvisorStorageBalance(fileSize, oldFileSize, fStorageBalance);
                                }
                            }
                        }
                        else
                        {
                            blFileSizeExceeded = true;
                        }

                        scope2.Complete();
                    }
                }
            }
            catch (BaseApplicationException Ex)
            {
                throw Ex;
            }
            catch (Exception Ex)
            {
                object[] objects = new object[2];
                objects[0] = repoVo;
                objects[1] = repoBo;
                PageException(objects, Ex, "ManageRepository.ascx:UpdateClick()");
            }
            return(blResult);
        }
    /// <summary>
    /// Handles the Click event of the cmdUpload control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void cmdUpload_Click(object sender, EventArgs e)
    {
        try
        {
            WorkItem workItem             = PageWorkItem;
            bool     bIsActivityInsert    = IsActivityInsert();
            bool     bIsHistoryInsert     = IsHistoryInsert();
            string   strTempAssociationID = string.Empty;

            if (bIsActivityInsert || bIsHistoryInsert)
            {
                if (workItem != null)
                {
                    object oStrTempAssociationID = workItem.State["TempAssociationID"];
                    if (oStrTempAssociationID != null)
                    {
                        strTempAssociationID = oStrTempAssociationID.ToString();
                    }
                }
            }

            string attachPath;
            if (!bIsActivityInsert && !bIsHistoryInsert)
            {
                attachPath = Rules.GetAttachmentPath();
            }
            else
            {
                /* When in Insert mode we keep the attachments in a special location, in case the operation gets cancelled out. */
                attachPath = Rules.GetTempAttachmentPath();
            }

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

            if (!String.IsNullOrEmpty(txtInsertURL.Text))
            {
                if (String.IsNullOrEmpty(txtInsertDesc.Text))
                {
                    return;
                }

                string url    = "URL=";
                Random random = new Random();
                //string urlFile = random.Next(9999) + "-" + txtInsertDesc.Text + "-" + random.Next(9999) + ".URL";
                string urlFile = Guid.NewGuid().ToString() + ".URL";
                string path    = attachPath + "/" + urlFile;
                if (!txtInsertURL.Text.Contains("://"))
                {
                    url += "http:\\\\";
                }
                FileStream   newFile      = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter streamWriter = new StreamWriter(newFile);
                streamWriter.WriteLine("[InternetShortcut]");
                streamWriter.WriteLine(url + txtInsertURL.Text);
                streamWriter.WriteLine("IconIndex=0");
                streamWriter.Close();
                newFile.Close();

                IAttachment attachment = EntityFactory.Create <IAttachment>();
                attachment.Description = txtInsertDesc.Text;
                attachment.FileName    = urlFile;

                if (!bIsActivityInsert && !bIsHistoryInsert)
                {
                    attachment.InsertURLAttachment(path);
                }
                else
                {
                    if (string.IsNullOrEmpty(strTempAssociationID) ||
                        (workItem != null) && (System.Convert.ToString(workItem.State["TempAssociationID"]) == strTempAssociationID))
                    {
                        /* Save to get an ID used for temp purposes. */

                        IUserService userServ = ApplicationContext.Current.Services.Get <IUserService>();
                        strTempAssociationID = userServ.UserId;
                        //attachment.Save();

                        if (workItem != null)
                        {
                            workItem.State["TempAssociationID"] = strTempAssociationID;
                        }
                    }
                    Rules.InsertTempURLAttachment(attachment, EntityContext.EntityType, strTempAssociationID, path);
                }

                txtInsertURL.Text  = String.Empty;
                txtInsertDesc.Text = String.Empty;
                LoadAttachments();
            }
            else if (uplInsertUpload.UploadedFiles.Count > 0)
            {
                UploadedFile file = uplInsertUpload.UploadedFiles[0];
                if (file != null)
                {
                    IAttachment attachment = EntityFactory.Create <IAttachment>();
                    attachment.Description = txtInsertDesc.Text;
                    if (String.IsNullOrEmpty(txtInsertDesc.Text))
                    {
                        attachment.Description = file.GetNameWithoutExtension();
                    }
                    if (!bIsActivityInsert && !bIsHistoryInsert)
                    {
                        attachment.InsertFileAttachment(WriteToFile(file));
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(strTempAssociationID) ||
                            (workItem != null) && (System.Convert.ToString(workItem.State["TempAssociationID"]) == strTempAssociationID))
                        {
                            attachment.FileName = Path.GetFileName(file.FileName); //ie sends up the full path, ff sends up just the filename
                            /* Save to get an ID used for temp purposes. */
                            attachment.Save();
                            IUserService userServ = ApplicationContext.Current.Services.Get <IUserService>();
                            strTempAssociationID = userServ.UserId; // If we use the attachment id it fails when they try to insert an item with 2 attachments
                            if (workItem != null)
                            {
                                workItem.State["TempAssociationID"] = strTempAssociationID;
                            }
                        }
                        Rules.InsertTempFileAttachment(attachment, EntityContext.EntityType, strTempAssociationID, WriteToFile(file));
                    }
                    txtInsertDesc.Text = String.Empty;
                    LoadAttachments();
                }
            }
            else
            {
                DialogService.ShowMessage(GetLocalResourceObject("Error_UnableToLoad_lz").ToString());
                log.Warn(GetLocalResourceObject("Error_UnableToLoad_lz").ToString());
            }
            hideAdds();
        }
        catch (Exception ex)
        {
            log.Error(ex.Message);
            DialogService.ShowMessage(ex.Message);
        }
    }
Exemplo n.º 51
0
 public string CreateContent(UploadedFile uploadedFile)
 {
     return(Path.GetFileName(uploadedFile.FileInfo.Name));
 }
Exemplo n.º 52
0
 public void SaveUploadedFile(UploadedFile UploadFile)
 {
     uploadedNominationRepository.Add(UploadFile);
     uploadedNominationRepository.SaveChages();
 }
Exemplo n.º 53
0
        public virtual ActionResult UploadPostFiles(AttachFileToPostViewModel attachFileToPostViewModel)
        {
            var topic = new Topic();

            try
            {
                User.GetMembershipUser(MembershipService);
                var loggedOnUsersRole = LoggedOnReadOnlyUser.GetRole(RoleService);

                // First this to do is get the post
                var post = _postService.Get(attachFileToPostViewModel.UploadPostId);
                if (post != null)
                {
                    // Now get the topic
                    topic = post.Topic;

                    // Check we get a valid post back and have some file
                    if (attachFileToPostViewModel.Files != null && attachFileToPostViewModel.Files.Any())
                    {
                        // Now get the Group
                        var Group = topic.Group;

                        // Get the permissions for this Group, and check they are allowed to update and
                        // not trying to be a sneaky mofo
                        var permissions = RoleService.GetPermissions(Group, loggedOnUsersRole);
                        if (permissions[ForumConfiguration.Instance.PermissionAttachFiles].IsTicked == false)
                        {
                            TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Errors.NoPermission"),
                                MessageType = GenericMessages.danger
                            };

                            return(Redirect(topic.NiceUrl));
                        }

                        // woot! User has permission and all seems ok
                        // Before we save anything, check the user already has an upload folder and if not create one
                        var uploadFolderPath = HostingEnvironment.MapPath(
                            string.Concat(ForumConfiguration.Instance.UploadFolderPath, LoggedOnReadOnlyUser?.Id));
                        if (!Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Loop through each file and get the file info and save to the users folder and Db
                        foreach (var file in attachFileToPostViewModel.Files)
                        {
                            if (file != null)
                            {
                                // If successful then upload the file
                                var uploadResult = file.UploadFile(uploadFolderPath, LocalizationService);
                                if (!uploadResult.UploadSuccessful)
                                {
                                    TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = uploadResult.ErrorMessage,
                                        MessageType = GenericMessages.danger
                                    };
                                    return(Redirect(topic.NiceUrl));
                                }

                                // Add the filename to the database
                                var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser?.Id);
                                var uploadedFile = new UploadedFile
                                {
                                    Filename       = uploadResult.UploadedFileName,
                                    Post           = post,
                                    MembershipUser = loggedOnUser
                                };
                                _uploadedFileService.Add(uploadedFile);
                            }
                        }

                        //Commit
                        Context.SaveChanges();

                        // Redirect to the topic with a success message
                        TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Post.FilesUploaded"),
                            MessageType = GenericMessages.success
                        };

                        return(Redirect(topic.NiceUrl));
                    }
                    // Else return with error to home page
                    return(topic != null
                        ? Redirect(topic.NiceUrl)
                        : ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
                }
                // Else return with error to home page
                return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
            }
            catch (Exception ex)
            {
                Context.RollBack();
                LoggingService.Error(ex);
                TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message     = LocalizationService.GetResourceString("Errors.GenericMessage"),
                    MessageType = GenericMessages.danger
                };
                return(topic != null
                    ? Redirect(topic.NiceUrl)
                    : ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage")));
            }
        }
Exemplo n.º 54
0
        public async Task <IActionResult> PostItem([FromRoute] string guildid, [FromRoute] string caseid, [FromForm] UploadedFile uploadedFile)
        {
            logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | Incoming request.");
            Identity currentIdentity = await identityManager.GetIdentity(HttpContext);

            User currentUser = await currentIdentity.GetCurrentDiscordUser();

            if (currentUser == null)
            {
                logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | 401 Unauthorized.");
                return(Unauthorized());
            }
            if (!await currentIdentity.HasModRoleOrHigherOnGuild(guildid, this.database) && !config.Value.SiteAdminDiscordUserIds.Contains(currentUser.Id))
            {
                logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | 401 Unauthorized.");
                return(Unauthorized());
            }
            // ========================================================

            if (uploadedFile.File == null)
            {
                logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | 400 No file provided.");
                return(BadRequest());
            }

            ModCase modCase = await database.SelectSpecificModCase(guildid, caseid);

            if (modCase == null)
            {
                logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | 400 Modcase not found.");
                return(BadRequest("Modcase not found."));
            }

            string uniqueFileName = await filesHandler.SaveFile(uploadedFile.File, Path.Combine(config.Value.AbsolutePathToFileUpload, guildid, caseid));

            logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | Sending notification.");
            try {
                await discordAnnouncer.AnnounceFile(uniqueFileName, modCase, currentUser, RestAction.Created);
            }
            catch (Exception e) {
                logger.LogError(e, "Failed to announce file.");
            }

            return(StatusCode(201, new { path = uniqueFileName }));
        }
Exemplo n.º 55
0
 protected abstract void Save(UploadedFile file);
Exemplo n.º 56
0
        public ActionResult Post([FromForm] UploadedFile uploadedFile)
        {
            _marsRoverService.LoadNewDates(uploadedFile);

            return(Ok());
        }
Exemplo n.º 57
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            string name    = "^[a-zA-Z0-9\u4e00-\u9fa5-]{1,}$";//字母数字汉字-
            Regex  rxname  = new Regex(name);
            string phone   = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
            Regex  rxphone = new Regex(phone);

            if (DDMachineFather.SelectedValue == "请选择")
            {
                RadAjaxManager1.Alert("请选择设备类别!");
                return;
            }
            else if (DDMachineSon.SelectedValue == "请选择")
            {
                RadAjaxManager1.Alert("请选择设备子类别!");
                return;
            }
            else if (TextBox1.Text.Trim() == "")
            {
                RadAjaxManager1.Alert("请输入设备名称!");
                return;
            }
            else if (!rxname.IsMatch(TextBox1.Text))
            {
                RadAjaxManager1.Alert("设备名称错误!");
                return;
            }
            else if (TextBox2.Text.Trim() == "")
            {
                RadAjaxManager1.Alert("请输入资产序号!");
                return;
            }
            else if (!rxname.IsMatch(TextBox2.Text))
            {
                RadAjaxManager1.Alert("资产序号格式错误!");
                return;
            }
            else if (TextBox3.Text.Trim() == "")
            {
                RadAjaxManager1.Alert("请输入型号参数!");
                return;
            }
            else if (!rxname.IsMatch(TextBox3.Text))
            {
                RadAjaxManager1.Alert("型号参数格式错误!");
                return;
            }
            else if (RadioButton1.Checked == false && RadioButton2.Checked == false)
            {
                RadAjaxManager1.Alert("请选择是否使用代用机!");
                return;
            }
            //else if (DDUnitName.SelectedValue == "")
            //{
            //    RadAjaxManager1.Alert("请输入报修单位!");
            //    return;
            //}
            else if (TextBox5.Text.Trim() == "")
            {
                RadAjaxManager1.Alert("请输入联系人!");
                return;
            }
            else if (!rxname.IsMatch(TextBox5.Text))
            {
                RadAjaxManager1.Alert("联系人格式错误!");
                return;
            }
            else if (TextBox6.Text.Trim() == "")
            {
                RadAjaxManager1.Alert("请输入联系电话!");
                return;
            }
            else if (!rxname.IsMatch(TextBox6.Text))
            {
                RadAjaxManager1.Alert("联系电话格式错误!");
                return;
            }
            else if (RadioButton3.Checked == false && RadioButton4.Checked == false)
            {
                RadAjaxManager1.Alert("请选择是否需要上门服务!");
                return;
            }
            //else if (RadAsyncUpload1.FileFilters.ToString() == "")
            //{
            //    RadAjaxManager1.Alert("请添加其他附件!");
            //    return;
            //}
            else if (myEditor.Value == "")
            {
                RadAjaxManager1.Alert("请添加故障现象!");
                return;
            }

            if (!rxphone.IsMatch(TextBox6.Text))
            {
                RadAjaxManager1.Alert("手机格式错误!");
                return;
            }
            else
            {
                Declaration_Mol = Declaration_Bll.GetModel(Request.QueryString["ID"].ToString());
                Declaration_Mol.MachineFatherType = DDMachineFather.SelectedValue;
                Declaration_Mol.MachineSonType    = DDMachineSon.SelectedValue;
                Declaration_Mol.MachineName       = TextBox1.Text;
                Declaration_Mol.AssetsID          = TextBox2.Text;
                Declaration_Mol.Model             = TextBox3.Text;

                if (RadioButton1.Checked == true)
                {
                    Declaration_Mol.ReplacementUse = "是";
                }
                if (RadioButton2.Checked == true)
                {
                    Declaration_Mol.ReplacementUse = "否";
                }
                //Declaration_Mol.UnitName = UnitsInfo_Bll.GetModel(UsersInfo_Bll.GetModel(UsersInfo.UserID).UnitID).UnitName;
                Declaration_Mol.RepairTime   = DateTime.Now;
                Declaration_Mol.Contact      = TextBox5.Text;
                Declaration_Mol.ContactPhone = TextBox6.Text;
                if (RadioButton3.Checked == true)
                {
                    Declaration_Mol.ReplacementUse = "是";
                }
                if (RadioButton4.Checked == true)
                {
                    Declaration_Mol.ReplacementUse = "否";
                }
                Declaration_Mol.DeclarationState = "未上报";
                if (RadAsyncUpload1.FileFilters.Count > 0)//判断上传控件内的数量
                {
                    try
                    {
                        UploadedFile file  = RadAsyncUpload1.UploadedFiles[0];
                        string       path  = "~/upload/" + file.FileName;
                        string       paths = Server.MapPath(path);
                        path111 = path;
                        file.SaveAs(paths);
                        //RadAjaxManager1.Alert("添加成功");
                    }
                    catch
                    {
                    }
                }
                string aa = "";

                foreach (ImgModel img in ImgList)
                {
                    aa += img.imgUrl + ";";
                }

                Declaration_Mol.CCC5      = aa;
                Declaration_Mol.OtherPart = path111;
                Declaration_Mol.BreakDown = myEditor.Value;
                Declaration_Bll.Update(Declaration_Mol);
                Response.Write("<script>alert('提交成功!');window.location.href='RepairBX.aspx'</script>");
            }
        }
Exemplo n.º 58
0
 public UploadedFile Add(UploadedFile uploadedFile)
 {
     uploadedFile.DateCreated = DateTime.UtcNow;
     return(_context.UploadedFile.Add(uploadedFile));
 }
Exemplo n.º 59
0
        public ActionResult Apply(RegisterApplicationForm doc)
        {
            if (ModelState.IsValid)
            {
                if (doc.UploadedFiles != null && doc.UploadedFiles[0] != null)
                {
                    if (!Directory.Exists(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name)))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name));
                    }
                    int i = 0;

                    float priceOrder     = 0;
                    int[] specComplexity = new int[doc.spec.Length];
                    foreach (int spec in doc.spec)
                    {
                        specComplexity[i] = (int)DataBase.GetSpecialization(spec).complexity;
                    }
                    i = 0;
                    List <double [, ]> nspecdocs = new List <double [, ]>();
                    foreach (var UploadedFile in doc.UploadedFiles)
                    {
                        bool         img       = false;
                        string       fileName  = System.IO.Path.GetFileName(UploadedFile.FileName);
                        const string chars     = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                        var          random    = new Random();
                        string       nfilename = new string(Enumerable.Repeat(chars, 10).Select(s => s[random.Next(s.Length)]).ToArray());
                        nfilename += "." + fileName.Split('.')[1];


                        UploadedFile.SaveAs(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name) + "\\" + nfilename);

                        //string result = TextParsing.ImgToFile(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name) + "\\" + nfilename, doc.Language);

                        //if (result != null)
                        //{
                        //    img = true;
                        //    string nfilenameTranslate = new string(Enumerable.Repeat(chars, 10).Select(s => s[random.Next(s.Length)]).ToArray())+".txt";
                        //    System.IO.File.WriteAllText(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name) + "\\" + nfilenameTranslate, result);
                        //    doc.translatefileNames[i] = nfilenameTranslate;
                        //}

                        //string filenameToCountSymbols;
                        //if (doc.translatefileNames != null && doc.translatefileNames[i] != null) {  filenameToCountSymbols = doc.translatefileNames[i]; }
                        //else filenameToCountSymbols = nfilename;
                        //int count = countSymbolsIndoc(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name) + "\\" + filenameToCountSymbols, filenameToCountSymbols.Split('.')[1]);
                        //priceOrder += textPrice(specComplexity, count);
                        //nspecdocs.Add( TextParsing.TextSpecialization(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name) + "\\" + filenameToCountSymbols,doc.Language));
                        //i++;
                    }
                }

                return(View(doc));
            }
            else
            {
                if (doc.UploadedFiles != null && doc.UploadedFiles[0] != null)
                {
                    foreach (var UploadedFile in doc.UploadedFiles)
                    {
                        // string fileName = System.IO.Path.GetFileName(UploadedFile.FileName);
                        //if(Directory.Exists(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name))&&System.IO.File.Exists(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name +"\\" +fileName)))
                        // System.IO.File.Delete(Server.MapPath("~/Content/Temporary/" + auth.AuthHelper.GetUser(HttpContext).name +"\\" +fileName));
                    }
                }
                return(View("~/Views/Application/Register.cshtml", doc));
            }
            //else return RedirectToAction("Register", "Application",doc);
        }
Exemplo n.º 60
0
        public void TestUpdateUser()
        {
            // given:

            Service.UserService userService = new UserService();
            userService.UserDao = ContextRegistry.GetContext().GetObject <IUserDao>();

            Document document1    = DocumentCreator.Create();
            Document document2    = DocumentCreator.Create();
            Document document3    = DocumentCreator.Create();
            User     userToUpdate = UserCreator.Create(documents: new [] { document1, document2 });


            UploadedFile uploadedFile = new UploadedFile(new FileInfo("C:\\Temp\\passbild.png"));

            Mock <IDocumentRepository> fileServiceMock = new Mock <IDocumentRepository>();

            fileServiceMock.Setup(s => s.Create(uploadedFile)).Returns(document3);
            userService.DocumentRepository = fileServiceMock.Object;

            // when:
            // UserLoginDto userLoginDto = UserUtil.CreateUserLoginDto("neuernutzer", "anderesPasswort", false);
            UserContactDto userContactDto = new UserContactDto("*****@*****.**",
                                                               "Straße",
                                                               "1",
                                                               "01234",
                                                               "Stadt",
                                                               Country.DE,
                                                               "Unternehmen",
                                                               "http://www.test.url",
                                                               "phone",
                                                               "privat",
                                                               "mobile");
            const string      NEW_USERNAME      = "******";
            const string      NEW_PASSWORDHASH  = "andererPasswortHash";
            UserDataDto       userDataDto       = new UserDataDto("neuerVorname", "neuerNachname", new DateTime(2000, 02, 02), NEW_USERNAME);
            UserPaymentDto    userPaymentDto    = new UserPaymentDto("PayPal", true);
            UserPermissionDto userPermissionDto = UserCreator.CreateUserPermissionDto(new List <string>()
            {
                Roles.Administrator
            }, false);
            EntityChangedDto changeDto = new EntityChangedDto(UserCreator.Create(), new DateTime(2017, 01, 01, 01, 02, 03));

            UserNotificationOptionsDto userNotificationsDto = UserNotificationOptionsDto.AllOff;

            userService.Update(userToUpdate,
                               NEW_PASSWORDHASH,
                               userContactDto,
                               userDataDto,
                               userPaymentDto,
                               userNotificationsDto,
                               userPermissionDto,
                               new List <UploadedFile>()
            {
                uploadedFile
            },
                               new List <Document> {
                document2
            },
                               changeDto);
            userService.UserDao.FlushAndClear();

            User actualUser = UserService.GetById(userToUpdate.Id);

            // then:
            Assert.AreEqual(NEW_USERNAME, actualUser.UserName, "Der Nutzername wurde nicht korrekt übernommen.");
            Assert.AreEqual(NEW_PASSWORDHASH, actualUser.PasswordHash, "Das Passwort wurde nicht korrekt übernommen.");
            DtoAssert.AreEqual(userContactDto, actualUser.GetUserContactDto());
            DtoAssert.AreEqual(userDataDto, actualUser.GetUserDataDto());
            DtoAssert.AreEqual(userNotificationsDto, actualUser.GetNotificationOptions());
            DtoAssert.AreEqual(userPermissionDto, actualUser.GetUserPermissionDto());

            actualUser.Documents.Should().BeEquivalentTo(document1, document3);

            actualUser.ChangedBy.Should().Be(changeDto.ChangedBy);
            actualUser.ChangedAt.Should().Be(changeDto.ChangedAt);
        }