Inheritance: com.Sconit.Web.ModuleBase
Ejemplo n.º 1
0
 public static async Task<string> UploadTestFileAsync()
 {
     // Upload file
     var filePath = TestFilePath;
     var upload = new FileUpload("image/png", Unique.String + ".png");
     return await upload.UploadFileAsync(filePath);
 }
Ejemplo n.º 2
0
    private void Upload(FileUpload fu, string name)
    {
        if (fu.HasFile)
        {
            try
            {
                string filename = System.IO.Path.GetFileName(fu.FileName);
                string fileUpload = Server.MapPath(@"~/Data/Images/") + filename;
                if (System.IO.File.Exists(fileUpload))
                    System.IO.File.Delete(fileUpload);
                fu.SaveAs(fileUpload);
                System.Drawing.Image image1 = System.Drawing.Image.FromFile(fileUpload);
                string fileAceess = Server.MapPath(@"~/Data/Images/" + name + ".jpg");
                if (System.IO.File.Exists(fileAceess))
                    System.IO.File.Delete(fileAceess);
                image1.Save(fileAceess, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (System.IO.File.Exists(fileUpload))
                    System.IO.File.Delete(fileUpload);
            }
            catch (Exception ex)
            {

            }
        }
    }
Ejemplo n.º 3
0
    public string FileUpload(FileUpload fu)
    {
        string backupFile = "";
        if (fu.PostedFile.FileName != "")
        {
            backupFile = fu.PostedFile.FileName.Substring(fu.PostedFile.FileName.LastIndexOf(@"\") + 1);//RT_EDITS_DOC_SET_CONTENTS_20080319.csv

            if (backupFile != "")
            {
                if (backupFile.Substring(0, 2) == "CT")
                {
                    fu.PostedFile.SaveAs(ConfigurationManager.AppSettings["FilePath"] + @"\CT\" + backupFile);//
                }
                else if (backupFile.Substring(0,2)=="RT")
                {
                    fu.PostedFile.SaveAs(ConfigurationManager.AppSettings["FilePath"] + @"\RT\" + backupFile);//
                }
                else// new second RT
                {
                    fu.PostedFile.SaveAs(ConfigurationManager.AppSettings["FilePath"] + @"\NSRT\" + backupFile);//
                }
            }
        }
        else
        {
            backupFile = "";
        }

        return backupFile;
    }
Ejemplo n.º 4
0
    private static HtmlTableCell AddControl(JobControl_Get_Result control)
    {
        HtmlTableCell cell = new HtmlTableCell();
        Control c = new Control();

        switch (control.ControlTypeName)
        {
            case "TextBox":
                c = new TextBox();
                c.ID = control.JobControlID + control.ControlTypeName + control.ControlName;
                break;

            case "CheckBox":
                c = new CheckBox();
                c.ID = control.JobControlID + control.ControlTypeName + control.ControlName;
                break;

            case "ImageUpload":
                c = new FileUpload();
                c.ID = control.JobControlID + control.ControlTypeName + control.ControlName;
                break;
        }

        cell.Controls.Add(c);
        return cell;
    }
Ejemplo n.º 5
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        pnlInput.Style.Add(HtmlTextWriterStyle.Display, "none");
        user u = Users.Get(db, userName);
        try
        {
            ticket newTicket = Tickets.Add(db, Server.HtmlEncode(txtTopic.Text), txtDetails.Text, Int32.Parse(ddlSubUnit.SelectedValue), Int32.Parse(ddlPriority.SelectedValue), u.id, u.sub_unit);

            FileUpload[] fuControls = new FileUpload[] { FileUpload1, FileUpload2, FileUpload3, FileUpload4, FileUpload5 };
            Tickets.Attachments.SaveMultiple(db, fuControls, newTicket.id, 0);
            string body = GetLocalResourceObject("ANew").ToString() +ddlPriority.SelectedItem.Text+" "+ GetLocalResourceObject("TicketWasSubmittedBy").ToString()+" " + u.userName + " (" + u.sub_unit1.unit.unit_name + " - " + u.sub_unit1.sub_unit_name + ") \n\n";
            body += newTicket.title + " [" + Resources.Common.TicketNumber + " #" + newTicket.id + "]\n\n" + Request.Url.OriginalString.Replace("new_ticket.aspx", string.Empty) + "ticket.aspx?ticketid=" + newTicket.id;
           
            pnlOutput.Visible = true;
            if ((bool.Parse(Utils.Settings.Get("email_notification"))))
            {
                try
                {
                    Utils.SendEmail(newTicket.sub_unit.mailto, "New " + ddlPriority.SelectedItem.Text.ToLower() + " " + Resources.Common.Priority.ToLower() + " " + Resources.Common.Ticket.ToLower() + " " + Resources.Common.AssignedTo.ToLower() + " " + newTicket.sub_unit.unit.unit_name + " - " + newTicket.sub_unit.sub_unit_name, body);
                    lblSentTo.Text = "<span class='bold'>" + newTicket.sub_unit.unit.unit_name + " - " + newTicket.sub_unit.sub_unit_name + "</span> " + GetLocalResourceObject("HasBeenNotified").ToString();
                }
                catch (Exception ex)
                {
                    lblSentTo.report(false, "<br />" + Resources.Common.EmailError, ex);
                }
            }
            lblTicketNumber.Text = "<a href='ticket.aspx?ticketID=" + newTicket.id.ToString() + "'>" + newTicket.id.ToString() + "</a>";
        }
        catch (Exception ex)
        {
            lblReport.report(false, Resources.Common.Error, ex);
            pnlError.Visible = true;
        }
    }
Ejemplo n.º 6
0
 private bool CheckDocRequired(FileUpload fuDocrequired, string[] validFileTypes)
 {
     int valid_up = 0;
     if (1 == 1)
     {
         int has_file = 0;
         if (fuDocrequired.HasFile)
         {
             ++has_file;
             string ext = System.IO.Path.GetExtension(fuDocrequired.PostedFile.FileName);
             bool isValidFile = false;
             for (int j = 0; j < validFileTypes.Length; j++)
             {
                 if (ext.ToLower() == "." + validFileTypes[j].ToLower())
                 {
                     isValidFile = true;
                     //lblStatus.Text = "Valid";
                     ++valid_up;
                     break;
                 }
             }
             if (!isValidFile)
             {
                 //lblStatus.Text = "Not Valid";
                 //lblUP_Error.Text = "Invalid File. Please upload a File with extension " + string.Join(",", validFileTypes);
             }
         }
         else { }
     }
     return (valid_up > 0) ? true : false;
 }
Ejemplo n.º 7
0
 public Boolean VerificarEnLoad(FileUpload fup, Label lbl)
 {
     if (VerificarFileUpload(fup))
     {
         //Esto es para la vista previa...
         //try
         //{
         //    fup.PostedFile.SaveAs(Server.MapPath("~/Temp/") + fup.FileName);
         //    lbl.Text = "¡Archivo subido con exito!";
         //    return true;
         //}
         //catch (Exception ex)
         //{
         //    lbl.Text = "¡El archivo no se pudo subir." + ex.Message;
         //    return false;
         //}
         lbl.Text = "¡Archivo subido con exito!";
         return true;
     }
     else
     {
         if (fup.FileName != null)
         {
             lbl.Text = "";
         }
         else
         {
             lbl.Text = "¡TIPO de archivo incorrecto";
         }
         return false;
     }
 }
Ejemplo n.º 8
0
 protected void Upload(FileUpload uploader, Label lblStatus)
 {
     if (uploader.PostedFile.ContentLength != 0) {
         try {
             if (uploader.PostedFile.ContentLength > 100000) {
                 lblStatus.Text = "File is too large for upload";
             } else {
                 using (StreamReader sr = new StreamReader(uploader.PostedFile.InputStream)) {
                     string line = null;
                     string[] split = null;
                     char[] sep = { ',' };
                     var headers = sr.ReadLine().Split(sep).Skip(1);
                     while ((line = sr.ReadLine()) != null) {
                         split = line.Split(sep);
                         AddToTypedTable(split, headers);
                     }
                 }
                 RSMTenon.Data.DataUtilities.UploadToDatabase(Table, TableName, null);
                 lblStatus.Text = String.Format("{0:#,##0} row(s) added to database", Table.Rows.Count);
             }
         } catch (Exception err) {
             lblStatus.Text = err.Message;
         }
     }
 }
Ejemplo n.º 9
0
    private string uploadProof(FileUpload upload)
    {
        string result = "";
        if ((upload.PostedFile != null) && (upload.PostedFile.ContentLength > 0))
        {
            string fn = "GamesResult";
            string ext = System.IO.Path.GetExtension(upload.PostedFile.FileName);
            string fileName = "Games" + "\\" + fn + "_" + DateTime.Now.Day + "_" + DateTime.Now.Month + "_" +
                              DateTime.Now.Year + ext;
            string SaveLocation = Server.MapPath("Attachments") + "\\" + fileName;
            try
            {
                double size = ((double)FileUpload1.PostedFile.ContentLength) / (1024 * 1024);

                if (!Directory.Exists(Server.MapPath("Attachments") + "\\Games"))
                    Directory.CreateDirectory(Server.MapPath("Attachments") + "\\Games");
                FileUpload1.PostedFile.SaveAs(SaveLocation);

                result = SaveLocation;

            }
            catch (Exception)
            {
                //message
            }
        }
        else result = "Empty";

        return result;
    }
Ejemplo n.º 10
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="PosPhotoUpload">控件</param>
 /// <param name="saveFileName">保存的文件名</param>
 /// <param name="imagePath">保存的文件路径</param>
 public string FileSc(FileUpload PosPhotoUpload, string saveFileName, string imagePath)
 {
     string state="";
     if (PosPhotoUpload.HasFile)
     {
         if (PosPhotoUpload.PostedFile.ContentLength / 1024 < 10240)
         {
             string MimeType = PosPhotoUpload.PostedFile.ContentType;
             if (String.Equals(MimeType, "image/gif") || String.Equals(MimeType, "image/pjpeg"))
             {
                 string extFileString = System.IO.Path.GetExtension(PosPhotoUpload.PostedFile.FileName);
                 PosPhotoUpload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(imagePath));
             }
             else
             {
                 state = "上传文件类型不正确";
             }
         }
         else
         {
             state = "上传文件不能大于10M";
         }
     }
     else
     {
         state= "没有上传文件";
     }
     return state;
 }
Ejemplo n.º 11
0
    public int ImageWidth(FileUpload fuName)
    {
        #region Remark
        /*############################ Example ############################
        ใช้หาขนาดความกว้างของรูป จาก FileUpload Control
        clsIO.ImageWidth(FileUploadControl).ToString()
        
        TIP : สามารถเรียกใช้ได้ครั้งละ 1 Function คือ ImageWidth หรือ ImageHeight เท่านั้น เพราะค่าใน FileUpload จะหายไป
        #################################################################*/
        #endregion

        int imgWidth = 0;

        if (fuName.HasFile)
        {
            if (FileTypeChecker(fuName.FileName) == "IMG")
            {
                Stream myStream = fuName.PostedFile.InputStream;
                System.Drawing.Image myImage = System.Drawing.Image.FromStream(myStream);

                if (myImage != null)
                {
                    imgWidth = myImage.Width;
                    myImage.Dispose();
                    myStream.Dispose();
                }
            }
        }

        return imgWidth;
    }
Ejemplo n.º 12
0
 /// <summary>
 /// 图片上传函数
 /// </summary>
 /// <param name="employeeId">员工编号</param>
 /// <param name="photoFile">文件上传控件</param>
 public void OperatePhoto(int employeeId, FileUpload photoFile)
 {
     //如果上传文件为空则不执行此代码。
     if (photoFile == null || photoFile.HasFile == false) return;
      //获取文件的输入流
     Stream imageStream = photoFile.PostedFile.InputStream;
     int imageLength = photoFile.PostedFile.ContentLength;
     string imageType = photoFile.PostedFile.ContentType;
     MemoryStream mStream = new MemoryStream();
     byte[] imageData = new byte[1024];
     int count = 0;
     while (0 < (count = imageStream.Read(imageData, 0, imageData.Length)))
     {
         //将文件流转换为字节,然后写入到数据库中
         mStream.Write(imageData, 0, count);
     }
     string connstr = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
     using (SqlConnection conn = new SqlConnection(connstr))
     {
         conn.Open();
         using (SqlCommand cmd =new SqlCommand("Update Employees Set Photo = @Photo WHERE EmployeeID = @EmployeeID",conn))
         {
             //更新员工照片信息
             cmd.Parameters.AddWithValue("@EmployeeID", employeeId);
             cmd.Parameters.AddWithValue("@photo", photoFile);
             cmd.ExecuteNonQuery();
         }
     }
 }
    public void UpdateDocumentDetails()
    {
        string DocName = default(System.String);
        int DocStatus = default(System.Int32);
        int OppsID = default(System.Int32);
        System.DateTime LastModifyDate = default(System.DateTime);

        //For LastModifyDate
        {
            TextBox LastModifyDateCal = new TextBox();
            LastModifyDateCal = (TextBox)DocumentDW.FindControl("LastModifyDate");
            if ((LastModifyDateCal != null))
            {
                if (!string.IsNullOrEmpty(LastModifyDateCal.Text))
                {
                    LastModifyDate = Convert.ToDateTime(LastModifyDateCal.Text.Trim());
                }
            }

        }
        //For Document Status
        DropDownList DocStatusDDList = new DropDownList();
        DocStatusDDList = (DropDownList)DocumentDW.FindControl("ddlDocStatus");
        if ((DocStatusDDList != null))
        {
            DocStatus = Convert.ToInt32(DocStatusDDList.SelectedValue);

        }
        //For Opportunity
        DropDownList OpportunityDDList = new DropDownList();
        OpportunityDDList = (DropDownList)DocumentDW.FindControl("ddlOpportunity");
        if ((OpportunityDDList != null))
        {
            OppsID = Convert.ToInt32(OpportunityDDList.SelectedValue);

        }
        FileUpload FileUploadControl = new FileUpload();
        FileUploadControl = (FileUpload)DocumentDW.FindControl("Upload");
        if ((FileUploadControl != null))
        {
            //Add GUID
            DocName = System.Guid.NewGuid() + "_" + FileUploadControl.FileName.ToString();
            if (string.IsNullOrEmpty(DocName))
            {
                //User has not uploaded new file so keep the same filename
                DocName = hidDocumentName.Value;
            }
            else
            {
                //Save the actual file in the documents folder
                //FileUploadControl.SaveAs(Server.MapPath(DocName));
                //FileUploadControl.SaveAs(ConfigurationManager.AppSettings["DocumentsUploadLocation"] + DocName);
                FileUploadControl.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["DocumentsUploadLocation"] + DocName));
            }

        }
        //Now Update
        new SandlerRepositories.DocumentsRepository().Update(Convert.ToInt32(hidDocumentID.Value), OppsID, DocName, DocStatus, LastModifyDate,CurrentUser);
    }
 public async Task FileUploadAsyncTest()
 {
     var file = FileHelper.TestFilePath;
     var filename = Unique.String + ".png";
     Console.WriteLine("Generated file name: {0}", filename);
     var handler = new FileUpload("image/png", filename);
     var uploadedFilename = await handler.UploadFileAsync(file);
     Console.WriteLine("Uploaded to file {0}", uploadedFilename);
 }
Ejemplo n.º 15
0
        public void ShouldUploadOneFile()
        {
            var file = new FileUpload("name", "filename", new byte[] { 0xDE });

            var fileNames = client.Post(file, "invoices")
                .On(HttpStatusCode.Created).Unwrap<string[]>();

            Assert.That(fileNames.Single(), Is.EqualTo("name"));
        }
Ejemplo n.º 16
0
 private void GetImage(ref List<byte[]> photolist, FileUpload con)
 {
     HttpPostedFile photo = con.PostedFile;
     int upPhotoLength = photo.ContentLength;
     byte[] PhotoArray = new Byte[upPhotoLength];
     Stream PhotoStream = photo.InputStream;
     PhotoStream.Read(PhotoArray, 0, upPhotoLength);
     photolist.Add(PhotoArray);
 }
    protected void dvDocument_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        string DocName = default(System.String);
        int DocStatus = default(System.Int32);
        System.DateTime LastModifyDate = default(System.DateTime);

        //for file
        FileUpload FileUploadControl = new FileUpload();
        FileUploadControl = (FileUpload)dvDocument.FindControl("Upload");
        if ((FileUploadControl != null))
        {
            //Create GUID and modify Document Name - This will ensure that document will be unique for all users even if they use same name
            DocName = System.Guid.NewGuid() + "_" + FileUploadControl.FileName.ToString();
            //check if we have Document name
            if (!string.IsNullOrEmpty(DocName))
            {
                //Save the actual file in the documents folder- DocumentsUploadLocation
                //FileUploadControl.SaveAs(Server.MapPath(DocName);
                FileUploadControl.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["DocumentsUploadLocation"] + DocName));
            }
            else
            {
                //There is not file to attach so inform the user
                ClientScript.RegisterStartupScript(this.GetType(), "NoDocument", ("<script> alert('Please click on Browse button and select document to attach.'); </script>"));
                e.Cancel = true;
            }

        }
        //For LastModifyDate
        {
            TextBox LastModifyDateCal = new TextBox();
            LastModifyDateCal = (TextBox)dvDocument.FindControl("LastModifyDate");
            if ((LastModifyDateCal != null))
            {
                if (!string.IsNullOrEmpty(LastModifyDateCal.Text))
                {
                    LastModifyDate = Convert.ToDateTime(LastModifyDateCal.Text.Trim());
                }

            }

        }
        //For Document Status
        DropDownList DocStatusDDList = new DropDownList();
        DocStatusDDList = (DropDownList)dvDocument.FindControl("ddlDocStatus");
        if ((DocStatusDDList != null))
        {
            DocStatus = Convert.ToInt32(DocStatusDDList.SelectedValue);

        }
        if (!e.Cancel)
        {
            new SandlerRepositories.DocumentsRepository().Insert(Convert.ToInt32(ddlOpportunity.SelectedValue), Convert.ToInt32(ddlCompany.SelectedValue), DocStatus, DocName, LastModifyDate,CurrentUser);
            lblResult.Text = "Document attached Successfully!";
        }
    }
Ejemplo n.º 18
0
 public async Task GetUploadUrlWithoutFilenameTest()
 {
     var upload = new FileUpload("image/png");
     var fileUrl = await upload.GetUploadUrlAsync(2);
     Assert.IsNotNull(fileUrl);
     Assert.IsFalse(string.IsNullOrWhiteSpace(fileUrl.FileName));
     Console.WriteLine("Filename: {0}", fileUrl.FileName);
     Assert.IsFalse(string.IsNullOrWhiteSpace(fileUrl.Url));
     Console.WriteLine("Upload url: {0}", fileUrl.Url);
 }
Ejemplo n.º 19
0
 public void UploadImage(FileUpload fileupload, string fileName)
 {
     try
     {
         string path = "~/images/products/" + fileName;
         fileupload.SaveAs(Server.MapPath(path));
     }
     catch (Exception)
     {
     }
 }
Ejemplo n.º 20
0
 public async Task GetUploadUrlWithFilenameTest()
 {
     var filename = Unique.String + ".png";
     var upload = new FileUpload("image/png", filename);
     var fileUrl = await upload.GetUploadUrlAsync(2);
     Assert.IsNotNull(fileUrl);
     Assert.IsFalse( string.IsNullOrWhiteSpace(fileUrl.FileName));
     Console.WriteLine("Filename: {0}", fileUrl.FileName);
     Assert.IsTrue(string.Compare(filename, fileUrl.FileName, true) == 0);
     Assert.IsFalse(string.IsNullOrWhiteSpace(fileUrl.Url));
     Console.WriteLine("Upload url: {0}", fileUrl.Url);
 }
Ejemplo n.º 21
0
 /// <summary>
 /// 清除缓存
 /// </summary>
 public void UploadFile_POST()
 {
     string uploadfor = base.Request["for"];
     string id = base.Request["upload.id"];
     DateTime dt = DateTime.Now;
     string dir = string.Format("/{0}s{1}/attachments/{2:yyyyMMdd}/",
         CmsVariables.RESOURCE_PATH,
         base.CurrentSite.SiteId.ToString(), dt);
     string name = String.Format("{0:yyyyMMdd_ss}{1}", dt, String.Empty.RandomLetters(4));
     string file = new FileUpload(dir, name).Upload(false);
     Response.Write("{"+String.Format("url:'{0}'",file)+"}");
 }
Ejemplo n.º 22
0
        //[Authoriz(Authorization.ChnCheck, Authorization.ChnCheckIn,Authorization.ChnDel)]
        public ActionResult Index()
        {
            //new RolePowerBll().tina();
            //new AreasBll().GetAll();
            //new AgentBll().search();
            //new goodsBll().add();
            return View();

            
            ViewBag.abcd = "111";

            FileUpload im = new FileUpload();
            #region 新建数据
            //Image img1 = System.Drawing.Image.FromFile("C:\\l_c0b6624ca85344feaba162befeb9cc9c.jpg");
            //MemoryStream ms1 = new MemoryStream();
            //byte[] imagedata1 = null;
            //img1.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
            //imagedata1 = ms1.GetBuffer();

            //ImageFileBll bll = new ImageFileBll();
            //bll.Add(new ImageFile()
            //{
            //    ImageId = "LEKGJJXHI6",
            //    Creater = "",
            //    CreateTime = DateTime.Now,
            //    Ip = "",
            //    Description = "这是图片",
            //    Ext = ".jpg",
            //    ImageData = imagedata1,
            //    Path = "",
            //    ImageName = "西湖景区",
            //    ImageType = 1
            //});
            #endregion


            #region  public string[] PictureSave(PType ptype,string picname, byte[] picturebyte,bool exites =false)
            //Image img = System.Drawing.Image.FromFile("d:\\x_02de507f04a340a89fa25d334bfb3bce.jpg");
            //MemoryStream ms = new MemoryStream();
            //byte[] imagedata = null;
            //img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            //imagedata = ms.GetBuffer();
            //im.PictureSave(PType.goods, "ddddd.jpg", imagedata);
            #endregion
            
            #region  URL
            //im.PictureSave(PType.goods, new string[] { "http://imgs.fangtuwang.com/img1/upload/201502/007/381/l_472b493cc1f043c68b0e2bcd57b1592f.jpg", "http://imgs.fangtuwang.com/img2/upload/201503/942/606/l_9f23d355f92e4761a449db0422e671e1.jpg" });
            #endregion

            return View();
        }
Ejemplo n.º 23
0
    // کاهنده حجم عکس
    public string ResizeAndSaveImage(FileUpload fu, bool HighQuality)
    {
        string addr = "";
        string extension = "";
        string fileName = "";
        if (fu.HasFile)
        {
            addr = Guid.NewGuid().ToString();
            fileName = Server.HtmlEncode(fu.FileName);
            extension = System.IO.Path.GetExtension(fileName);

            if ((extension.ToUpper() == ".JPG") | (extension.ToUpper() == ".GIF"))
            {

                //**** Resize image section ****
                System.Drawing.Image image_file = System.Drawing.Image.FromStream(fu.PostedFile.InputStream);
                int image_height = image_file.Height;
                int image_width = image_file.Width;
                int max_height = 0;
                int max_width = 0;

                if (HighQuality)
                {
                    max_height = 400;
                    max_width = 250;
                }
                else
                {
                    max_height = 80;
                    max_width = 50;
                }

                image_height = (image_height * max_width) / image_width;
                image_width = max_width;

                if (image_height > max_height)
                {
                    image_width = (image_width * max_height) / image_height;
                    image_height = max_height;
                }

                Bitmap bitmap_file = new Bitmap(image_file, max_width, max_height);
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                bitmap_file.Save(Server.MapPath("~/uploadedfiles") + "/" + addr + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            }
            return "../uploadedfiles/" + addr + ".jpg";

        }
        else { return ""; }
    }
Ejemplo n.º 24
0
    private void UploadRefundDoc(FileUpload f1, string doc_code)
    {
        string file ="";
        if (f1.HasFile)
        {
            bool checkDoc = CheckDocRequired(f1, validFileTypes);
            bool checksize = CheckForSize(f1);
            if (checkDoc == true && checksize == true)
            {
                string imagefile = null;
                imagefile = f1.PostedFile.FileName;
                string ext = System.IO.Path.GetExtension(f1.PostedFile.FileName);
                if (f1.HasFile)
                {
                    string snow = DateTime.Now.ToString("ddMMyyyyHms");
                    f1.SaveAs(Page.MapPath("/resume/" + snow + "." + ext));
                    file = Page.MapPath("/resume/" + snow + "." + ext);


                    CVUploadEx cp = new CVUploadEx();
                    cp.AdditionalInfo = additionaltxt.Text; ;
                    cp.cvFile = Util.BaseSiteUrl + "resume/" + snow + "." + ext;
                    cp.Id = 0;
                    cp.Email = emailtxt.Text;
                    cp.FullName = fullname.Text;
                    cp.PhoneNo = phonetxt.Text;
                    int result = DataService.Provider.SaveCVUploadEx(cp);
                }
                else
                {
                    imagefile = "no_image.jpg";
                }
            }
            else if (checkDoc == false && checksize == true)
            {
                msgBox1.alert("Kindly select an image in .jpg or .png Format, The selected file is invalid!");
                return;
            }
            else if (checkDoc == false && checksize == false)
            {
                msgBox1.alert("Bad Format and Size, Please select a Valid File!");
                return;
            }
            else if (checkDoc == true && checksize == false)
            {
                msgBox1.alert("File Limit Exceeded!");
                return;
            }
            else { return; }
        }
    }
Ejemplo n.º 25
0
 private byte[] ConvertImageToByteArray(FileUpload fuImage)
 {
     byte[] ImageByteArray;
     try
     {
         MemoryStream ms = new MemoryStream(fuImage.FileBytes);
         ImageByteArray = ms.ToArray();
         return ImageByteArray;
     }
     catch (Exception ex)
     {
         return null;
     }
 }
        public async Task GetDownloadUrlAsyncTest()
        {
            // Upload file
            var filePath = FileHelper.TestFilePath;
            var upload = new FileUpload("image/png", Unique.String + ".png");
            var filename = await upload.UploadFileAsync(filePath);

            // Get download url
            var download = new FileDownload(filename);
            var url = await download.GetDownloadUrl();
            Assert.IsFalse(string.IsNullOrWhiteSpace(url));
            Console.WriteLine("Download url: {0}", url);
            
        }
Ejemplo n.º 27
0
 public string Addphoto(FileUpload Photo)
 {
     if ((Photo.FileName) != "")
     {
         string ext = Path.GetExtension(Photo.FileName);
         int index = Photo.FileName.IndexOf('.');
         string filename = Photo.FileName.Substring(0, index) + Session.SessionID + ext;
         string path = Server.MapPath("~/Profile_Photo/" + filename + "");
         Photo.SaveAs(path);
         return filename;
     }
     else
         return null;
 }
Ejemplo n.º 28
0
    public string UploadImage(FileUpload fileupload, string fill)
    {
        try
        {
            string path = "~/images/products/" + DateTime.Now.ToString("yyyyMMddhhmmss") + fill + "." + fileupload.FileName;
            fileupload.SaveAs(Server.MapPath(path));
            return path;
        }
        catch (Exception)
        {

            return "";
        }
    }
    private string GetUpLoadImage(FileUpload ful)
    {
        #region check image
        if (ful.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") < -1)
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Please select upload images";
            return "";
        }
        #endregion

        #region check image size
        System.Drawing.Image img = System.Drawing.Image.FromStream(ful.PostedFile.InputStream);
        int Width = img.Width;
        int Height = img.Height;
        if (Width > 700 || Height > 700 || ful.PostedFile.ContentLength > 1024 * 1024 * 2)
        {
            lblMessage.Visible = true;
            lblMessage.Text = "The file is too large";
            return "";
        }
        #endregion
        
        #region check image type
        var flag = false;
        HttpPostedFile postedFile = ful.PostedFile;
        string fileName = Path.GetFileName(postedFile.FileName);
        string fileExtension = Path.GetExtension(fileName);
        String[] allowedExtensions = { ".bmp", ".jpg", ".gif", ".png" };
        for (int j = 0; j < allowedExtensions.Length; j++)
        {
            if (fileExtension == allowedExtensions[j])
            {
                flag = true;
                break;
            }
        }

        if (!flag)
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Only images(.jpg, .png, .bmp and .gif) can be uploaded";
            return "";
        }
        #endregion
        
        this.ful.PostedFile.SaveAs(Server.MapPath("~/Images/Products/") + fileName);
        return Path.Combine("~/Images/Products/" + fileName);
    }
Ejemplo n.º 30
0
    /// <summary>
    /// 取出客戶端上傳照片
    /// </summary>
    public void UploadImage(FileUpload myFileUpload, string filePath, int maxPx)
    {
        fileName = Guid.NewGuid().ToString(); // 亂數得要圖片的檔名
        imageName = ""; // ex:檔名 1604151001.jpg

        //是否允許上傳
        bool fileAllow = false;

        //設定允許上載的延伸檔名類型
        string[] allowExtensions = { ".jpg", ".gif", ".png" };

        //取得網站根目錄路徑 大圖先丟到delete資料夾
        string path = HttpContext.Current.Request.MapPath("~/pic/delete/");

        //檢查是否有檔案
        if (myFileUpload.HasFile)
        {
            //取得上載檔案副檔名,並轉換成小寫字母
            string fileExtension =
                System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();

            //檢查副檔名是否符合限定類型
            for (int i = 0; i < allowExtensions.Length; i++)
            {
                if (fileExtension == allowExtensions[i])
                {
                    fileExtension = ".jpg";
                    fileAllow = true;
                }

            }
            if (fileAllow)
            {
                try
                {
                    //將 檔名 跟 附檔名存入 資料庫 設為路徑
                    imageName = fileName + fileExtension;
                    //儲存檔案到磁碟
                    myFileUpload.SaveAs(path + fileName + fileExtension); //路徑 + 檔名 + jpg/png
                    //maxPx 宣告一個圖片尺寸的設定值(Max寬度)
                    addImage(myFileUpload, filePath, fileExtension, maxPx);//將大圖縮小後 刪除 大圖  存小圖 //
                }
                catch (Exception)
                {

                }
            }
        }
    }
Ejemplo n.º 31
0
    protected void BtnUserAccountCreate_Click(object sender, EventArgs e)
    {
        string     userID         = txtNewUserID.Text.Trim();
        string     password       = txtNewUserPassword.Text.Trim();
        string     verifyPassword = txtVerifyNewUserPassword.Text.Trim();
        string     email          = txtNewUserEmail.Text.Trim();
        string     firstName      = txtNewUserFirstName.Text.Trim();
        string     lastName       = txtNewUserLastName.Text.Trim();
        FileUpload pic            = (FileUpload)imgNewUserPic;
        int        userIDExists   = 0;

        MySqlConnection connection = new MySqlConnection(connectionString);

        connection.Open();

        MySqlCommand command = connection.CreateCommand();

        command.CommandText = "SELECT COUNT(*) AS COUNT FROM cis470_seniorproject.users WHERE LOWER(UserID) = LOWER('" + userID + "')";
        MySqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            userIDExists = Convert.ToInt32(reader["COUNT"]);
        }
        reader.Close();

        if (userID == "")
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.Yellow;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "Please enter a User ID.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (userID != "" && userIDExists != 0)
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.Yellow;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "User ID is already taken, please select a different User ID.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (password == "")
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.Yellow;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "Please enter a Pasword.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (verifyPassword == "")
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.Yellow;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "Please verify your Password.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (password != verifyPassword)
        {//validates matching password and password verification fields
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.Yellow;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.Yellow;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "Password and Password Verification must be the same.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (firstName == "")
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.Yellow;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "Please enter your First Name.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (lastName == "")
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.Yellow;
            lblError.Text      = "Please enter your Last Name.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (email == "")
        {//standard validation of empty field
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.Yellow;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "Please enter an Email address.";
            lblError.BackColor = System.Drawing.Color.Red;
        }
        else if (userID != "" && password != "" && verifyPassword != "" && email != "" && firstName != "" && lastName != "")
        {//resets validation fields
            txtNewUserID.BackColor             = System.Drawing.Color.White;
            txtNewUserPassword.BackColor       = System.Drawing.Color.White;
            txtVerifyNewUserPassword.BackColor = System.Drawing.Color.White;
            txtNewUserEmail.BackColor          = System.Drawing.Color.White;
            txtNewUserFirstName.BackColor      = System.Drawing.Color.White;
            txtNewUserLastName.BackColor       = System.Drawing.Color.White;
            lblError.Text      = "";
            lblError.BackColor = System.Drawing.Color.White;

            Session["sessionUserID"] = userID;

            try
            {
                MySqlCommand cmd;

                MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
                conn.Open();

                string sqlStmt = "INSERT INTO CIS470_seniorproject.users (UserID, UserPW, UserEmail, UserFirstName, UserLastName, UserStartDt, UserPic) Values('" + userID + "','" + password + "','" + email + "','" + firstName + "','" + lastName + "',NOW(),'" + pic + "');";

                cmd = new MySqlCommand(sqlStmt, conn);
                cmd.ExecuteReader();
                conn.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.Write(ex);
            }

            Response.Redirect("~/frmDashboard.aspx?userID=" + userID);
        }
    }
Ejemplo n.º 32
0
        public ActionResult Edit(CrudCompanyVm model, Address address)
        {
            try
            {
                if (model.SubCategoryId.HasValue && model.SubCategoryId != 0)
                {
                    model.Company.SubCategoryId = model.SubCategoryId.Value;
                }
                else
                {
                    model.Company.SubCategoryId = model.CategoryId;
                }

                address.SetCoordinates(address.LatitudeString, address.LongitudeString);
                model.Company.Address  = address;
                model.Company.Contacts = model.Contacts;

                if (model.Company.Logo == null || model.LogoFile != null)
                {
                    model.Company.Logo = FileUpload.GetBytes(model.LogoFile, "Logo");
                }
                if (model.Company.Cover == null || model.CoverFile != null)
                {
                    model.Company.Cover = FileUpload.GetBytes(model.CoverFile, "Capa");
                }

                ModelState.Remove("Company.Logo");
                ModelState.Remove("Company.Cover");
                if (!ModelState.IsValid)
                {
                    SetBiewBags(model);
                    return(View(model).Error(ModelState));
                }

                var oldCompany = _db.Companies
                                 .Include(c => c.Address)
                                 .Include(c => c.SubCategory)
                                 .Include(c => c.Contacts)
                                 .FirstOrDefault(x => x.CompanyId == model.Company.CompanyId);
                if (oldCompany == null)
                {
                    return(RedirectToAction("Index").Success("Empresa atualizada com sucesso"));
                }

                // Update parent
                _db.Entry(oldCompany).CurrentValues.SetValues(model.Company);
                oldCompany.Address.UpdateAddress(model.Company.Address);
                _db.Entry(oldCompany.Address).State = EntityState.Modified;

                // Delete children
                foreach (var existingContact in oldCompany.Contacts.ToList())
                {
                    if (model.Contacts.All(c => c.ContactId != existingContact.ContactId))
                    {
                        _db.Contacts.Remove(existingContact);
                    }
                }

                // Update and Insert children
                foreach (var childContact in model.Contacts)
                {
                    var existingContact = oldCompany.Contacts
                                          .FirstOrDefault(c => c.ContactId == childContact.ContactId);

                    childContact.CompanyId = model.Company.CompanyId;
                    if (existingContact != null)
                    {
                        // Update child
                        _db.Entry(existingContact).CurrentValues.SetValues(childContact);
                    }
                    else
                    {
                        // Insert child
                        oldCompany.Contacts.Add(childContact);
                        _db.Contacts.Add(childContact);
                    }
                }

                _db.SaveChanges();
                return(RedirectToAction("Index").Success("Empresa atualizada com sucesso"));
            }
            catch (Exception ex)
            {
                SetBiewBags(model);

                return(View(model).Error(ex.Message));
            }
        }
Ejemplo n.º 33
0
    /// <summary>
    /// Save file from upload
    /// </summary>
    /// Return explain:
    /// <param name="message">Message from upload file</param>
    /// <param name="fileName">Uploaded File name</param>
    /// /// <param name="result">Result in boolean</param>
    /// <returns>List of KeyValuePair string and object</returns>
    /// <example>Helper.SaveFileFromUpload(subPath, fulImageUpload, new string[] { ".jpg", ".gif", ".png"});</example>
    /// <get>string message = list.First(kvp => kvp.Key == "message").Value.ToString();</get>
    /// <get>string isSuccess = list.First(kvp => kvp.Key == "result").Value.ToString();</get>
    /// <get>string fileName = result.First(kvp => kvp.Key == "fileName").Value.ToString();</get>
    public static List <KeyValuePair <string, object> > SaveFileFromUpload(string subPath, FileUpload ful, string[] extensions)
    {
        try
        {
            bool exists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(subPath));
            if (!exists)
            {
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(subPath));
            }

            subPath = HttpContext.Current.Server.MapPath(subPath);

            string result = "";

            // Get the name of the file to upload.
            string fileName = ful.FileName;

            string ext = System.IO.Path.GetExtension(fileName).ToLower();
            if (extensions.Contains(ext))
            {
                // Create the path and file name to check for duplicates.
                string pathToCheck = subPath + fileName;

                // Create a temporary file name to use for checking duplicates.
                string tempfileName = "";

                // Check to see if a file already exists with the
                // same name as the file to upload.
                if (System.IO.File.Exists(pathToCheck))
                {
                    int counter = 2;
                    while (System.IO.File.Exists(pathToCheck))
                    {
                        // if a file with this name already exists,
                        // prefix the filename with a number.
                        tempfileName = counter.ToString() + fileName;
                        pathToCheck  = subPath + tempfileName;
                        counter++;
                    }

                    fileName = tempfileName;

                    // Notify the user that the file name was changed.
                    result = "A file with the same name already exists." +
                             "<br />Your file was saved as " + fileName;
                }
                else
                {
                    // Notify the user that the file was saved successfully.
                    result = "Your file was uploaded successfully.";
                }

                // Append the name of the file to upload to the path.
                subPath += fileName;

                // Call the SaveAs method to save the uploaded
                // file to the specified directory.
                ful.SaveAs(subPath);


                var list = new List <KeyValuePair <string, object> >();
                list.Add(new KeyValuePair <string, object>("message", result));
                list.Add(new KeyValuePair <string, object>("fileName", fileName));
                list.Add(new KeyValuePair <string, object>("result", true));
                return(list);
            }
            else
            {
                var list = new List <KeyValuePair <string, object> >();
                list.Add(new KeyValuePair <string, object>("message", "Invalid file extension!"));
                list.Add(new KeyValuePair <string, object>("fileName", null));
                list.Add(new KeyValuePair <string, object>("result", false));
                return(list);
            }
        } catch (Exception ex)
        {
            var list = new List <KeyValuePair <string, object> >();
            list.Add(new KeyValuePair <string, object>("message", ex.Message));
            list.Add(new KeyValuePair <string, object>("fileName", null));
            list.Add(new KeyValuePair <string, object>("result", false));
            return(list);
        }
    }
Ejemplo n.º 34
0
        protected void subir_archivos()
        {
            Int32 idOrdenTrabajo = Convert.ToInt32(hdId.Value);

            Int32 idDocumento = Convert.ToInt32(dl_lista_titulos.SelectedValue);

            //divido la fecha en año mes dia.
            string x    = DateTime.Now.ToString("yyyyMMddHHmmss");
            string anio = x.Substring(0, 4);
            string mes  = x.Substring(4, 2);
            string dia  = x.Substring(6, 2);

            //obtengo todos los nombres de los meses del año en español.
            String[] Meses = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

            //valido que el formato de los dias y meses sean equivalentes a los nombres de las carpetas de destino.
            string numero_mes = CambiarMes(mes);
            string CarpetaMes = numero_mes + "." + Meses[Convert.ToInt32(mes) - 1].ToString();
            string nuevo_dia  = CambiarDia(dia);

            //armo los strings con las rutas dependiendo de la consulta.
            string destino = "";

            destino = "/" + anio + "/" + CarpetaMes + "/" + nuevo_dia;

            string sPath = String.Format("{0}/{1}/{2}", "docs", IdOrdenTrabajo.ToString().Trim(), dl_lista_titulos.SelectedValue.Trim());

            if (!System.IO.Directory.Exists(@sPath))
            {
                sPath = String.Format("{0}/{1}", "docs", dl_lista_titulos.SelectedValue.Trim());
            }
            if (!System.IO.Directory.Exists(@sPath))
            {
                sPath = "docs";
            }


            //string sPath = String.Format("{0}/{1}/{2}", "docs", IdOrdenTrabajo,IdOrdenTrabajo);
            //if (!System.IO.Directory.Exists(@sPath)) sPath = String.Format("{0}/{1}", "docs",idOrdenTrabajo);
            //if (!System.IO.Directory.Exists(@sPath)) sPath = "docs";
            FileUpload fu_documento = fu_archivo;

            if (fu_documento.PostedFile != null && fu_documento.PostedFile.ContentLength > 0)
            {
                FileInfo fi_documento = new FileInfo(fu_documento.FileName);
                if (fi_documento != null)
                {
                    if (fi_documento.Extension.ToLower() == ".png" || fi_documento.Extension.ToLower() == ".jpg" ||
                        fi_documento.Extension.ToLower() == ".gif" || fi_documento.Extension.ToLower() == ".pdf" ||
                        fi_documento.Extension.ToLower() == ".doc" || fi_documento.Extension.ToLower() == ".docx" ||
                        fi_documento.Extension.ToLower() == ".xls" || fi_documento.Extension.ToLower() == ".xlsx" ||
                        fi_documento.Extension.ToLower() == ".tiff")
                    {
                        if (fu_documento.PostedFile.ContentLength <= 10195407)
                        {
                            string sDoc  = idOrdenTrabajo.ToString() + "_" + idDocumento.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + fi_documento.Extension;
                            string sSave = Server.MapPath(@sPath) + destino + "\\" + sDoc;
                            //string sSave = Server.MapPath(@"docs") + "\\" + sDoc;
                            try
                            {
                                fu_documento.PostedFile.SaveAs(sSave);
                                //sSave = "docs/" + sDoc;
                                sSave = sPath + destino + "/" + sDoc;
                                new ChecklistOrdenTrabajoBC().AddChecklistOrdenTrabajo(new ChecklistOrdenTrabajo
                                {
                                    IdChecklist    = Convert.ToInt16(dl_lista_titulos.SelectedValue),
                                    CuentaUsuario  = Session["usrname"].ToString().Trim(),
                                    Url            = sSave,
                                    Observacion    = txt_comentarios.Text.Trim(),
                                    IdOrdenTrabajo = Convert.ToInt32(hdId.Value)
                                });


                                ;
                            }
                            catch (Exception ex)
                            {
                                FuncionGlobal.alerta_updatepanel(ex.Message, Page, UpdatePanel1);
                                return;
                            }
                        }
                    }
                }
            }
            //Page.RegisterClientScriptBlock("ShowAlert", "<script language=javascript>alert('Archivos subidos con éxito');</script>");
            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.UpdatePanel1.GetType(), "ShowAlert", "<script type=\"text/javascript\">alert('Archivos subidos con éxito');</script>", false);
        }
        public FileUploadSteps()
        {
            var driver = ScenarioContext.Current.Get <IWebDriver>("currentDriver");

            _fileUpload = new FileUpload(driver);
        }
Ejemplo n.º 36
0
        public ActionResult FileSwitchInit()
        {
            try
            {
                FileUpload fileUpload = new FileUpload();
                using (var fileContext = new FileContext())
                {
                    var fileIds = fileContext.FileDescription.Select(p => p.ID);

                    fileIds.ToList().ForEach(id =>
                    {
                        var fd = fileContext.FileDescription.Single(p => p.ID == id);

                        // step 1 delete data which link id is Guid.Empty
                        if (fd.LinkID == Guid.Empty)
                        {
                            fileContext.Entry(fd).State = EntityState.Deleted;

                            fileContext.SaveChanges();
                        }
                        else
                        {
                            // step 2 switch file store mode

                            if (fd.FileData != null && fd.FileData.Any()) //fd.FileStorageID == Guid.Empty &&
                            {
                                string hashCode = MD5HashCode(fd.FileData);
                                var fileStorage = fileContext.FileStorage.FirstOrDefault(f => f.MD5 == hashCode);

                                if (fileStorage == null)
                                {
                                    fileStorage = new FileStorage
                                    {
                                        ID        = Guid.NewGuid(),
                                        FileData  = fd.FileData,
                                        StoreType = "1",
                                        FileUrl   = "",
                                        MD5       = hashCode
                                    };

                                    fileContext.FileStorage.Add(fileStorage);

                                    fileContext.SaveChanges();
                                }

                                fd.FileStorageID = fileStorage.ID;

                                // 清除filedata
                                fd.FileData = new byte[0];

                                fileContext.FileDescription.Attach(fd);
                                var fileDescriptionEntry   = fileContext.Entry(fd);
                                fileDescriptionEntry.State = EntityState.Modified;

                                fileContext.SaveChanges();
                            }
                        }
                    });
                }
                return(Json(new
                {
                    Success = true,
                    Message = "成功"
                }));
            }
            catch (Exception ex)
            {
                return(Json(new
                {
                    Success = false,
                    Message = ex.Message
                }));
            }
        }
Ejemplo n.º 37
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (BP.WF.Dev2Interface.Flow_IsCanStartThisFlow(this.FK_Flow, WebUser.No) == false)
            {
            }

            Flow fl = new Flow(this.FK_Flow);

            this.Page.Title = fl.Name;
            MapAttrs attrs = new MapAttrs(this.FK_MapData);

            if (fl.BatchStartFields.Length == 0)
            {
                this.Pub1.AddFieldSet("流程属性设置错误");
                this.Pub1.Add("您需要在流程属性里设置批量发起需要填写的字段。");
                this.Pub1.AddFieldSetEnd();
            }

            MapExts mes = new MapExts(this.FK_MapData);

            BP.WF.Node nd = new BP.WF.Node(int.Parse(this.FK_Flow + "01"));
            Work       wk = nd.HisWork;

            wk.ResetDefaultVal();

            this.Pub1.AddTable();
            this.Pub1.AddCaptionMsg("批量发起:" + fl.Name);

            #region 输出标题.
            this.Pub1.AddTR();
            this.Pub1.AddTDTitle("序");

            string str1 = "<INPUT id='checkedAll' onclick=\"SelectAllBS(this);\" value='选择' type='checkbox' name='checkedAll' >全部选择";
            this.Pub1.AddTDTitle("align='left'", str1);

            //this.Pub1.AddTDTitle("align='left'", "");

            string[] strs = fl.BatchStartFields.Split(',');
            foreach (string str in strs)
            {
                if (string.IsNullOrEmpty(str))
                {
                    continue;
                }

                foreach (MapAttr attr in attrs)
                {
                    if (str != attr.KeyOfEn)
                    {
                        continue;
                    }
                    this.Pub1.AddTDTitle(attr.Name);
                }
            }
            this.Pub1.AddTREnd();
            #endregion 输出标题.

            #region 输出标题.
            for (int i = 1; i <= this.RowNum; i++)
            {
                this.Pub1.AddTR();
                this.Pub1.AddTDIdx(i);
                CheckBox cbIdx = new CheckBox();
                cbIdx.Checked = false;
                cbIdx.Text    = "发起否?";
                cbIdx.ID      = "CB_IDX_" + i;
                this.Pub1.AddTD(cbIdx);

                foreach (string str in strs)
                {
                    if (string.IsNullOrEmpty(str))
                    {
                        continue;
                    }
                    foreach (MapAttr attr in attrs)
                    {
                        if (str != attr.KeyOfEn)
                        {
                            continue;
                        }

                        TB tb = new TB();
                        tb.ID = "TB_" + attr.KeyOfEn + "_" + i;
                        switch (attr.LGType)
                        {
                        case FieldTypeS.Normal:
                            switch (attr.MyDataType)
                            {
                            case BP.DA.DataType.AppString:
                                if (attr.UIRows == 1)
                                {
                                    tb.Text = attr.DefVal;
                                    tb.Attributes["style"] = "width: " + attr.UIWidth + "px; text-align: left; height: 15px;padding: 0px;margin: 0px;";
                                    if (attr.UIIsEnable)
                                    {
                                        tb.CssClass = "TB";
                                    }
                                    else
                                    {
                                        tb.CssClass = "TBReadonly";
                                    }
                                    this.Pub1.AddTD(tb);
                                }
                                else
                                {
                                    tb.TextMode = TextBoxMode.MultiLine;
                                    tb.Text     = attr.DefVal;

                                    tb.Attributes["style"]     = "width: " + attr.UIWidth + "px; text-align: left;padding: 0px;margin: 0px;";
                                    tb.Attributes["maxlength"] = attr.MaxLen.ToString();
                                    tb.Rows = attr.UIRows;

                                    if (attr.UIIsEnable)
                                    {
                                        tb.CssClass = "TBDoc";
                                    }
                                    else
                                    {
                                        tb.CssClass = "TBReadonly";
                                    }

                                    this.Pub1.AddTD(tb);
                                }
                                break;

                            case BP.DA.DataType.AppDate:
                                tb.ShowType = TBType.Date;
                                tb.Text     = attr.DefVal;

                                if (attr.UIIsEnable)
                                {
                                    tb.Attributes["onfocus"] = "WdatePicker();";
                                }

                                if (attr.UIIsEnable)
                                {
                                    tb.Attributes["class"] = "TB";
                                }
                                else
                                {
                                    tb.Attributes["class"] = "TBReadonly";
                                }

                                tb.Attributes["style"] = "width: " + attr.UIWidth + "px; text-align: left; height: 19px;";
                                this.Pub1.AddTD(tb);
                                break;

                            case BP.DA.DataType.AppDateTime:
                                tb.ShowType = TBType.DateTime;
                                tb.Text     = attr.DefVal;     // en.GetValStrByKey(attr.KeyOfEn);

                                if (attr.UIIsEnable)
                                {
                                    tb.Attributes["class"] = "TBcalendar";
                                }
                                else
                                {
                                    tb.Attributes["class"] = "TBReadonly";
                                }

                                if (attr.UIIsEnable)
                                {
                                    tb.Attributes["onfocus"] = "WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'});";
                                }
                                tb.Attributes["style"] = "width: " + attr.UIWidth + "px; text-align: left; height: 19px;";
                                this.Pub1.AddTD(tb);
                                break;

                            case BP.DA.DataType.AppBoolean:
                                CheckBox cb = new CheckBox();
                                //cb.Width = 350;
                                cb.Text    = attr.Name;
                                cb.ID      = "CB_" + attr.KeyOfEn + "_" + i;
                                cb.Checked = attr.DefValOfBool;
                                cb.Enabled = attr.UIIsEnable;
                                cb.Checked = attr.DefValOfBool;

                                if (cb.Enabled == false)
                                {
                                    cb.Enabled = false;
                                }
                                else
                                {
                                    //add by dgq 2013-4-9,添加内容修改后的事件
                                    // cb.Attributes["onmousedown"] = "Change('" + attr.FK_MapData + "')";
                                    cb.Enabled = true;
                                }
                                this.Pub1.AddTD(cb);
                                break;

                            case BP.DA.DataType.AppDouble:
                            case BP.DA.DataType.AppFloat:
                                tb.Attributes["style"] = "width: " + attr.GetValStrByKey("UIWidth") + "px; text-align: right; height: 19px;word-break: keep-all;";
                                tb.Text = attr.DefVal;

                                if (attr.UIIsEnable)
                                {
                                    //增加验证
                                    tb.Attributes.Add("onkeyup", @"Change('" + attr.FK_MapData + "');");
                                    tb.Attributes.Add("onblur", @"value=value.replace(/[^-?\d+\.*\d*$]/g,'');TB_ClickNum(this,0);");
                                    tb.Attributes.Add("onClick", "TB_ClickNum(this)");
                                    tb.Attributes["OnKeyPress"] += @"javascript:return  VirtyNum(this,'float');";
                                    tb.Attributes["class"]       = "TBNum";
                                }
                                else
                                {
                                    tb.Attributes["class"] = "TBReadonly";
                                }

                                this.Pub1.AddTD(tb);
                                break;

                            case BP.DA.DataType.AppInt:
                                tb.Attributes["style"] = "width: " + attr.GetValStrByKey("UIWidth") + "px; text-align: right; height: 19px;word-break: keep-all;";
                                tb.Text = attr.DefVal;

                                if (attr.UIIsEnable)
                                {
                                    //增加验证
                                    tb.Attributes.Add("onkeyup", @"Change('" + attr.FK_MapData + "');");
                                    tb.Attributes.Add("onblur", @"value=value.replace(/[^-?\d]/g,'');TB_ClickNum(this,0);");
                                    tb.Attributes.Add("onClick", "TB_ClickNum(this)");
                                    tb.Attributes["OnKeyPress"] += @"javascript:return  VirtyNum(this,'int');";
                                    tb.Attributes["class"]       = "TBNum";
                                }
                                else
                                {
                                    tb.Attributes["class"] = "TBReadonly";
                                }

                                this.Pub1.AddTD(tb);
                                break;

                            case BP.DA.DataType.AppMoney:
                                if (attr.UIIsEnable)
                                {
                                    //增加验证
                                    tb.Attributes.Add("onkeyup", @"Change('" + attr.FK_MapData + "');");
                                    tb.Attributes.Add("onblur", @"value=value.replace(/[^-?\d+\.*\d*$]/g,'');TB_ClickNum(this,'0.00');");
                                    tb.Attributes.Add("onClick", "TB_ClickNum(this)");
                                    tb.Attributes["OnKeyPress"] += @"javascript:return  VirtyNum(this,'float');";
                                    tb.Attributes["class"]       = "TBNum";
                                }
                                else
                                {
                                    tb.Attributes["class"] = "TBReadonly";
                                }
                                //  tb.ShowType = TBType.Moneny;
                                tb.Text = attr.DefVal;

                                tb.Attributes["style"] = "width: " + attr.GetValStrByKey("UIWidth") + "px; text-align: right; height: 19px;";
                                this.Pub1.AddTD(tb);
                                break;

                            case BP.DA.DataType.AppRate:
                                if (attr.UIIsEnable)
                                {
                                    tb.Attributes["class"] = "TBNum";
                                }
                                else
                                {
                                    tb.Attributes["class"] = "TBReadonly";
                                }
                                tb.ShowType            = TBType.Moneny;
                                tb.Text                = attr.DefVal;
                                tb.Attributes["style"] = "width: " + attr.GetValStrByKey("UIWidth") + "px; text-align: right; height: 19px;";
                                this.Pub1.AddTD(tb);
                                break;

                            default:
                                break;
                            }
                            break;

                        case FieldTypeS.Enum:
                            if (attr.UIContralType == UIContralType.DDL)
                            {
                                DDL ddle = new DDL();
                                ddle.ID = "DDL_" + attr.KeyOfEn + "_" + i;
                                ddle.BindSysEnum(attr.UIBindKey);
                                ddle.SetSelectItem(attr.DefVal);
                                ddle.Enabled = attr.UIIsEnable;
                                ddle.Attributes["tabindex"] = attr.Idx.ToString();
                                if (attr.UIIsEnable)
                                {
                                    //add by dgq 2013-4-9,添加内容修改后的事件
                                    //   ddle.Attributes["onchange"] = "Change('" + attr.FK_MapData + "')";
                                }
                                //    ddle.Enabled = false;
                                this.Pub1.AddTD(ddle);
                            }
                            else
                            {
                            }
                            break;

                        case FieldTypeS.FK:
                            DDL ddl1 = new DDL();
                            ddl1.ID = "DDL_" + attr.KeyOfEn + "_" + i;
                            ddl1.Attributes["tabindex"] = attr.Idx.ToString();
                            if (ddl1.Enabled)
                            {
                                EntitiesNoName ens = attr.HisEntitiesNoName;
                                ens.RetrieveAll();
                                ddl1.BindEntities(ens);
                                ddl1.SetSelectItem(attr.DefVal);
                                //add by dgq 2013-4-9,添加内容修改后的事件
                                //  ddl1.Attributes["onchange"] = "Change('" + attr.FK_MapData + "')";
                            }
                            else
                            {
                                ddl1.Attributes["style"] = "width: " + attr.UIWidth + "px;height: 19px;";
                                if (ddl1.Enabled == true)
                                {
                                    ddl1.Enabled = false;
                                }
                                ddl1.Attributes["Width"] = attr.UIWidth.ToString();
                                ddl1.Items.Add(new ListItem(attr.DefVal, attr.DefVal));
                            }
                            ddl1.Enabled = attr.UIIsEnable;
                            this.Pub1.AddTD(ddl1);
                            break;

                        default:
                            break;
                        }
                    }
                }
                this.Pub1.AddTREnd();
            }
            #endregion 输出标题.

            this.Pub1.AddTableEnd();

            #region 处理扩展属性.
            if (mes.Count != 0)
            {
                this.Page.RegisterClientScriptBlock("s81",
                                                    "<script language='JavaScript' src='/WF/Scripts/jquery-1.4.1.min.js' ></script>");
                this.Page.RegisterClientScriptBlock("b81",
                                                    "<script language='JavaScript' src='/WF/CCForm/MapExt.js' defer='defer' type='text/javascript' ></script>");
                this.Pub1.Add("<div id='divinfo' style='width: 155px; position: absolute; color: Lime; display: none;cursor: pointer;align:left'></div>");
                this.Page.RegisterClientScriptBlock("dCd",
                                                    "<script language='JavaScript' src='/DataUser/JSLibData/" + this.FK_MapData + ".js' ></script>");

                for (int i = 1; i <= this.RowNum; i++)
                {
                    foreach (MapExt me in mes)
                    {
                        switch (me.ExtType)
                        {
                        case MapExtXmlList.DDLFullCtrl:     // 自动填充.
                            DDL ddlOper = this.Pub1.GetDDLByID("DDL_" + me.AttrOfOper + "_" + i);
                            if (ddlOper == null)
                            {
                                continue;
                            }
                            ddlOper.Attributes["onchange"] = "DDLFullCtrl(this.value,\'" + ddlOper.ClientID + "\', \'" + me.MyPK + "\')";
                            break;

                        case MapExtXmlList.ActiveDDL:
                            DDL       ddlPerant = this.Pub1.GetDDLByID("DDL_" + me.AttrOfOper + "_" + i);
                            string    val, valC;
                            DataTable dt;
                            if (ddlPerant == null)
                            {
                                continue;
                            }
#warning 此处需要优化
                            string ddlC = "ContentPlaceHolder1_BatchStart1_DDL_" + me.AttrsOfActive + "_" + i;
                            //  ddlPerant.Attributes["onchange"] = " isChange=true; DDLAnsc(this.value, \'" + ddlC + "\', \'" + me.MyPK + "\')";
                            ddlPerant.Attributes["onchange"] = "DDLAnsc(this.value, \'" + ddlC + "\', \'" + me.MyPK + "\')";

                            DDL ddlChild = this.Pub1.GetDDLByID("DDL_" + me.AttrsOfActive + "_" + i);
                            val = ddlPerant.SelectedItemStringVal;
                            if (ddlChild.Items.Count == 0)
                            {
                                valC = wk.GetValStrByKey(me.AttrsOfActive);
                            }
                            else
                            {
                                valC = ddlChild.SelectedItemStringVal;
                            }

                            string mysql = me.Doc.Replace("@Key", val);
                            if (mysql.Contains("@") && i >= 100)
                            {
                                mysql = BP.WF.Glo.DealExp(mysql, wk, null);
                            }
                            else
                            {
                                continue;
                            }

                            dt = DBAccess.RunSQLReturnTable(mysql);

                            ddlChild.Bind(dt, "No", "Name");
                            if (ddlChild.SetSelectItem(valC) == false)
                            {
                                ddlChild.Items.Insert(0, new ListItem("请选择" + valC, valC));
                                ddlChild.SelectedIndex = 0;
                            }
                            //  ddlChild.Attributes["onchange"] = " isChange=true;";

                            break;

                        case MapExtXmlList.AutoFullDLL:     //自动填充下拉框的范围.
                            DDL ddlFull = this.Pub1.GetDDLByID("DDL_" + me.AttrOfOper + "_" + i);
                            if (ddlFull == null)
                            {
                                continue;
                            }

                            string valOld = wk.GetValStrByKey(me.AttrOfOper);
                            //string valOld =ddlFull.SelectedItemStringVal;

                            string fullSQL = me.Doc.Replace("@WebUser.No", WebUser.No);
                            fullSQL = fullSQL.Replace("@WebUser.Name", WebUser.Name);
                            fullSQL = fullSQL.Replace("@WebUser.FK_Dept", WebUser.FK_Dept);
                            fullSQL = fullSQL.Replace("@WebUser.FK_DeptName", WebUser.FK_DeptName);
                            fullSQL = fullSQL.Replace("@Key", this.Request.QueryString["Key"]);

                            if (fullSQL.Contains("@"))
                            {
                                Attrs attrsFull = wk.EnMap.Attrs;
                                foreach (Attr attr in attrsFull)
                                {
                                    if (fullSQL.Contains("@") == false)
                                    {
                                        break;
                                    }
                                    fullSQL = fullSQL.Replace("@" + attr.Key, wk.GetValStrByKey(attr.Key));
                                }
                            }

                            //if (fullSQL.Contains("@"))
                            //{
                            //    /*从主表中取数据*/
                            //    Attrs attrsFull = this.MainEn.EnMap.Attrs;
                            //    foreach (Attr attr in attrsFull)
                            //    {
                            //        if (fullSQL.Contains("@") == false)
                            //            break;

                            //        if (fullSQL.Contains("@" + attr.Key) == false)
                            //            continue;

                            //        fullSQL = fullSQL.Replace("@" + attr.Key, this.MainEn.GetValStrByKey(attr.Key));
                            //    }
                            //}

                            ddlFull.Items.Clear();
                            ddlFull.Bind(DBAccess.RunSQLReturnTable(fullSQL), "No", "Name");
                            if (ddlFull.SetSelectItem(valOld) == false)
                            {
                                ddlFull.Items.Insert(0, new ListItem("请选择" + valOld, valOld));
                                ddlFull.SelectedIndex = 0;
                            }
                            // ddlFull.Attributes["onchange"] = " isChange=true;";
                            break;

                        case MapExtXmlList.TBFullCtrl:     // 自动填充.
                            TextBox tbAuto = this.Pub1.GetTextBoxByID("TB_" + me.AttrOfOper + "_" + i);
                            if (tbAuto == null)
                            {
                                continue;
                            }
                            // tbAuto.Attributes["onkeyup"] = " isChange=true; DoAnscToFillDiv(this,this.value,\'" + tbAuto.ClientID + "\', \'" + me.MyPK + "\');";
                            tbAuto.Attributes["onkeyup"] = " DoAnscToFillDiv(this,this.value,\'" + tbAuto.ClientID + "\', \'" + me.MyPK + "\');";

                            tbAuto.Attributes["AUTOCOMPLETE"] = "OFF";
                            if (me.Tag != "")
                            {
                                /* 处理下拉框的选择范围的问题 */
                                string[] strsTmp = me.Tag.Split('$');
                                foreach (string str in strsTmp)
                                {
                                    string[] myCtl = str.Split(':');
                                    string   ctlID = myCtl[0];
                                    DDL      ddlC1 = this.Pub1.GetDDLByID("DDL_" + ctlID + "_" + i);
                                    if (ddlC1 == null)
                                    {
                                        //me.Tag = "";
                                        // me.Update();
                                        continue;
                                    }

                                    string sql = myCtl[1].Replace("~", "'");
                                    sql = sql.Replace("@WebUser.No", WebUser.No);
                                    sql = sql.Replace("@WebUser.Name", WebUser.Name);
                                    sql = sql.Replace("@WebUser.FK_Dept", WebUser.FK_Dept);
                                    sql = sql.Replace("@Key", tbAuto.Text.Trim());
                                    dt  = DBAccess.RunSQLReturnTable(sql);
                                    string valC1 = ddlC1.SelectedItemStringVal;
                                    ddlC1.Items.Clear();
                                    foreach (DataRow dr in dt.Rows)
                                    {
                                        ddlC1.Items.Add(new ListItem(dr[1].ToString(), dr[0].ToString()));
                                    }
                                    ddlC1.SetSelectItem(valC1);
                                }
                            }
                            break;

                        case MapExtXmlList.InputCheck:
                            TextBox tbCheck = this.Pub1.GetTextBoxByID("TB_" + me.AttrOfOper + "_" + i);
                            if (tbCheck != null)
                            {
                                tbCheck.Attributes[me.Tag2] += " rowPK=" + i + "; " + me.Tag1 + "(this);";
                            }
                            break;

                        case MapExtXmlList.PopVal:     //弹出窗.
                            TB tb = this.Pub1.GetTBByID("TB_" + me.AttrOfOper + "_" + i);
                            //  tb.Attributes["ondblclick"] = " isChange=true; ReturnVal(this,'" + me.Doc + "','sd');";
                            tb.Attributes["ondblclick"] = " ReturnVal(this,'" + me.Doc + "','sd');";
                            break;

                        case MapExtXmlList.Link:     // 超链接.
                            //TB tb = this.Pub1.GetTBByID("TB_" + me.AttrOfOper + "_" + mydtl.OID);
                            //tb.Attributes["ondblclick"] = " isChange=true; ReturnVal(this,'" + me.Doc + "','sd');";
                            break;

                        case MapExtXmlList.RegularExpression:    //正则表达式,对数据控件处理
                            TextBox tbExp = this.Pub1.GetTextBoxByID("TB_" + me.AttrOfOper + "_" + i);
                            if (tbExp == null || me.Tag == "onsubmit")
                            {
                                continue;
                            }
                            //验证输入的正则格式
                            string regFilter = me.Doc;
                            if (regFilter.LastIndexOf("/g") < 0 && regFilter.LastIndexOf('/') < 0)
                            {
                                regFilter = "'" + regFilter + "'";
                            }
                            //处理事件
                            tbExp.Attributes.Add("" + me.Tag + "", "return txtTest_Onkeyup(this," + regFilter + ",'" + me.Tag1 + "')");    //[me.Tag] += "this.value=this.value.replace(" + regFilter + ",'')";
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            #endregion 拓展属性

            Button btn = new Button();
            btn.Text          = "执行发起";
            btn.ID            = "Btn_Start";
            btn.Click        += new EventHandler(btn_Send_Click);
            btn.OnClientClick = "return checkType()";
            this.Pub1.Add(btn);

            #region 文件上传.
            this.Pub1.AddFieldSet("通过Excel导入方式发起:<a href='/DataUser/BatchStartFlowTemplete/" + this.FK_Flow + ".xls'><img src='/WF/Img/FileType/xls.gif' />下载Excel模版</a>");
            this.Pub1.Add("文件名:");
            FileUpload fu = new FileUpload();
            fu.ID = "File1";
            this.Pub1.Add(fu);
            btn        = new Button();
            btn.Text   = "导入";
            btn.ID     = "Btn_Imp";
            btn.Click += new EventHandler(btn_Upload_Click);
            this.Pub1.Add(btn);
            this.Pub1.AddFieldSetEnd();
            #endregion 文件上传.
        }
Ejemplo n.º 38
0
        protected void ImportFromExcel(object sender, EventArgs e)
        {
            string        sCon = ClsConnection.Connection();
            SqlConnection con1 = new SqlConnection(sCon);

            //con1.Open();
            //using (SqlCommand cmd = new SqlCommand("usp_del_empDetails", con1))
            //{
            //    cmd.CommandType = CommandType.StoredProcedure;
            //    //  con.Open();
            //    cmd.ExecuteNonQuery();
            //}
            //con1.Close();

            // CHECK IF A FILE HAS BEEN SELECTED.
            if ((FileUpload.HasFile))
            {
                if (!Convert.IsDBNull(FileUpload.PostedFile) &
                    FileUpload.PostedFile.ContentLength > 0)
                {
                    //FIRST, SAVE THE SELECTED FILE IN THE ROOT DIRECTORY.
                    string StrName = Request.Cookies["empcode"].Value.ToString() + "-" + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "-").Replace(":", "-");

                    FileUpload.SaveAs(Server.MapPath(".") + "\\exceluploaded\\" + StrName + FileUpload.FileName);

                    SqlBulkCopy oSqlBulk = null;

                    // SET A CONNECTION WITH THE EXCEL FILE.
                    OleDbConnection myExcelConn = new OleDbConnection
                                                      ("Provider=Microsoft.ACE.OLEDB.12.0; " +
                                                      "Data Source=" + Server.MapPath(".") + "\\exceluploaded\\" + StrName + FileUpload.FileName +
                                                      ";Extended Properties=Excel 12.0;");
                    try
                    {
                        myExcelConn.Open();

                        // GET DATA FROM EXCEL SHEET.
                        OleDbCommand objOleDB =
                            new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);

                        // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
                        OleDbDataReader objBulkReader = null;
                        objBulkReader = objOleDB.ExecuteReader();
                        var str = "";
                        // objBulkReader.Read();
                        //while (objBulkReader.Read())
                        //{
                        //    if (objBulkReader["Name"].ToString() != "")
                        //    {
                        //       str  = objBulkReader["Name"].ToString();
                        //    }
                        //    //if (objBulkReader["EmpName"].ToString() != "")
                        //    //{
                        //    //    txtname.Text = objBulkReader["EmpName"].ToString();
                        //    //}
                        //    //if (objBulkReader["MobileNumber"].ToString() != "")
                        //    //{
                        //    //    txtmobno.Text = objBulkReader["MobileNumber"].ToString();
                        //    //}
                        //    //if (objBulkReader["Address"].ToString() != "")
                        //    //{
                        //    //    txtaddress.Text = objBulkReader["Address"].ToString();
                        //    //}
                        //}

                        // SET THE CONNECTION STRING.
                        //string sCon = "server=49.50.77.98,1433\\DBServer;database=RupeeBoss;uid=rb;password=Kotak@123;";


                        // sCon= "server=10.0.0.220\\DBServer;database=RupeeBoss;uid=rupeeboss;password=boss@rupee;";
                        // sCon = "server=49.50.77.98,1433\\DBServer;database=RupeeBoss;uid=rb;password=Kotak@123;";
                        using (con1 = new SqlConnection(sCon))
                        {
                            con1.Open();
                            oSqlBulk = new SqlBulkCopy(con1);
                            using (SqlCommand cmd = new SqlCommand("usp_del_empDetails", con1))
                            {
                                cmd.CommandType = CommandType.StoredProcedure;
                                //  con.Open();
                                cmd.ExecuteNonQuery();
                            }

                            // FINALLY, LOAD DATA INTO THE DATABASE TABLE.

                            oSqlBulk.DestinationTableName = "EmpDetails"; // TABLE NAME.



                            oSqlBulk.WriteToServer(objBulkReader);

                            //SqlCommand cmd = new SqlCommand();
                            //cmd.CommandType = CommandType.StoredProcedure;
                            //cmd.CommandText = "usp_updt_cityIds";

                            //cmd.EndExecuteNonQuery();



                            using (SqlCommand cmd = new SqlCommand("usp_updt_cityIds_newR", con1))
                            {
                                cmd.CommandType = CommandType.StoredProcedure;
                                SqlParameter sqlparam = new SqlParameter();
                                sqlparam = new SqlParameter("@empCode", Request.Cookies["empcode"].Value.ToString());


                                cmd.Parameters.Add(sqlparam);

                                //  con.Open();
                                cmd.ExecuteNonQuery();
                            }
                        }

                        lblConfirm.Text = "DATA IMPORTED SUCCESSFULLY.";
                        lblConfirm.Attributes.Add("style", "color:green");
                    }
                    catch (Exception ex)
                    {
                        lblConfirm.Text = ex.Message;
                        lblConfirm.Attributes.Add("style", "color:red");
                    }
                    finally
                    {
                        // CLEAR.
                        //oSqlBulk.Close();
                        //oSqlBulk = null;
                        myExcelConn.Close();
                        myExcelConn = null;
                    }
                }
            }
        }
Ejemplo n.º 39
0
    protected void ButtonModify_Click(object sender, EventArgs e)
    {
        string sql_modify_count = "select t.modify_count from onduty t where t.seq='" + Session["seq"] + "' ";

        dsTemp1 = func.get_dataSet_access(sql_modify_count, conn);

        Int32 modify_count_num = Convert.ToInt32(dsTemp1.Tables[0].Rows[0]["modify_count"]);

        modify_count_num++;

        sql = " update onduty                                       " +
              "    set seq = '" + Session["seq"].ToString() + "',                                 " +
              "        calltime = to_date('" + txtEstimateCALLTIME.SelectedDate.Value.ToString("yyyy/MM/dd") + " " + DropDownList1.SelectedValue + ":" + DropDownList2.SelectedValue + "','YYYY/MM/DD HH24:MI'),     " +
              "        endtime = to_date('" + txtEstimateEndTime.SelectedDate.Value.ToString("yyyy/MM/dd") + " " + DropDownList5.SelectedValue + ":" + DropDownList6.SelectedValue + "','YYYY/MM/DD HH24:MI'),     " +
              "        caller = '" + TextBox_CALLER.Text + "',                           " +
              "        extension = '" + TextBox_EXTENTION.Text.Trim().Replace("'", "''") + "',                     " +
              "        engineer = '" + DropDownList_ENGINEER.SelectedValue + "',                       " +
              "        fab = '" + DropDownList1_FAB.SelectedValue + "',                                 " +
              "        system = '" + DropDownList_SYSTEM.SelectedValue + "',                           " +
              "        offday = '" + RadioButtonList_OFFDAY.SelectedValue + "',                           " +
              "        type = '" + DropDownList_TYPE.SelectedValue + "',                               " +
              "        cassette = '" + TextBox_CASSETTE.Text + "',                       " +
              "        lot_id = '" + TextBox_LOT_ID.Text.Trim().Replace("'", "''") + "',                           " +
              "        eq_id = '" + TextBox_EQ_ID.Text.Trim().Replace("'", "''") + "',                             " +
              "        question = '" + TextBox_QUESTION.Text.Trim().Replace("'", "''") + "',                       " +
              "        bywhom = '" + DropDownList_BY_WHOM.SelectedValue + "',                           " +
              "        description = '" + TextBox_DESCRIPTION.Text.Trim().Replace("'", "''") + "',                 " +
              "        close_flag = '" + RadioButtonList_CLOSE_FLAG.SelectedValue + "',                   " +
              "        mobile = '" + TextBox_MOBILE.Text.Trim().Replace("'", "''") + "',                           " +
              "        area = '" + DropDownList_AREA.Text + "',                               " +
              "        starttime = to_date('" + txtEstimateSTARTTIME.SelectedDate.Value.ToString("yyyy/MM/dd") + " " + DropDownList3.SelectedValue + ":" + DropDownList4.SelectedValue + "','YYYY/MM/DD HH24:MI'),     " +
              "        reason = '" + TextBox_REASON.Text.Trim().Replace("'", "''") + "',                           " +
              "        method = '" + TextBox_METHOD.Text.Trim().Replace("'", "''") + "',                           " +
              "        assign_owner = '" + DropDownList_ASSIGN_OWNER.SelectedValue + "',               " +
              "        additional_info = '" + TextBox_ADDITION_INFO.Text.Trim().Replace("'", "''") + "',         " +
              "        ars_flag = '" + RadioButtonList_ARS_FLAG.SelectedValue + "',                       " +
              "        ars_link = '" + TextBox_ARS_LINK.Text.Trim().Replace("'", "''") + "',                       " +
              "        due_time = round((to_date('" + txtEstimateEndTime.SelectedDate.Value.ToString("yyyy/MM/dd") + " " + DropDownList5.SelectedValue + ":" + DropDownList6.SelectedValue + "','YYYY/MM/DD HH24:MI')-" + "to_date('" + txtEstimateSTARTTIME.SelectedDate.Value.ToString("yyyy/MM/dd") + " " + DropDownList3.SelectedValue + ":" + DropDownList4.SelectedValue + "','YYYY/MM/DD HH24:MI') )*24*60,0) ," +
              "        alarm_flag = '" + RadioButtonList_ALARM_FLAG.SelectedValue + "',                   " +
              "        product_impact = '" + DropDownList_PRODUCT_IMPACT.SelectedValue + "',           " +
              "        product_impact_info = '" + TextBox_PRODUCT_IMPACT_INFO.Text.Trim().Replace("'", "''") + "', " +
              "        finaltime = sysdate,                     " +
              "        recharge_flag = '" + RadioButtonList1.SelectedValue + "',             " +
              "        modify_count = '" + modify_count_num + "'                " +
              "  where seq = '" + Session["seq"].ToString() + "'                                  ";

        func.get_sql_execute(sql, conn);
        BindData1();



        #region Add UploadFile


        NetworkDrive oNetDrive1 = new NetworkDrive();
        oNetDrive1.LocalDrive      = "M:";
        oNetDrive1.Persistent      = true;
        oNetDrive1.SaveCredentials = true;
        oNetDrive1.ShareName       = @"\\172.16.12.62\ams";

        try
        {
            oNetDrive1.MapDrive(@"T1FAB\t1eda", "CIMabc123");



            for (int i = 1; i <= Request.Files.Count; i++)
            {
                FileUpload myFL = new FileUpload();
                //ContentPlaceHolder c = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
                //myFL = (FileUpload)c.FindControl("FileUpload" + i);
                myFL = (FileUpload)Page.FindControl("FileUpload" + i);
                if (myFL.PostedFile.ContentLength < 15360000)
                {
                    if ((myFL.PostedFile != null) && (myFL.PostedFile.ContentLength > 0))
                    {
                        string fn = System.IO.Path.GetFileName(myFL.PostedFile.FileName);
                        // string saveLocation = Server.MapPath("../") + "\\upload_file\\" + fn;
                        //string saveLocation = Server.MapPath("FileList/") + fn;
                        string saveLocation = oNetDrive1.LocalDrive + @"\" + fn;


                        //Session["file_path"] = "FileList/" + fn;
                        int    file_size = myFL.PostedFile.ContentLength;
                        string file_type = myFL.PostedFile.ContentType;
                        try
                        {
                            myFL.PostedFile.SaveAs(saveLocation);

                            //OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["dsnn"]);

                            //string strClientIP;

                            string strClientIP = Request.ServerVariables["remote_host"].ToString();

                            string sql_insert = @"insert into onduty_file
                                             (seq, file_name, dttm)
                                             values
                                            ('{0}', '{1}', sysdate)";

                            FileHandle cfilehandle = new FileHandle();
                            //cfilehandle.GetMaxSeq();
                            cfilehandle.Seq = Session["seq"].ToString();
                            sql_insert      = string.Format(sql_insert, cfilehandle.Seq, fn);

                            func.get_sql_execute(sql_insert, conn);
                        }
                        catch (Exception ex)
                        {
                            Response.Write("上傳檔案失敗");
                        }
                    }
                }

                else
                {
                    //Label3.Visible = true;
                    //Label3.Text = "上傳檔案超過15MB...";
                }
            }
            // Parser_tmp_directory_file(oNetDrive.LocalDrive + "\\T1\\" + DropDownList1.SelectedValue.ToString() + "\\EDANG\\", "*.TXT", -360);
            // Delete_tmp_directory_file(HttpContext.Current.Server.MapPath(".") + "\\File\\", "*", -3);


            oNetDrive1.UnMapDrive(oNetDrive1.LocalDrive, true);
        }
        catch (Exception)
        {
            oNetDrive1.UnMapDrive(oNetDrive1.LocalDrive, true);
        }
        finally
        {
            //oNetDrive.UnMapDrive();
        }


        //oNetDrive.MapDrive(@"T1FAB\t1eda", "CIMabc123");

        #endregion



//        string frmClose = @"<script language='javascript' type='text/JavaScript'> 
//                             self.opener.location.reload();
//                             window.opener=null; 
//
//                             window.open('','_self'); 
//
//                             window.close();
//
//                             </script>";

//        //呼叫 javascript 
//        this.Page.RegisterStartupScript("", frmClose);
    }
Ejemplo n.º 40
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if ((FileUpload.HasFile))
        {
            if (!Convert.IsDBNull(FileUpload.PostedFile) &
                FileUpload.PostedFile.ContentLength > 0)
            {
                //FIRST, SAVE THE SELECTED FILE IN THE ROOT DIRECTORY.
                FileUpload.SaveAs(Server.MapPath(".") + "\\" + FileUpload.FileName);

                SqlBulkCopy oSqlBulk = null;

                // SET A CONNECTION WITH THE EXCEL FILE.
                OleDbConnection myExcelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + Server.MapPath(".") + "\\" + FileUpload.FileName + ";Extended Properties=Excel 12.0;");
                try
                {
                    myExcelConn.Open();

                    // GET DATA FROM EXCEL SHEET.
                    OleDbCommand objOleDB = new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);

                    // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
                    OleDbDataReader objBulkReader = null;
                    objBulkReader = objOleDB.ExecuteReader();

                    // SET THE CONNECTION STRING.
                    string sCon = "Data Source=NGOC-KUTE\\NGOCPHANTHI;Persist Security Info=False;" +
                                  "Integrated Security=SSPI;" +
                                  "Initial Catalog=D8CNPM;User Id=sa;Password=123456;" +
                                  "Connect Timeout=30;";



                    using (SqlConnection con = new SqlConnection(sCon))
                    {
                        con.Open();

                        // FINALLY, LOAD DATA INTO THE DATABASE TABLE.
                        oSqlBulk = new SqlBulkCopy(con);
                        oSqlBulk.DestinationTableName = "tblTheLoai"; // TABLE NAME.
                        oSqlBulk.WriteToServer(objBulkReader);
                    }
                    string script = "alert(\"Thêm thành công!\");";
                    ScriptManager.RegisterStartupScript(this, GetType(),
                                                        "ServerControlScript", script, true);

                    Load_data();
                }
                catch (Exception ex)
                {
                    string script = "alert(\"Thêm k thành công!\");";
                    ScriptManager.RegisterStartupScript(this, GetType(),
                                                        "ServerControlScript", script, true);
                }
                finally
                {
                    string script = "alert(\"Thêm k thành công!\");";
                    ScriptManager.RegisterStartupScript(this, GetType(),
                                                        "ServerControlScript", script, true);
                    // CLEAR.
                    // oSqlBulk.Close();
                    //oSqlBulk = null;
                    myExcelConn.Close();
                    myExcelConn = null;
                }
            }
        }
    }
Ejemplo n.º 41
0
 /// <summary>
 /// Uploads an Image for A Category
 /// Level: External
 /// </summary>
 /// <param name="myUploadControl">The Upload Control</param>
 /// <returns>Tuple Where string is the URL and UploadResult is an Enum</returns>
 private Tuple <string, UploadResult> UploadImage(FileUpload myUploadControl)
 {
     return(new External.administrator.UploadImage().Upload(myUploadControl));
 }
Ejemplo n.º 42
0
 public static Comando <Entidad> CrearComandoSubirArchivo(FileUpload fileUpload)
 {
     return(new ComandoSubirArchivo(fileUpload));
 }
Ejemplo n.º 43
0
        public async Task <IActionResult> UpdateSlider(int id, [FromForm] FileUpload obj, [FromForm] Slider _slider)
        {
            string imageName = null;

            if (id != _slider.SliderID || id == null)
            {
                return(BadRequest(new { message = "you should sent equal id's" }));
            }

            if (_slider == null)
            {
                return(BadRequest());
            }

            var retrievedSlider = await Context.Slider.FindAsync(id);

            if (id == null)
            {
                return(NotFound(new { message = "there is no slider with this id" }));
            }


            if (obj.Files != null)
            {
                string Ext = Path.GetExtension(obj.Files.FileName);

                if ((Ext == ".jpg" || Ext == ".png"))
                {
                    if (!Directory.Exists(_environment.WebRootPath + "\\Slider\\"))
                    {
                        Directory.CreateDirectory(_environment.WebRootPath + "\\Slider\\");
                    }

                    imageName = Guid.NewGuid().ToString() + "-" + obj.Files.FileName;
                    //var FilePath = Path.Combine(uploadDir)
                    using (FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\Slider\\" + imageName))
                    {
                        await obj.Files.CopyToAsync(fileStream);

                        await fileStream.FlushAsync();

                        //imageName = obj.Files.FileName;
                    }
                }
            }

            try
            {
                //Db.UpdateSlider(id, _slider);
                retrievedSlider.Link        = _slider.Link;
                retrievedSlider.Image       = imageName;
                retrievedSlider.Title       = _slider.Title;
                retrievedSlider.Description = _slider.Description;

                await Context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw new TimeoutException("time exception out in Slider Controller Update");
            }

            return(Ok(retrievedSlider));
        }
Ejemplo n.º 44
0
    StructUpload ConvertCSVtoDataTable(FileUpload fu)
    {
        ErrorLst = new List <string>();
        lines    = new List <string>();

        string strForHeader = "";

        using (System.IO.StreamReader file = new StreamReader(fu.FileContent))
        {
            strForHeader = file.ReadLine();
            while (!file.EndOfStream)
            {
                lines.Add(file.ReadLine());
                lineCount = lines.Count;
            }
        }

        string[]  headers    = strForHeader.Split('~');
        DataTable dtSave     = new DataTable();
        int       errorCount = 0;

        foreach (string header in headers)
        {
            string colName = header;
            #region Rename ColName
            //int a = 1;
            //foreach (DataColumn item in dtSave.Columns)
            //{
            //    while (item.ColumnName == colName)
            //    {
            //        a++;
            //        colName += a;
            //    }
            //}
            #endregion
            try
            {
                dtSave.Columns.Add(colName);
            }
            catch (Exception ex)
            {
                errorCount++;
                lblException.Text += errorCount + ". " + ex.Message + "<br />";
            }
        }
        dtSave.Columns.Add("FileName", typeof(string));

        foreach (string item in lines)
        {
            string[] rows = Regex.Split(item, "~(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.IgnoreCase);
            DataRow  dr   = dtSave.NewRow();

            if (rows.Count() < headers.Count())
            {
                ErrorLst.Add(item);
                //lblException.Text += "System Can Not Read This Lines : <br />" + ErrorLst + "<br />";
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowException", "ShowException()", true);
            }
            else
            {
                int i;
                for (i = 0; i < rows.Count(); i++)
                {
                    dr[i] = rows[i];
                }

                dr[i] = fu.FileName;
                dtSave.Rows.Add(dr);
            }
            rows = null;
        }

        StructUpload structUpload = new StructUpload();
        structUpload.BulkDT    = dtSave;
        structUpload.DataCount = (int)dtSave.Rows.Count;
        structUpload.FileName  = fu.FileName;

        if (listStruct == null)
        {
            listStruct = new StructUpload[5];
            //listStruct = new List<StructUpload>(4);
        }
        //structUpload.TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File" + (listStruct.Count() + 1).ToString();

        return(structUpload);
    }
Ejemplo n.º 45
0
    private void UploadAnsDisplay(FileUpload sender) //פונקציית עליית תמונות
    {
        string fileType = sender.PostedFile.ContentType;

        if (fileType.Contains("image"))
        {
            string fileName      = sender.PostedFile.FileName;
            string endOfFileName = fileName.Substring(fileName.LastIndexOf("."));
            string myTime        = DateTime.Now.ToString("dd_MM_yy-HH_mm_ss");
            string imageNewName  = "imageNewName" + myTime + endOfFileName;

            // Bitmap המרת הקובץ שיתקבל למשתנה מסוג
            System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(sender.PostedFile.InputStream);

            //קריאה לפונקציה המקטינה את התמונה
            System.Drawing.Image objImage = FixedSize(bmpPostedImage, 134, 126);

            //שמירת הקובץ בגודלו החדש בתיקייה
            objImage.Save(Server.MapPath(imageLibPath) + imageNewName);


            for (int i = 1; i <= 4; i++)
            {
                FileUpload btnSender = sender as FileUpload;
                string     mySender  = btnSender.ClientID;
                string     myUpload  = "myUpload" + i.ToString();
                string     ans_url   = "ans_url" + i.ToString();

                if (mySender == "myUpload5") //אם התמונה שייכת לשאלה
                {
                    ImageButton5.ImageUrl = imageLibPath + imageNewName;
                    ans_url = imageNewName;
                    Session["pic" + i + "_url"] = ans_url;

                    ImgMagnify5.Visible = true;
                    ImgTrash5.Visible   = true;
                }

                else if (mySender == myUpload) //אם התמונה שייכת למסיח
                {
                    var AnswerPic = ((Image)FindControl("ImageButton" + i.ToString()));
                    AnswerPic.ImageUrl          = imageLibPath + imageNewName;
                    ans_url                     = imageNewName;
                    Session["pic" + i + "_url"] = ans_url;

                    var AnswerTxt = ((TextBox)FindControl("txtAnswer" + i.ToString()));
                    AnswerTxt.Text      = imageLibPath + imageNewName;
                    AnswerTxt.Enabled   = false;
                    AnswerTxt.ForeColor = System.Drawing.Color.FromArgb(235, 235, 228);

                    var ImgMagnify = ((ImageButton)FindControl("ImgMagnify" + i.ToString()));
                    ImgMagnify.Visible = true;

                    var ImgTrash = ((ImageButton)FindControl("ImgTrash" + i.ToString()));
                    ImgTrash.Visible = true;
                }

                ViewState["VSNumOfAns"] = lblNumOfAns.Text;
                Page.ClientScript.RegisterHiddenField("HiddenVSNumOfAns", ViewState["VSNumOfAns"].ToString());

                ViewState["VSNewOrUpdate"] = lblNewOrUpdate.Text;
                Page.ClientScript.RegisterHiddenField("HiddenVSNewOrUpdate", ViewState["VSNewOrUpdate"].ToString());
            }
        }
    }
Ejemplo n.º 46
0
    protected void btnHide_Click(object sender, EventArgs e)
    {
        try
        {
            #region Code
            AlertSuccess.Visible = false;
            AlertWarning.Visible = false;
            if (FU1.HasFile)
            {
                f1 = FU1;

                string NameOfFile = ValidateNameOfFile(f1); //Validate FileName

                string Tab = Path.GetFileNameWithoutExtension(f1.FileName);
                Tab = Tab.Substring(Tab.IndexOf("_"));
                Tab = Tab.Split('_')[1].Split('_')[0];
                Tab = Tab.Substring(3);

                if (Tab != "1")
                {
                    spanFName1.Attributes.Add("class", "text-danger");
                    spanFName1.InnerText = "File Should be _TAB1_" + NameOfFile;
                    return;
                }
                if (NameOfFile != "true")
                {
                    spanFName1.Attributes.Add("class", "text-danger");
                    spanFName1.InnerText = "File Should be .._TAB1_" + NameOfFile;//"File name does not match with selected Session & Year";
                    return;
                }

                StructUpload FUData = ConvertCSVtoDataTable(f1);
                FUData.TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File1";

                //string filter = NameOfFile;
                //FU2.Attributes.Add("accept", NameOfFile);//".xls, .xlsx");

                #region Implement
                //string TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File1";
                //DataTable dtColumnCheck = dlFU.DtColumnCheck(TableName);
                //int i = 0;
                //foreach (DataRow dr in dtColumnCheck.Rows)
                //{
                //    foreach (DataColumn item in FUData.BulkDT.Columns)
                //    {
                //        if (dr[0].ToString() != item.ColumnName)
                //        {
                //            lblException.Text += "<br />" + item + " is not matching with " + dr[0];
                //        }
                //    }
                //    if (dr[i] == )
                //    {

                //    }
                //}
                #endregion

                //listStruct.Insert(0, FUData);
                listStruct.SetValue(FUData, 0);//[0] = FUData;
                spanFName1.Attributes.Add("class", "text-primary");
                spanFName1.InnerText  = FUData.DataCount.ToString();
                spanFName1.InnerText += " - " + FU1.FileName;
            }
            else if (FU2.HasFile)
            {
                f2 = FU2;

                string NameOfFile = ValidateNameOfFile(f2); //Validate FileName

                string Tab = Path.GetFileNameWithoutExtension(f2.FileName);
                Tab = Tab.Substring(Tab.IndexOf("_"));
                Tab = Tab.Split('_')[1].Split('_')[0];
                Tab = Tab.Substring(3);

                if (Tab != "2")
                {
                    spanFName2.Attributes.Add("class", "text-danger");
                    spanFName2.InnerText = "File Should be .._TAB2_" + NameOfFile;
                    return;
                }
                if (NameOfFile != "true")
                {
                    spanFName2.Attributes.Add("class", "text-danger");
                    spanFName2.InnerText = "File Should be .._TAB2_" + NameOfFile;
                    return;
                }
                StructUpload FUData = ConvertCSVtoDataTable(f2);
                FUData.TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File2";
                listStruct.SetValue(FUData, 1);
                //listStruct.Insert(1, FUData);
                spanFName2.Attributes.Add("class", "text-primary");
                spanFName2.InnerText  = FUData.DataCount.ToString();
                spanFName2.InnerText += " - " + FU2.FileName;
            }
            else if (FU3.HasFile)
            {
                f3 = FU3;
                string NameOfFile = ValidateNameOfFile(f3); //Validate FileName

                string Tab = Path.GetFileNameWithoutExtension(f3.FileName);
                Tab = Tab.Substring(Tab.IndexOf("_"));
                Tab = Tab.Split('_')[1].Split('_')[0];
                Tab = Tab.Substring(3);

                if (Tab != "3")
                {
                    spanFName3.Attributes.Add("class", "text-danger");
                    spanFName3.InnerText = "File Should be .._TAB3_" + NameOfFile;
                    return;
                }
                if (NameOfFile != "true")
                {
                    spanFName3.Attributes.Add("class", "text-danger");
                    spanFName3.InnerText = "File Should be .._TAB3_" + NameOfFile;
                    return;
                }
                StructUpload FUData = ConvertCSVtoDataTable(f3);
                FUData.TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File3";
                listStruct.SetValue(FUData, 2);
                //listStruct.Insert(2, FUData);
                spanFName3.InnerText  = FUData.DataCount.ToString();
                spanFName3.InnerText += " - " + FU3.FileName;
                spanFName3.Attributes.Add("class", "text-primary");
            }
            else if (FU4.HasFile)
            {
                f4 = FU4;

                string NameOfFile = ValidateNameOfFile(f4); //Validate FileName

                string Tab = Path.GetFileNameWithoutExtension(f4.FileName);
                Tab = Tab.Substring(Tab.IndexOf("_"));
                Tab = Tab.Split('_')[1].Split('_')[0];
                Tab = Tab.Substring(3);

                if (Tab != "4")
                {
                    spanFName4.Attributes.Add("class", "text-danger");
                    spanFName4.InnerText = "File Should be .._TAB4_" + NameOfFile;
                    return;
                }
                if (NameOfFile != "true")
                {
                    spanFName4.Attributes.Add("class", "text-danger");
                    spanFName4.InnerText = "File Should be .._TAB4_" + NameOfFile;
                    return;
                }
                StructUpload FUData = ConvertCSVtoDataTable(f4);
                FUData.TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File4";
                listStruct.SetValue(FUData, 3);
                //listStruct.Insert(3, FUData);
                spanFName4.InnerText  = FUData.DataCount.ToString();
                spanFName4.InnerText += " - " + FU4.FileName;
                spanFName4.Attributes.Add("class", "text-primary");
            }
            else if (FU5.HasFile)
            {
                f5 = FU5;

                string NameOfFile = ValidateNameOfFile(f5); //Validate FileName
                string Tab        = Path.GetFileNameWithoutExtension(f5.FileName);
                Tab = Tab.Substring(Tab.IndexOf("_"));
                Tab = Tab.Split('_')[1].Split('_')[0];
                Tab = Tab.Substring(3);

                if (Tab != "5")
                {
                    spanFName5.Attributes.Add("class", "text-danger");
                    spanFName5.InnerText = "File Should be .._TAB5_" + NameOfFile;
                    return;
                }
                if (NameOfFile != "true")
                {
                    spanFName5.Attributes.Add("class", "text-danger");
                    spanFName5.InnerText = "File Should be .._TAB5_" + NameOfFile;
                    return;
                }

                StructUpload FUData = ConvertCSVtoDataTable(f5);
                FUData.TableName = "Tbl_" + ddlExamName.SelectedItem.Text + "_" + ddlSession.SelectedItem.Text + "_" + "_File5";
                listStruct.SetValue(FUData, 4);
                //listStruct.Insert(4, FUData);
                spanFName5.InnerText  = FUData.DataCount.ToString();
                spanFName5.InnerText += " - " + FU5.FileName;
                spanFName5.Attributes.Add("class", "text-primary");
            }
            #endregion
        }
        catch (Exception ex)
        {
            lblException.Text += ex.Message;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowException", "ShowException()", true);
        }
        finally
        {
            if (listStruct != null)
            {
                if (!string.IsNullOrEmpty(listStruct[0].FileName) && !string.IsNullOrEmpty(listStruct[1].FileName) && !string.IsNullOrEmpty(listStruct[2].FileName) && !string.IsNullOrEmpty(listStruct[3].FileName) && !string.IsNullOrEmpty(listStruct[4].FileName))
                {
                    btnSave.Visible = true;
                }
            }
            else
            {
                listStruct           = new StructUpload[5];
                spanFName1.InnerText = spanFName2.InnerText = spanFName3.InnerText = spanFName4.InnerText = spanFName5.InnerText = "";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('All files has empty. please file choose again')", true);
            }
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowConfirmation", "ShowConfirmation()", true);
        }
    }
Ejemplo n.º 47
0
    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        System.Text.StringBuilder myLabel = new System.Text.StringBuilder();

        string strSql123 = "";

        for (int i = 1; i <= Request.Files.Count; i++)
        {
            FileUpload myFL = new FileUpload();
            myFL = (FileUpload)Page.FindControl("FileUpload" + i);
            if ((myFL.PostedFile != null) && (myFL.PostedFile.ContentLength > 0))
            {
                string fn           = System.IO.Path.GetFileName(myFL.PostedFile.FileName);
                string SaveLocation = Server.MapPath("upload_file/") + fn;
                int    file_size    = myFL.PostedFile.ContentLength;
                string file_type    = myFL.PostedFile.ContentType;
                //try
                //{
                //    myFL.PostedFile.SaveAs(SaveLocation);

                //    OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["dsnn"]);

                //    string strClientIP;

                //    strClientIP = Request.ServerVariables["remote_host"].ToString();


                //    strSql123 = "insert into mms_meeting_upload_file";

                //    strSql123 += "(aid, aid2, file_path, file_name, file_size, file_type, ip, user_id) values";

                //    strSql123 += "('" + Request.QueryString["aid"].ToString() + "', '" + Request.QueryString["aid2"].ToString() + "', '" + SaveLocation + "', '" + fn + "', '" + file_size + "', '" + file_type + "', '" + strClientIP + "', 'test')";
                //    //strSql123 += "(1, 2, '" + SaveLocation + "', '" + fn + "', '" + file_size + "', '" + file_type + "', '" + strClientIP + "', 'test')";


                //    OleDbCommand myCommand = new OleDbCommand(strSql123, myConnection);
                //    myConnection.Open();
                //    OleDbDataReader MyReader = myCommand.ExecuteReader();
                //    myLabel.Append("<hr>--- " + fn);

                //    Label2.Text = " 上傳成功!!!" + myLabel.ToString();

                //}
                //catch (Exception Ex)
                //{
                //    Response.Write("銝撜瑼獢憭望");
                //}

                myFL.PostedFile.SaveAs(SaveLocation);


                #region insert data to New Alarm Server mapping Db
                sql_temp = "SELECT * FROM [Sheet1$] ";

                ds_temp1 = func.get_dataSet_access(sql_temp, conn);
                DT       = ds_temp1.Tables[0];

                insert_user_id();
                insert_Event_id();
                insert_FAB_id();
                insert_SUBSYSTEM_id();
                insert_brm_normalalarm();
                insert_brm_alarmlevel();
                insert_brm_user_eventgroup();
                insert_map_usereventgroup();
                insert_map_dispatchrule();

                #endregion



                myLabel.Append("<BR><hr>--- " + fn);
            }



            LabelX.Text = " <br>上傳成功!!!" + myLabel.ToString();
        }

        sql_temp = "SELECT * FROM [Sheet1$] ";

        ds_temp1             = func.get_dataSet_access(sql_temp, conn);
        GridView1.DataSource = ds_temp1.Tables[0];
        GridView1.DataBind();
    }
Ejemplo n.º 48
0
        protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            lbid = hlbid.Value;
            System.Web.UI.WebControls.Button btn = e.CommandSource as System.Web.UI.WebControls.Button;
            if (btn == null)
            {
                return;
            }
            int index = ((System.Web.UI.WebControls.GridViewRow)btn.Parent.Parent).RowIndex;

            DataKey key    = this.GV.DataKeys[index];
            string  NewsID = key.Value.ToString();


            GridViewRow gvr = GV.Rows[index];

            if (e.CommandName == "upFile")
            {
                //寻找上传控件
                FileUpload fu = (FileUpload)gvr.FindControl("FileUpload1");
                if (fu != null)
                {
                    if (fu.HasFile)
                    {
                        SQLHelper_ db = new SQLHelper_();
                        //上传图片
                        string pic = UpFile(fu);
                        //删除原图
                        db.sql = "SELECT pic FROM " + com.tablePrefix + "News WHERE NewsID=" + NewsID;
                        string pic0 = db.Get_DataTable().Rows[0][0].ToString();
                        if (pic0.Length > 0)
                        {
                            FileSys.delFile(pic0);
                        }

                        //更新数据库
                        db.sql = "UPDATE News SET pic='" + pic + "' WHERE NewsID=" + NewsID;
                        db.ExecSql();

                        bindGv();
                        alert.Show(Page, "图片更新成功");
                    }
                }
            }
            if (e.CommandName == "Save")
            {
                //查找 title控件
                TextBox txtTitle = null;
                try
                {
                    txtTitle = this.GV.Rows[index].Cells[1].Controls[0] as TextBox;
                }
                catch
                {
                    alert.Show(Page, "未找到标题控件");
                    return;
                }
                TextBox txtEditTime = null;
                try
                {
                    txtEditTime = this.GV.Rows[index].Cells[2].Controls[0] as TextBox;
                }
                catch
                {
                    alert.Show(Page, "未找到标题控件");
                    return;
                }



                FileUpload fu      = gvr.Cells[4].FindControl("FileUpload1") as FileUpload;
                TextBox    txtHref = null;
                try
                {
                    txtHref = this.GV.Rows[index].Cells[5].Controls[0] as TextBox;
                }
                catch
                {
                    alert.Show(Page, "未找到链接地址控件");
                    return;
                }


                string title    = pg.GetSafeString(txtTitle.Text.Trim());
                string EditTime = pg.GetSafeString(txtEditTime.Text.Trim());
                string href     = pg.GetSafeString(txtHref.Text.Trim());
                if (title == "")
                {
                    alert.Show(Page, "请填写标题");
                    return;
                }
                if (href == "")
                {
                    alert.Show(Page, "请填写链接地址");
                    return;
                }


                if (EditTime == "")
                {
                    EditTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                }
                string     pic = UpFile(fu);
                SQLHelper_ db  = new SQLHelper_();
                if (NewsID.Length > 0)
                {
                    //更新
                    if (pic != "")
                    {
                        db.sql = "UPDATE News SET title='" + title + "',pic='" + pic + "',editTime='" + EditTime + "',href='" + href + "' WHERE NewsID=" + NewsID;
                    }
                    else
                    {
                        db.sql = "UPDATE News SET title='" + title + "',editTime='" + EditTime + "',href='" + href + "' WHERE NewsID=" + NewsID;
                    }



                    if (db.ExecSql() != "1")
                    {
                        alert.Show(Page, "保存失败");
                    }
                    else
                    {
                        GV.EditIndex = -1;
                        bindGv();
                    }
                }
                else
                {
                    //添加
                    NewsID = clsNews.MaxNewsid();
                    db.sql = "INSERT INTO News(lbid,NewsID,title,pic,EditTime,AddTime,href) VALUES(" + lbid + "," + NewsID + ",'" + title + "','" + pic + "','" + EditTime + "',getdate(),'" + href + "')";
                    if (db.ExecSql() != "1")
                    {
                        alert.Show(Page, "添加失败");
                    }
                    else
                    {
                        GV.EditIndex = -1;
                        bindGv();
                    }
                }
            }
        }
        private async Task <string> FileMerge(string guid, string mediaName, int mediaGroupId)
        {
            string result = string.Empty;
            //媒体临时文件夹
            string guidFolder = Path.Combine(GlobalParameter._TEMPROARY, Guid.NewGuid().ToString());
            //分块临时文件夹
            string temporary = Path.Combine(GlobalParameter._TEMPROARY, guid);//临时文件夹

            try
            {
                if (!Directory.Exists(guidFolder))
                {
                    Directory.CreateDirectory(guidFolder);
                }
                var files     = Directory.GetFiles(temporary);//获得下面的所有文件
                var finalPath = Path.Combine(guidFolder, mediaName);
                var fs        = new FileStream(finalPath, FileMode.Create);
                foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保证从0-N Write
                {
                    var bytes = System.IO.File.ReadAllBytes(part);
                    await fs.WriteAsync(bytes, 0, bytes.Length);

                    bytes = null;
                    System.IO.File.Delete(part);//删除分块
                }
                fs.Close();
                fs.Dispose();
                Directory.Delete(temporary);//删除文件夹

                //处理文件
                FileUpload fileUpload = new FileUpload();
                fileUpload.file_name      = mediaName;
                fileUpload.status         = "add";
                fileUpload.file_path      = Path.GetDirectoryName(finalPath);
                fileUpload.media_group_id = mediaGroupId;

                List <FileUpload> fileUploads = new List <FileUpload>();
                fileUploads.Add(fileUpload);

                FileService   fileService = new FileService(_mediaInfoService, _mediaGroupService);
                List <string> objreList   = fileService.LoadFiles(fileUploads);
                if (objreList.Count > 0)
                {
                    result = objreList[0];
                }
                System.IO.File.Delete(finalPath);
                Directory.Delete(Path.GetDirectoryName(finalPath));//删除文件夹
            }
            catch (Exception ex)
            {
                var files = Directory.GetFiles(temporary);                        //获得下面的所有文件
                foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x)) //排一下序,保证从0-N Write
                {
                    System.IO.File.Delete(part);                                  //删除分块
                }
                Directory.Delete(temporary);                                      //删除文件夹

                result = ex.Message;
            }
            return(result);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            _hfBinaryFileId    = new HiddenField();
            _hfBinaryFileId.ID = this.ID + "_hfBinaryFileId";
            Controls.Add(_hfBinaryFileId);

            _hfOriginalBinaryFileId    = new HiddenField();
            _hfOriginalBinaryFileId.ID = this.ID + "_hfOriginalBinaryFileId";
            Controls.Add(_hfOriginalBinaryFileId);

            _hfCropBinaryFileId    = new HiddenField();
            _hfCropBinaryFileId.ID = this.ID + "_hfCropBinaryFileId";
            Controls.Add(_hfCropBinaryFileId);

            _hfBinaryFileTypeGuid    = new HiddenField();
            _hfBinaryFileTypeGuid.ID = this.ID + "_hfBinaryFileTypeGuid";
            Controls.Add(_hfBinaryFileTypeGuid);

            _aRemove           = new HtmlAnchor();
            _aRemove.ID        = "rmv";
            _aRemove.InnerHtml = "<i class='fa fa-times'></i>";
            Controls.Add(_aRemove);

            _lbShowModal                  = new LinkButton();
            _lbShowModal.ID               = this.ID + "_lbShowModal";
            _lbShowModal.CssClass         = this.ButtonCssClass;
            _lbShowModal.Text             = this.ButtonText;
            _lbShowModal.Click           += _lbShowModal_Click;
            _lbShowModal.CausesValidation = false;
            Controls.Add(_lbShowModal);

            // If we are not showing the delete button then
            // only the UploadImage button should be active.
            if (!ShowDeleteButton)
            {
                _aRemove.Visible     = false;
                _lbShowModal.Visible = false;
            }

            _lbUploadImage                  = new LinkButton();
            _lbUploadImage.ID               = this.ID + "_lbUploadImage";
            _lbUploadImage.CssClass         = this.ButtonCssClass;
            _lbUploadImage.Text             = this.ButtonText;
            _lbUploadImage.CausesValidation = false;
            Controls.Add(_lbUploadImage);

            _lSaveStatus          = new Label();
            _lSaveStatus.ID       = this.ID + "_lSaveStatus";
            _lSaveStatus.CssClass = "fa fa-2x fa-check-circle-o text-success";
            _lSaveStatus.Style.Add("vertical-align", "bottom");
            _lSaveStatus.Visible = false;
            Controls.Add(_lSaveStatus);

            _fileUpload    = new FileUpload();
            _fileUpload.ID = this.ID + "_fu";
            Controls.Add(_fileUpload);

            _mdImageDialog = new ModalDialog();
            _mdImageDialog.ValidationGroup = "vg_mdImageDialog";
            _mdImageDialog.ID             = this.ID + "_mdImageDialog";
            _mdImageDialog.Title          = "Image";
            _mdImageDialog.SaveButtonText = "Crop";
            _mdImageDialog.SaveClick     += _mdImageDialog_SaveClick;

            _pnlCropContainer                   = new Panel();
            _pnlCropContainer.CssClass          = "crop-container image-editor-crop-container clearfix";
            _nbImageWarning                     = new NotificationBox();
            _nbImageWarning.ID                  = this.ID + "_nbImageWarning";
            _nbImageWarning.NotificationBoxType = NotificationBoxType.Warning;
            _nbImageWarning.Text                = "SVG image cropping is not supported.";

            _imgCropSource          = new Image();
            _imgCropSource.ID       = this.ID + "_imgCropSource";
            _imgCropSource.CssClass = "image-editor-crop-source";

            _pnlCropContainer.Controls.Add(_imgCropSource);

            _mdImageDialog.Content.Controls.Add(_nbImageWarning);
            _mdImageDialog.Content.Controls.Add(_pnlCropContainer);

            _hfCropCoords    = new HiddenField();
            _hfCropCoords.ID = this.ID + "_hfCropCoords";
            _pnlCropContainer.Controls.Add(_hfCropCoords);

            Controls.Add(_mdImageDialog);
        }
Ejemplo n.º 51
0
        public async Task InsertImageUpload(FileUpload upload)
        {
            var id = (int)await _connection.InsertAsync(upload).ConfigureAwait(false);

            upload.Id = id;
        }
Ejemplo n.º 52
0
 protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
 {
     try
     {
         if (e.CommandName == "Send")
         {
             TextBox a = (TextBox)e.Item.FindControl("TextBox1");
             if (a.Text.Trim() != "")
             {
                 Dept   obj   = new Dept();
                 string dname = obj.getDeptName(id);
                 if (!dname.Contains("Occured"))
                 {
                     string result = obj.sendMessage(dname, a.Text, "Applicant-" + e.CommandArgument);
                     if (!result.Contains("Occured"))
                     {
                         Response.Write("<div class='notification green'>Message Send to Applicant!</div>");
                     }
                     else
                     {
                         Response.Write("<div class='notification red'>" + result + " in sending message</div>");
                     }
                 }
                 else
                 {
                     Response.Write("<div class='notification red'>Could not get Dept Name</div>");
                 }
             }
             else
             {
                 Response.Write("<div class='notification red'>Message cannot be empty</div>");
             }
             //empty text area
             a.Text = "";
         }
         if (e.CommandName == "Upload")
         {
             FileUpload fp = (FileUpload)e.Item.FindControl("FileUpload1");
             if (fp.HasFile)
             {
                 Dept   obj       = new Dept();
                 string dname     = obj.getDeptName(id);
                 string extension = Path.GetExtension(fp.PostedFile.FileName);
                 string filename  = "Dept-" + dname + "- to Applicant id-" + e.CommandArgument + " - " + DateTime.Now + extension;
                 string path      = Server.MapPath("/Applicant_Data/Files");
                 filename = filename.Replace("/", "-").Replace(":", "-");
                 if (!Directory.Exists(path))
                 {
                     Directory.CreateDirectory(path);
                 }
                 fp.SaveAs(path + "/" + filename);
                 string result = obj.uploadFile(dname, "Applicant_Data/Files/" + filename, "Applicant-" + e.CommandArgument);
                 if (!result.Contains("Occured"))
                 {
                     Response.Write("<div class='notification green'>File uploaded and sent successfully to applicant id: " + e.CommandArgument + "</div>");
                 }
                 else
                 {
                     Response.Write("<div class='notification red'>" + result + "</div>");
                 }
             }
             else
             {
                 Response.Write("<div class='notification red'>Select a file first</div>");
             }
         }
     }
     catch (Exception ex)
     {
         writeException obj = new writeException();
         obj.WriteExceptionToFile(ex, "Department.aspx.cs-ListView1_ItemCommand");
         Response.Write("<script>alert('Exception Occured')</script>");
     }
 }
Ejemplo n.º 53
0
        protected void EditDocumentInfo(object sender, EventArgs e)
        {
            HtmlControl theframe1 = (HtmlControl)this.Master.FindControl("oBodyPlaceHolder").FindControl("frame1");



            //theframe1.Attributes["src"] = @"\\autism-fs01\d$\WebDocs\DocVersID__ReplacingFileNotice.htm";

            //HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");

            // edit the following to replace the file //
            FileUpload FileUpload2      = (FileUpload)this.FormView1.FindControl("FileUpload2");
            Label      FileUploadLabel2 = (Label)this.FormView1.FindControl("FileUploadLabel2");
            Label      FileExtLabel2    = (Label)this.FormView1.FindControl("FileExtLabel2");
            Label      DocVersIDLabel2  = (Label)this.FormView1.FindControl("DocVersIDTextbox");
            //int New_or_Replace = this.FormView1.FindControl("RadioButtonList1");

            //        string path = ConfigurationManager.AppSettings["DOCUMENT_LOCATION"];

            string path         = @"\\autism-fs01\d$\WebDocs\";
            string path_replace = @"\\autism-fs01\d$\WebDocs\ReplacedDocs\";

            bool fileOK;

            fileOK = false;
            // Before attempting to perform operations
            // on the file, verify that the FileUpload
            // control contains a file.
            if (FileUpload2.HasFile)
            {
                String DocVersID     = DocVersIDLabel2.Text;
                String filePath      = System.IO.Path.GetFullPath(FileUpload2.FileName);
                String fileExtension =
                    System.IO.Path.GetExtension(FileUpload2.FileName).ToLower();
                String[] allowedExtensions =
                { ".doc", ".pdf", ".txt", ".xls", ".gif", ".png", ".jpeg", ".jpg", ".bmp", ".sps", ".sav", ".spo", ".rtf" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }

                if (fileOK)
                {
                    try
                    {
                        ((Label)FormView1.FindControl("FileExtLabel2")).Text    = fileExtension;
                        ((Label)FormView1.FindControl("FileUploadLabel2")).Text = "DocVersID_" + DocVersID + fileExtension;
                        //((Label)FormView1.Row.Cells[0].FindControl("FileUploadLabel2")).Text = FileUpload2.FileName;


                        //copy the original to the "ReplacedDocs" folder
                        string oldfilename = @"\\autism-fs01\d$\WebDocs\DocVersID_" + DocVersID + ViewState["fileext"].ToString();
                        string newfilename = @"\\autism-fs01\d$\WebDocs\ReplacedDocs\DocVersID_" + DocVersID + "__" +
                                             DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day.ToString() + "__" +
                                             DateTime.Now.Hour.ToString() + "hrs" + DateTime.Now.Minute.ToString() + "mins" + ViewState["fileext"].ToString();
                        File.Copy(oldfilename, newfilename);



                        FileUpload2.PostedFile.SaveAs(path + "DocVersID_" + DocVersID + fileExtension);
                        MessageBox2.Show("File uploaded.");
                    }
                    catch (Exception ex)
                    {
                        //  ((Label)FormView1.Row.Cells[0].FindControl("FileUploadLabel1")).Text = "File could not be uploaded.";
                        MessageBox2.Show("ERROR: File could not be uploaded. (" + ex.Message + ")");
                    }
                }
                else
                {
                    MessageBox2.Show("Cannot accept files of this type.");
                }
            }
        }
Ejemplo n.º 54
0
        public string GetConfigurationTemplate(string template, IDictionary <string, string> parameters)
        {
            Settings settingsObj = Settings.Parse(template);

            new Populator(parameters).Populate(settingsObj);

#warning This should be taken care of via InputMappings
            DropDown CsvFile = settingsObj.Find("File") as DropDown;
            CsvFile.Options = this.ParentOutputs.Select(i => new Option()
            {
                DisplayMemeber = i.Name, ValueMemeber = i.Name
            }).ToList();

            Grid       definition     = (Grid)settingsObj.Find(nameof(CSVDefinition));
            CheckBox   useFile        = (CheckBox)settingsObj.Find("UseFileDefinition");
            FileUpload definitionFile = (FileUpload)settingsObj.Find("FileDef");
            definition.DisableDelete       =
                definition.DisableInsert   =
                    definitionFile.Visible = useFile.Value;

            if (useFile.Value)
            {
                if (definitionFile.Value?.Content != null)
                {
                    string[] headers = null;
                    //Read file and retrieve headers
                    var csvHeaderConfig = new CsvHelper.Configuration.Configuration()
                    {
                        HasHeaderRecord  = ((Setting <bool>)settingsObj.Find(nameof(HasHeaderRecord))).Value,
                        Delimiter        = ((Setting <string>)settingsObj.Find(nameof(Delimiter))).Value,
                        Encoding         = System.Text.Encoding.GetEncoding(((Setting <string>)settingsObj.Find(nameof(Encoding))).Value),
                        Quote            = ((Setting <string>)settingsObj.Find(nameof(Quote))).Value.FirstOrDefault(),
                        ShouldSkipRecord = (row) => row.Length == 1 && row.First() == "\0",
                    };

                    using (var csv = new CsvReader(new StreamReader(new MemoryStream(definitionFile.Value.Content)), csvHeaderConfig))
                    {
                        csv.Read();
                        var h = csv.ReadHeader();
                        if (h == true)
                        {
                            headers = csv.Context.HeaderRecord;
                        }
                    }
                    if (headers != null)
                    {
                        IReadOnlyCollection <IDictionary <string, object> > fields = definition.Rows.ToArray();
                        //Put headers in the Definition grid; retaining values that are already there and removing those that do not have a matching header
                        var refreshedHeaders = headers
                                               .Select(h => definition.Rows.FirstOrDefault(r => h == (string)r["Name"])
                                                       ?? new Dictionary <string, object> {
                            { "Name", h }, { "Type", nameof(Types.String) }
                        });

                        definition.Value = Newtonsoft.Json.JsonConvert.SerializeObject(refreshedHeaders);
                    }
                }
                else
                {
                    //Clear the grid
                    definition.Value = Newtonsoft.Json.JsonConvert.SerializeObject(Array.Empty <IDictionary <string, object> >());
                }
            }

            return(settingsObj.ToString());
        }
Ejemplo n.º 55
0
    protected void lvExamResponse_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
        TextBox    examDt     = e.Item.FindControl("txtResponseDt") as TextBox;
        FileUpload uploadFile = e.Item.FindControl("FileUploadResponse") as FileUpload;
        TextBox    Remarks    = e.Item.FindControl("txtResponseRemarks") as TextBox;
        DateTime   examDate;

        if (!DateTime.TryParse(examDt.Text.Trim(), out examDate))
        {
            ClientScript.RegisterStartupScript(GetType(), "Response Date", "<script>alert('Verify Response Date')</script>");
            return;
        }
        if (uploadFile.HasFile == false)
        {
            ClientScript.RegisterStartupScript(GetType(), "Information", "<script>alert('Please select Upload File')</script>");
            return;
        }
        DataTable dt       = (DataTable)ViewState["ExamRptResponse"];
        int       Maxvalue = 0;

        foreach (DataRow dr in dt.Rows)
        {
            int getSlNo = dr.Field <int>("ResponseSlNo");
            Maxvalue = Math.Max(Maxvalue, getSlNo);
        }
        dt.Clear();
        string ExamRptFile   = "";
        string FileExtension = uploadFile.PostedFile.FileName.Substring(uploadFile.PostedFile.FileName.LastIndexOf(".") + 1).ToLower();

        if (Maxvalue > 0)
        {
            Maxvalue    = Maxvalue + 1;
            ExamRptFile = "ResponseExamRpt-" + lblFileNo.Text.Trim() + "-" + ddlFER.SelectedItem.Text.Trim() + "-" + Maxvalue.ToString() + "." + FileExtension;
        }
        else
        {
            Maxvalue    = 1;
            ExamRptFile = "ResponseExamRpt-" + lblFileNo.Text.Trim() + "-" + ddlFER.SelectedItem.Text.Trim() + "-" + "1" + "." + FileExtension;
        }
        SqlTransaction Trans;

        con.Open();
        Trans = con.BeginTransaction();
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "ExaminationResponseInsert";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection  = con;
            cmd.Transaction = Trans;
            SqlParameter pm1 = new SqlParameter();
            pm1.SourceColumn  = "FileNo";
            pm1.ParameterName = "@FileNo";
            pm1.Value         = lblFileNo.Text.Trim();
            pm1.SqlDbType     = SqlDbType.Char;
            pm1.Direction     = ParameterDirection.Input;
            SqlParameter pm2 = new SqlParameter();
            pm2.SourceColumn  = "ExaminationReport";
            pm2.ParameterName = "@ExaminationReport";
            pm2.Value         = ddlFER.SelectedItem.Text.Trim();
            pm2.SqlDbType     = SqlDbType.Char;
            pm2.Direction     = ParameterDirection.Input;
            SqlParameter pm3 = new SqlParameter();
            pm3.SourceColumn  = "ResponseSlNo";
            pm3.ParameterName = "@ResponseSlNo";
            pm3.Value         = Maxvalue;
            pm3.SqlDbType     = SqlDbType.Int;
            pm3.Direction     = ParameterDirection.Input;
            SqlParameter pm4 = new SqlParameter();
            pm4.SourceColumn  = "ResponseDate";
            pm4.ParameterName = "@ResponseDate";
            pm4.Value         = examDate.ToShortDateString();
            pm4.SqlDbType     = SqlDbType.Char;
            pm4.Direction     = ParameterDirection.Input;
            SqlParameter pm5 = new SqlParameter();
            pm5.SourceColumn  = "ResponseDocument";
            pm5.ParameterName = "@ResponseDocument";
            pm5.Value         = ExamRptFile;
            pm5.SqlDbType     = SqlDbType.Char;
            pm5.Direction     = ParameterDirection.Input;
            SqlParameter pm6 = new SqlParameter();
            pm6.SourceColumn  = "Remarks";
            pm6.ParameterName = "@Remarks";
            pm6.Value         = Remarks.Text.Trim();
            pm6.SqlDbType     = SqlDbType.Char;
            pm6.Direction     = ParameterDirection.Input;
            SqlParameter pm7 = new SqlParameter();
            pm7.SourceColumn  = "EntryDt";
            pm7.ParameterName = "@EntryDt";
            pm7.Value         = DateTime.Now.ToShortDateString();
            pm7.SqlDbType     = SqlDbType.Char;
            pm7.Direction     = ParameterDirection.Input;
            cmd.Parameters.Add(pm1);
            cmd.Parameters.Add(pm2);
            cmd.Parameters.Add(pm3);
            cmd.Parameters.Add(pm4);
            cmd.Parameters.Add(pm5);
            cmd.Parameters.Add(pm6);
            cmd.Parameters.Add(pm7);
            cmd.ExecuteNonQuery();

            try
            {
                HttpPostedFile file1      = uploadFile.PostedFile;
                Int32          fileLength = file1.ContentLength;
                string         fileName   = file1.FileName;
                byte[]         buffer     = new byte[fileLength];
                file1.InputStream.Read(buffer, 0, fileLength);
                FileStream newFile;
                string     strPath = @"F:\PatentDocument\" + lblFileNo.Text.Trim() + @"\Examination" + @"\";
                if (!Directory.Exists(strPath))
                {
                    Directory.CreateDirectory(strPath);
                }
                if (!File.Exists(strPath + ExamRptFile))
                {
                    newFile = File.Open(strPath + ExamRptFile, FileMode.Create);
                    newFile.Write(buffer, 0, buffer.Length);
                    newFile.Close();
                }
                else
                {
                    ClientScript.RegisterStartupScript(GetType(), "Information", "<script>alert('This File exists in this Folder')</script>");
                    Trans.Rollback();
                    con.Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "Error", "<script>alert('" + ex.Message.ToString() + "')</script>");
                Trans.Rollback();
                con.Close();
                return;
            }
            ClientScript.RegisterStartupScript(GetType(), "Success", "<script>alert('This Record successfully added')</script>");
            Trans.Commit();
            con.Close();
            string sql = "select * from examinationResponse where FileNo ='" + lblFileNo.Text.Trim() + "' and ExaminationReport='" + ddlFER.SelectedItem.Text.Trim() + "'";
            dt = SelectExamination(sql);
            ViewState["ExamRptResponse"]      = dt;
            lvExamResponse.InsertItemPosition = InsertItemPosition.None;
            lvExamResponse.DataSource         = dt;
            lvExamResponse.DataBind();
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(GetType(), "Error", "<script>alert('" + ex.Message.ToString() + "')</script>");
            Trans.Rollback();
            con.Close();
            return;
        }
    }
Ejemplo n.º 56
0
    void convert_str(FileUpload FileUpload1, Page page)
    {
        try
        {
            string _name = "";
            if (!FileUpload1.HasFile)
            {
                //AJAXManager.Alert(UpdatePanel1, "请选择文件");
                Manager.Alert("请选择文件", page);
                return;
            }
            else
            {
                string   path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "OA\\upload\\shuadan\\convert\\";
                string[] strs = { ".txt" };
                if (!BLL.Manager.UpFile(FileUpload1, strs, path, ""))
                {
                    //AJAXManager.Alert(UpdatePanel1, "文件上传错误");
                    Manager.Alert("文件上传错误", page);
                    return;
                }
                else
                {
                    HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[Manager.decl_UploadFileName];
                    _name = cookie.Value;
                    FileStream    fs   = new FileStream(path + _name, FileMode.Open, FileAccess.Read, FileShare.None);
                    StreamReader  sr   = new StreamReader(fs, System.Text.Encoding.Default);
                    List <string> list = new List <string>();
                    //手机号导入完毕,开始存储为txt文件
                    Random       ran          = new Random();
                    string       filename     = DateTime.Now.ToString("yyyy年MM月dd日HHmmss") + ran.Next(999, 9999).ToString() + ".txt";
                    string       filepath     = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "OA\\upload\\shuadan\\convert\\" + filename;
                    FileStream   fs_write     = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite);
                    StreamWriter strmWriter   = new StreamWriter(fs_write, System.Text.Encoding.Default);
                    string       convert_yuan = "";
                    string       convert_new  = "";
                    convert_new  = txt_new.Text.Trim();
                    convert_yuan = txt_yuan.Text.Trim();

                    string str = "";
                    string s   = Console.ReadLine();
                    int    j   = 0;
                    while (str != null)
                    {
                        str = sr.ReadLine();
                        if (str == null)
                        {
                            break;
                        }
                        j++;
                        if (j == 1)
                        {
                            continue;
                        }
                        //string[] xu = new String[2];
                        str = str.Replace(convert_yuan, convert_new);
                        //xu = str.Split('-');
                        //if (xu[0] == "")
                        //{
                        //    break;
                        //}
                        //Entity.shuadan sd = new Entity.shuadan();
                        //sd.sddate = DateTime.Now;
                        //sd.sdinfofrom = "4";
                        //sd.sdname = xu[0];
                        //sd.sdphone = xu[1];
                        //sd.sdprovince = xu[2];
                        //sd.scity = xu[3];
                        //sd.sdistrict = xu[4];
                        //sd.sdaddress = xu[5];
                        //list.Add(sd);
                        strmWriter.Write(str);
                        strmWriter.WriteLine(); //换行
                    }
                    sr.Close();

                    //strmWriter.Write(dt.Columns[i].ColumnName + " ");
                    //    strmWriter.WriteLine(); //换行
                    //foreach (shuadan sd_temp in list)
                    //{
                    //    //插入刷单数据
                    //    //BLL.shuadanManager.Insert(sd_temp);
                    //    string str_write = sd_temp.sdname + "," + sd_temp.sdphone + "," + sd_temp.sdprovince + " " + sd_temp.scity + " " + sd_temp.sdistrict + " " + sd_temp.sdaddress + ",100000";
                    //    strmWriter.Write(str_write);
                    //    strmWriter.WriteLine(); //换行
                    //}
                    strmWriter.Flush();
                    strmWriter.Close();


                    Entity.shuadan_record srr = new shuadan_record();
                    srr.srcount  = 1;
                    srr.srdate   = DateTime.Now;
                    srr.srname   = filename;
                    srr.srnum    = list.Count.ToString();
                    srr.srpath   = "~/OA/upload/shuadan/convert/" + filename;
                    srr.srremark = "";
                    srr.srstate  = "1";
                    srr.srtype   = "6";


                    Manager.FileDownload("~/OA/upload/shuadan/convert/" + filename, filename, srr);
                }
            }
        }
        catch (Exception ex)
        {
            Manager.Alert(ex.ToString(), page);
        }
    }
Ejemplo n.º 57
0
        public JsonResult UploadFileForm(FileUpload file)
        {
            Console.WriteLine("Hi from the controller!");
            Console.WriteLine("file1: " + file.FileName);
            Console.WriteLine("file2: " + file.UserID);
            Console.WriteLine("file3: " + file.isUserInputName);
            Console.WriteLine("file4: " + file.DestFolder);
            Console.WriteLine("file4: " + file.TaskID);

            Dictionary <string, object> result = new Dictionary <string, object>();

            if (ModelState.IsValid)
            {
                User user = repository.Users.Where(p => p.UserID == file.UserID).FirstOrDefault();

                string folderPath = "";
                if (String.IsNullOrEmpty(file.DestFolder))
                {
                    Console.WriteLine("hi im here");
                    folderPath = user.RootFolderLocation;
                }
                else
                {
                    Console.WriteLine("hi im here :(");
                    folderPath = file.DestFolder;
                }

                if (folderPath.LastIndexOf("/") != folderPath.Length - 1)
                {
                    folderPath += "/";
                }

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

                Console.WriteLine("folder " + folderPath);
                string fileName = file.isUserInputName ? file.FileName : Path.GetFileNameWithoutExtension(file.File.FileName);

                string filePath = folderPath + fileName + Path.GetExtension(file.File.FileName);

                Console.WriteLine("file " + filePath);

                if (!System.IO.File.Exists(filePath))
                {
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        file.File.CopyTo(fileStream);
                    }

                    Console.WriteLine("ovde");

                    if (file.TaskID != null)
                    {
                        Task     task     = this.taskRepository.Tasks.FirstOrDefault(t => t.TaskID == file.TaskID);
                        TaskFile taskFile = new TaskFile {
                            Task = task, FilePath = filePath
                        };
                        this.taskFileRepository.Save(taskFile);
                    }

                    result.Add("result", true);

                    return(Json(result));
                }
                else
                {
                    result.Add("result", false);
                    result.Add("error_code", 421);
                    result.Add("error_message", "file already exists");

                    return(Json(result));
                }
            }

            result.Add("result", false);
            result.Add("error_code", 1);
            result.Add("error_message", "form validation failed");

            return(Json(result));
        }
Ejemplo n.º 58
0
    private void FileUpLoadApp(string ChkType, FileUpload UpLoadBar, TextBox UpLoadText, string UpLoadStr, string UpLoadType, System.Web.UI.WebControls.Image UpLoadView, HyperLink UpLoadLink)
    {
        GBClass001 MyBassAppPj = new GBClass001();
        string     SwcFileName = "";
        string     CaseId      = LBSWC000.Text + "";

        if (UpLoadBar.HasFile)
        {
            string filename = UpLoadBar.FileName;   // UpLoadBar.FileName 只有 "檔案名稱.附檔名",並沒有 Client 端的完整理路徑

            string extension = Path.GetExtension(filename).ToLowerInvariant();

            // 判斷是否為允許上傳的檔案附檔名

            switch (ChkType)
            {
            case "PIC":
                List <string> allowedExtextsion01 = new List <string> {
                    ".jpg", ".png"
                };

                if (allowedExtextsion01.IndexOf(extension) == -1)
                {
                    error_msg.Text = MyBassAppPj.AlertMsg("請選擇 JPG PNG 檔案格式上傳,謝謝!!");
                    return;
                }
                break;

            case "DOC":
                List <string> allowedExtextsion02 = new List <string> {
                    ".xls", ".xlsx"
                };

                if (allowedExtextsion02.IndexOf(extension) == -1)
                {
                    error_msg.Text = MyBassAppPj.AlertMsg("請選擇 excel 檔案格式上傳,謝謝!!");
                    return;
                }
                break;
            }


            int filesize = UpLoadBar.PostedFile.ContentLength;

            switch (ChkType)
            {
            case "PIC":
                // 限制檔案大小,限制為 5MB
                if (filesize > 5000000)
                {
                    error_msg.Text = "請選擇 5Mb 以下檔案上傳,謝謝!!";
                    return;
                }
                break;

            case "DOC":
                // 限制檔案大小,限制為 50MB
                if (filesize > 50000000)
                {
                    error_msg.Text = "請選擇 50Mb 以下檔案上傳,謝謝!!";
                    return;
                }
                break;
            }

            // 檢查 Server 上該資料夾是否存在,不存在就自動建立
            string serverDir = ConfigurationManager.AppSettings["SwcFileTemp"] + CaseId;

            if (Directory.Exists(serverDir) == false)
            {
                Directory.CreateDirectory(serverDir);
            }

            Session[UpLoadStr] = "有檔案";
            //SwcFileName = CaseId + UpLoadType + System.IO.Path.GetExtension(UpLoadBar.FileName);
            SwcFileName     = Path.GetFileNameWithoutExtension(filename) + UpLoadType + System.IO.Path.GetExtension(UpLoadBar.FileName);
            UpLoadText.Text = SwcFileName;

            // 判斷 Server 上檔案名稱是否有重覆情況,有的話必須進行更名
            // 使用 Path.Combine 來集合路徑的優點
            //  以前發生過儲存 Table 內的是 \\ServerName\Dir(最後面沒有 \ 符號),
            //  直接跟 FileName 來進行結合,會變成 \\ServerName\DirFileName 的情況,
            //  資料夾路徑的最後面有沒有 \ 符號變成還需要判斷,但用 Path.Combine 來結合的話,
            //  資料夾路徑沒有 \ 符號,會自動補上,有的話,就直接結合

            string serverFilePath = Path.Combine(serverDir, SwcFileName);
            string fileNameOnly   = Path.GetFileNameWithoutExtension(SwcFileName);
            int    fileCount      = 1;

            //while (File.Exists(serverFilePath))
            //{
            //    // 重覆檔案的命名規則為 檔名_1、檔名_2 以此類推
            //    filename = string.Concat(fileNameOnly, "_", fileCount, extension);
            //    serverFilePath = Path.Combine(serverDir, filename);
            //    fileCount++;
            //}

            // 把檔案傳入指定的 Server 內路徑
            try
            {
                UpLoadBar.SaveAs(serverFilePath);
                //error_msg.Text = "檔案上傳成功";

                switch (ChkType)
                {
                case "PIC":
                    UpLoadView.Attributes.Add("src", "..\\UpLoadFiles\\temp\\" + CaseId + "\\" + SwcFileName + "?ts=" + System.DateTime.Now.Millisecond);
                    //UpLoadView.ImageUrl = "..\\UpLoadFiles\\temp\\" + CaseId +"\\"+ geohfilename;

                    imagestitch(UpLoadView, serverDir + "\\" + SwcFileName, 320, 180);
                    break;

                case "DOC":
                    UpLoadLink.Text        = SwcFileName;
                    UpLoadLink.NavigateUrl = "..\\UpLoadFiles\\temp\\" + CaseId + "\\" + SwcFileName + "?ts=" + System.DateTime.Now.Millisecond;
                    UpLoadLink.Visible     = true;
                    break;
                }
            }
            catch (Exception ex)
            {
                //error_msg.Text = "檔案上傳失敗";
            }
        }
        else
        {
            Session[UpLoadStr] = "";
        }
    }
Ejemplo n.º 59
0
    public string SendEmailWithOptionalAttachment(string to, string subject, string message, FileUpload fuAttachment)
    {
        try
        {
            string sendersEmailAddress  = new DtoAdminDetails().AdminEmail;
            string sendersEmailPassword = new DtoAdminDetails().AdminPassword;



            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl             = true;
            client.Timeout               = 10000000;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials           = new NetworkCredential(sendersEmailAddress, sendersEmailPassword);
            MailMessage msg = new MailMessage();
            msg.To.Add(to);
            msg.From    = new MailAddress(sendersEmailAddress);
            msg.Subject = subject;
            msg.Body    = message;


            if (fuAttachment.HasFile)
            {
                msg.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, fuAttachment.FileName));
            }


            client.Send(msg);

            return("Published successfully.");
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
            string temp = "Error : " + ex.Message;
            return(temp);
        }
    }
Ejemplo n.º 60
0
    public string UploadFile(FileUpload Fupload)
    {
        //文件上传
        string str_ParentFolder;
        string filename;

        str_ParentFolder = Server.MapPath(@"..\app_data\");
        /*判断是否更名*/
        filename = "zhuanjia.xls";
        try
        {
            //上传新的对应关系文件
            if (Fupload.PostedFile.FileName == "")
            {
                return("请选择要上传的数据!");
            }
            //创建文件夹
            if (!Directory.Exists(str_ParentFolder))
            {
                Directory.CreateDirectory(str_ParentFolder);
                if (!Directory.Exists(str_ParentFolder))
                {
                    return("创建文件夹失败!");
                }
            }
            if (Fupload.PostedFile.FileName != "")
            {
                string extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper();
                //判断上传类型
                string str_UploadFileType = "xls";

                if (str_UploadFileType.IndexOf(extname.ToLower()) == -1)
                {
                    return("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>");
                }
                Fupload.PostedFile.SaveAs(str_ParentFolder + filename);
            }
            string str_sql;
            str_sql = "select * from [sheet1$] ";
            DataTable dt = ExcelManager.GetXlsDataTable(str_ParentFolder + filename, str_sql);
            int       j = 0, k = 0;
            string    str_pwd;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                str_sql = "select count(*) from t_Expert where LoginName ='" + dt.Rows[i][0].ToString() + "'";
                str_pwd = dt.Rows[i][2].ToString();
                //如果密码为空,则设置登录名为密码
                if (str_pwd == "")
                {
                    str_pwd = dt.Rows[i][0].ToString();
                }

                str_pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str_pwd, "MD5");
                if ((int)DBFun.ExecuteScalar(str_sql) == 0)
                {
                    str_sql = string.Format("insert into t_Expert (LoginName,UserName,pwd,szbm,zc,jb,zy) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
                                            dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), str_pwd, dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString());
                    j++;
                }
                else
                {
                    str_sql = string.Format("update t_Expert set UserName='******',pwd='{2}',szbm='{3}',zc='{4}',jb='{5}',zy='{6}' where LoginName='{0}'",
                                            dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), str_pwd, dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString());
                    k++;
                }
                if (!DBFun.ExecuteUpdate(str_sql))
                {
                    return("系统错误");
                }
            }
            str_sql            = "select count(*) from t_Expert where LoginName is not null";
            lbl_result.Visible = true;
            lbl_result.Text    = "数据库中共有记录 " + DBFun.ExecuteScalar(str_sql).ToString() + " 条,本次新增了 " + j.ToString() + " 条记录,更新了 " + k.ToString() + " 条记录";
            Fupload.Dispose();
            //if (lbl_type.Text == "2")
            //{
            //    str_sql = " delete from zjry where flag = 2;";
            //    DBFun.ExecuteUpdate(str_sql);

            //    str_sql = " insert into zjry (flag,zj_sfzh,cpry_sfzh,fs_sftj) " +
            //              " select 2,pszj.sfzh,ej_cpry.sfzh,'false' from pszj,ej_cpry where pszj.flag = 2;";
            //    if (!DBFun.ExecuteUpdate(str_sql))
            //    {
            //        return "上传失败";
            //    }
            //}
            return("上传成功");
        }
        catch (IOException e)
        {
            return(e.Message);
        }
        catch (Exception e)
        {
            return(e.Message);
        }
    }