示例#1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DecodedData"/> class.
 /// </summary>
 public DecodedData()
 {
   Parameters = new ParameterCollection();
   Files = new HttpFileCollection();
 }
        public TradelanePackageDetailExcel GetPiecesDetailFromExcel()
        {
            TradelanePackageDetailExcel frayteShipmentDetailexcel = new TradelanePackageDetailExcel();
            var httpRequest = HttpContext.Current.Request;

            List <TradelanePackage> _shipmentdetail = new List <TradelanePackage>();

            if (httpRequest.Files.Count > 0)
            {
                HttpFileCollection files = httpRequest.Files;
                HttpPostedFile     file  = files[0];
                int ShipmentId           = Convert.ToInt32(httpRequest.Form["ShipmentId"].ToString());

                if (!string.IsNullOrEmpty(file.FileName))
                {
                    //int ShipmentId = Convert.ToInt32(httpRequest.Form["ShipmentId"].ToString());
                    string connString = "";
                    string filename   = DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss_") + file.FileName;
                    string filepath   = HttpContext.Current.Server.MapPath("~/UploadFiles/Tradelane/" + filename);
                    file.SaveAs(filepath);
                    connString = new DirectShipmentRepository().getExcelConnectionString(filename, filepath);

                    string fileExtension = "";
                    fileExtension = new DirectShipmentRepository().getFileExtensionString(filename);
                    try
                    {
                        if (!string.IsNullOrEmpty(fileExtension))
                        {
                            var ds = new DataSet();
                            if (fileExtension == FrayteFileExtension.CSV)
                            {
                                using (var conn = new OleDbConnection(connString))
                                {
                                    conn.Open();
                                    var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
                                    using (var adapter = new OleDbDataAdapter(query, conn))
                                    {
                                        adapter.Fill(ds, "Pieces");
                                    }
                                }
                            }
                            else
                            {
                                var excel        = new ExcelQueryFactory("excelFileName");
                                var oldCompanies = (from c in excel.Worksheet <TradelanePackage>("sheet1")
                                                    select c);

                                using (var conn = new OleDbConnection(connString))
                                {
                                    conn.Open();
                                    DataTable dbSchema       = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                                    string    firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
                                    var       query          = "SELECT * FROM " + "[" + firstSheetName + "]";
                                    using (var adapter = new OleDbDataAdapter(query, conn))
                                    {
                                        adapter.Fill(ds, "Pieces");
                                    }
                                }
                            }

                            var exceldata = ds.Tables[0];

                            // Step 1: Validate for excel column

                            string PiecesColumnList = "CartonNumber,CartonQTY,Length,Width,Height,Weight";
                            bool   IsExcelValid     = UtilityRepository.CheckUploadExcelFormat(PiecesColumnList, exceldata);
                            if (!IsExcelValid)
                            {
                                frayteShipmentDetailexcel.Message = "Columns are not matching with provided template columns. Please check the column names.";
                            }
                            else
                            {
                                if (exceldata.Rows.Count > 0)
                                {
                                    frayteShipmentDetailexcel.TotalUploaded = exceldata.Rows.Count;
                                    _shipmentdetail = new TradelaneBookingRepository().GetPiecesDetail(exceldata);
                                    frayteShipmentDetailexcel.Packages        = new List <TradelanePackage>();
                                    frayteShipmentDetailexcel.Packages        = _shipmentdetail;
                                    frayteShipmentDetailexcel.Message         = "OK";
                                    frayteShipmentDetailexcel.SuccessUploaded = _shipmentdetail.Count;
                                    new TradelaneBookingRepository().SavePackagedetailShipment(frayteShipmentDetailexcel.Packages, ShipmentId);
                                }
                                else
                                {
                                    frayteShipmentDetailexcel.Message = "No records found.";
                                }
                            }
                            if ((System.IO.File.Exists(filepath)))
                            {
                                System.IO.File.Delete(filepath);
                            }
                        }
                        else
                        {
                            frayteShipmentDetailexcel.Message = "Excel file not valid";
                        }
                    }
                    catch (Exception ex)
                    {
                        Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                        if (ex != null && !string.IsNullOrEmpty(ex.Message) && ex.Message.Contains("Sheet1$"))
                        {
                            frayteShipmentDetailexcel.Message = "Sheet name is invalid.";
                        }
                        else
                        {
                            frayteShipmentDetailexcel.Message = "Error while uploading the excel.";
                        }
                        return(frayteShipmentDetailexcel);
                    }
                }
            }
            return(frayteShipmentDetailexcel);
        }
示例#3
0
		private string UpdateFiles()
		{
			string text = "";
			HttpFileCollection files = HttpContext.Current.Request.Files;
			string text2 = DateTime.Now.ToString("yyMMdd");
			string text3 = base.Server.MapPath("~/Files/OfficeFiles/");
			string str = "~/Files/OfficeFiles/" + text2 + "/";
			text3 += text2;
			if (!Directory.Exists(text3))
			{
				FileSystemManager.CreateFolder(text2, base.Server.MapPath("~/Files/OfficeFiles"));
			}
			try
			{
				string str2 = "";
				if (this.Attachword.Visible)
				{
					foreach (RepeaterItem repeaterItem in this.rpt.Items)
					{
						HtmlInputCheckBox htmlInputCheckBox = repeaterItem.FindControl("chk") as HtmlInputCheckBox;
						if (htmlInputCheckBox.Checked)
						{
							str2 = str2 + htmlInputCheckBox.Value + "|";
						}
					}
				}
				for (int i = 0; i < files.Count; i++)
				{
					HttpPostedFile httpPostedFile = files[i];
					if (Config.IsValidFile(httpPostedFile))
					{
						string fileName = Path.GetFileName(httpPostedFile.FileName);
						string str3 = str + fileName;
						string text4 = text3 + "\\" + fileName;
						if (File.Exists(text4))
						{
							string text5 = string.Concat(new object[]
							{
								DateTime.Now.ToString("HHmmssfff"),
								Utils.CreateRandomStr(3),
								this.Uid,
								i
							});
							text4 = string.Concat(new string[]
							{
								text3,
								"\\",
								text5,
								"@",
								Utils.GetFileExtension(fileName)
							});
							str3 = str + text5 + "@" + Utils.GetFileExtension(fileName);
						}
						httpPostedFile.SaveAs(text4);
						text = text + str3 + "|";
					}
				}
				text = str2 + text;
			}
			catch (IOException ex)
			{
				throw;
			}
			return text;
		}
示例#4
0
        public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
        {
            if (ImageTitle == "")
            {
                throw new InvalidDataException("Image title is mandatory");
            }
            //IInformationObject container = sources.GetDefaultSource().RetrieveInformationObject();
            Image        image = Image.CreateDefault();
            VirtualOwner owner = VirtualOwner.FigureOwner(this);

            image.SetLocationAsOwnerContent(owner, image.ID);
            image.Title = ImageTitle;
            StorageSupport.StoreInformationMasterFirst(image, owner, true);
            DefaultViewSupport.CreateDefaultViewRelativeToRequester(requesterLocation, image, owner);
            return(true);
        }
        /// <summary>
        /// Send an email using default SMTP settings
        /// </summary>
        /// <param name="fromEmailAddress"></param>
        /// <param name="toEmailAddresses"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="ccEmailAddresses"></param>
        /// <param name="bccEmailAddresses"></param>
        /// <param name="isBodyHtml"></param>
        /// <param name="files"> Use Request.Files["filename"] to get file. Form needs to have enctype="multipart/form-data".</param>
        /// <param name="fromName">Display name</param>
        /// <param name="replyTo"></param>
        /// <param name="replyToName">Display name</param>
        public static void SendEmail(string fromEmailAddress, IEnumerable <string> toEmailAddresses, string subject, string body, IEnumerable <string> ccEmailAddresses = null, IEnumerable <string> bccEmailAddresses = null, bool isBodyHtml = false, HttpFileCollection files = null, string fromName = "", string replyTo = "", string replyToName = "")
        {
            var filesWrapper = new HttpFileCollectionWrapper(files);

            SendEmail(fromEmailAddress, toEmailAddresses, subject, body, ccEmailAddresses, bccEmailAddresses, isBodyHtml, filesWrapper, fromName, replyTo, replyToName);
        }
示例#6
0
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (img.PostedFile.ContentLength < 8388608)
            {
                try
                {
                    if (img.HasFile)
                    {
                        try
                        {
                            //Aqui ele vai filtrar pelo tipo de arquivo
                            if (img.PostedFile.ContentType == "image/jpeg" ||
                                img.PostedFile.ContentType == "image/jpg" ||
                                img.PostedFile.ContentType == "image/png" ||
                                img.PostedFile.ContentType == "image/gif" ||
                                img.PostedFile.ContentType == "image/bmp")
                            {
                                try
                                {
                                    //Obtem o  HttpFileCollection
                                    HttpFileCollection hfc = Request.Files;
                                    for (int i = 0; i < hfc.Count; i++)
                                    {
                                        HttpPostedFile hpf = hfc[i];
                                        if (hpf.ContentLength > 0)
                                        {
                                            //Pega o nome do arquivo
                                            string nome = Path.GetFileName(hpf.FileName);
                                            //Pega a extensão do arquivo
                                            string extensao = Path.GetExtension(hpf.FileName);
                                            //Gera nome novo do Arquivo numericamente
                                            string filename = string.Format("{0:00000000000000}", GerarID());
                                            //Caminho a onde será salvo
                                            hpf.SaveAs(Server.MapPath("~/dist/img/users/") + filename + i
                                                       + extensao);

                                            //Prefixo p/ img pequena
                                            var prefixoP = "-80x80";
                                            //Prefixo p/ img grande
                                            var prefixoG = "-160x160";

                                            //pega o arquivo já carregado
                                            string pth = Server.MapPath("~/dist/img/users/")
                                                         + filename + i + extensao;

                                            //Redefine altura e largura da imagem e Salva o arquivo + prefixo
                                            ImageResize.resizeImageAndSave(pth, 80, 80, prefixoP);
                                            ImageResize.resizeImageAndSave(pth, 160, 160, prefixoG);
                                            image = filename + i + prefixoG + extensao;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    mensagem = "Erro ao Fazer Upload da Imagem " + ex.Message;
                                    ClientScript.RegisterStartupScript(GetType(), "Popup", "NotificacaoErro();", true);
                                }
                                // Mensagem se tudo ocorreu bem
                                imgSel.ImageUrl    = "dist/img/users/" + image;
                                lblCaminhoImg.Text = image;
                                ClientScript.RegisterStartupScript(GetType(), "Popup", "uploadSucesso();", true);
                            }
                            else
                            {
                                // Mensagem notifica que é permitido carregar apenas
                                // as imagens definida la em cima.
                                mensagem = "É permitido carregar apenas imagens!";
                                ClientScript.RegisterStartupScript(GetType(), "Popup", "NotificacaoErro();", true);
                            }
                        }
                        catch (Exception ex)
                        {
                            // Mensagem notifica quando ocorre erros
                            mensagem = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                            ClientScript.RegisterStartupScript(GetType(), "Popup", "NotificacaoErro();", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Mensagem notifica quando ocorre erros
                    mensagem = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                    ClientScript.RegisterStartupScript(GetType(), "Popup", "NotificacaoErro();", true);
                }
            }
            else
            {
                // Mensagem notifica quando imagem é superior a 8 MB
                mensagem = "Não é permitido carregar mais do que 8 MB";
                ClientScript.RegisterStartupScript(GetType(), "Popup", "NotificacaoErro();", true);
            }
        }
示例#7
0
        public void AdReleaseAddList(HttpContext context)
        {
            int AdReleaseID  = 0;
            int AdPositionID = 0;
            int ResourceID   = 0;

            if (!string.IsNullOrEmpty(context.Request.Form["AdReleaseID"].ToString()))
            {
                AdReleaseID = Convert.ToInt32(context.Request.Form["AdReleaseID"].ToString());
            }
            if (!string.IsNullOrEmpty(context.Request.Form["AdPositionID"].ToString()))
            {
                AdPositionID = Convert.ToInt32(context.Request.Form["AdPositionID"].ToString());
            }

            var             objOrder     = GetParam("AdReleaseModel", context);
            AdReleaseBackup AdRelease    = JsonConvert.DeserializeObject <AdReleaseBackup>(objOrder.ToString());
            AdReleaseBLL    AdReleasebll = new AdReleaseBLL();

            //int result = 0;
            ////编辑
            //if (AdReleaseID > 0)
            //{
            //    if (AdRelease.BeginTime.ToString() != "" && AdRelease.EndTime.ToString() != "")
            //    {
            //        //AdRelease.ResourceInfo
            //        //result = AdReleasebll.Update(AdRelease) ? 1 : 0;
            //    }
            //}
            //else {

            if (AdRelease.BeginTime.ToString() != "" && AdRelease.EndTime.ToString() != "")
            {
                string             TPath    = "";
                byte[]             bytes    = null;
                string             fileName = "";
                HttpFileCollection hfColl   = context.Request.Files;
                HttpPostedFile     postFile = hfColl["FileLoad1"];
                if (postFile != null)
                {
                    int FileLen;
                    fileName = Path.GetFileName(postFile.FileName);
                    string fPath    = "/Resources/";
                    string basePath = HttpContext.Current.Server.MapPath(fPath);
                    // 存储路径规则:基础路径+日期(yyyyMMdd)+主键ID
                    TPath = DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
                    string fDir = basePath + TPath;
                    // 路径不存在的创建
                    if (!System.IO.Directory.Exists(basePath))
                    {
                        System.IO.Directory.CreateDirectory(basePath);
                    }

                    if (System.IO.File.Exists(fDir))
                    {
                        System.IO.File.Delete(fDir);
                    }


                    postFile.SaveAs(fDir);
                    FileLen = postFile.ContentLength;
                    bytes   = new byte[FileLen];
                }
                else
                {
                    ResourceID = AdRelease.ResourceID;
                }
                ResourceBLL ResourceAddbll = new ResourceBLL();
                string      msg            = "";
                bool        b = false;

                b = ResourceAddbll.ResourceAdd(ResourceID, AdPositionID, AdRelease, TPath, out msg, bytes, fileName);

                if (b)
                {
                    AdReleaseID = 1;
                }
            }
            ////}
            context.Response.Write(AdReleaseID);
        }
示例#8
0
        protected void UploadButton_Click(object sender, EventArgs e)
        {
            ///'遍历File表单元素
            HttpFileCollection files = HttpContext.Current.Request.Files;

            /// '状态信息
            System.Text.StringBuilder strMsg = new System.Text.StringBuilder("培训班为:" + qishu_dro.SelectedValue + "<br/>");
            strMsg.Append("上传的文件分别是:<hr color='red'/>");
            int count = 0;

            try
            {
                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    ///'检查文件扩展名字
                    HttpPostedFile postedFile = files[iFile];
                    string         fileName, fileExtension;
                    fileName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Today.GetDateTimeFormats('D')[0].ToString() + System.IO.Path.GetExtension(postedFile.FileName);
                    if (fileName != "")
                    {
                        fileExtension = System.IO.Path.GetExtension(fileName);

                        strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");
                        strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");
                        strMsg.Append("上传文件的文件名:" + fileName + "<br>");
                        strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");
                        ///'可根据扩展名字的不同保存到不同的文件夹
                        ///注意:可能要修改你的文件夹的匿名写入权限。
                        postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("../images/") + fileName);


                        System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Request.MapPath("../images/") + fileName);

                        string strName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Today.GetDateTimeFormats('D')[0].ToString() + "_small_" + System.IO.Path.GetExtension(postedFile.FileName);
                        //string strName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Today.GetDateTimeFormats('D')[0].ToString()  + System.IO.Path.GetExtension(postedFile.FileName);
                        string strResizePicName = System.Web.HttpContext.Current.Request.MapPath("../images/") + strName;
                        Maticsoft.BLL.photos ph = new BLL.photos();
                        string str = ph.photoscompress(imgPhoto, 400, 300, strResizePicName);
                        if (str == "保存成功")
                        {
                            Maticsoft.Model.photos ph_m = new Model.photos();
                            ph_m.ContentType        = postedFile.ContentType.ToString();
                            ph_m.postedFileFileName = postedFile.FileName;
                            ph_m.FileName           = strName;
                            ph_m.fileExtension      = fileExtension;
                            ph_m.qishu = qishu_dro.SelectedValue;
                            if (fenlei_txt.Text == "")
                            {
                                ph_m.fenlei2 = fenlei_dro.SelectedValue;
                            }
                            else
                            {
                                ph_m.fenlei2 = fenlei_txt.Text.Trim();
                            }
                            Maticsoft.BLL.photos pho = new BLL.photos();
                            count += pho.Add(ph_m);
                        }
                        else
                        {
                            strMsg.Append(str);
                        }
                    }
                }
                strMsg.Append("共上传图片" + count + "张");
                strStatus.Text = strMsg.ToString();
            }
            catch (System.Exception Ex)
            {
                strStatus.Text = Ex.Message;
            }
        }
        private void OnUpload(HttpContext context)
        {
            string errorMsg = "";

            try
            {
                int  effect              = 0;
                bool isCreateThumbnail   = ConfigHelper.GetValueByKey("IsCteateContentPictureThumbnail") == "1";
                UploadFilesHelper  ufh   = new UploadFilesHelper();
                HttpFileCollection files = context.Request.Files;
                foreach (string item in files.AllKeys)
                {
                    if (files[item] == null || files[item].ContentLength == 0)
                    {
                        continue;
                    }

                    string[]           paths   = ufh.Upload(files[item], "ContentPictures", isCreateThumbnail);
                    ContentPicture     ppBll   = new ContentPicture();
                    ContentPictureInfo ppModel = new ContentPictureInfo();

                    string originalPicturePath = "";
                    string bPicturePath        = "";
                    string mPicturePath        = "";
                    string sPicturePath        = "";
                    string otherPicturePath    = "";
                    for (int i = 0; i < paths.Length; i++)
                    {
                        switch (i)
                        {
                        case 0:
                            originalPicturePath = paths[i].Replace("~", "");
                            break;

                        case 1:
                            bPicturePath = paths[i].Replace("~", "");
                            break;

                        case 2:
                            mPicturePath = paths[i].Replace("~", "");
                            break;

                        case 3:
                            sPicturePath = paths[i].Replace("~", "");
                            break;

                        case 4:
                            otherPicturePath = paths[i].Replace("~", "");
                            break;

                        default:
                            break;
                        }
                    }
                    ppModel.OriginalPicture = originalPicturePath;
                    ppModel.BPicture        = bPicturePath;
                    ppModel.MPicture        = mPicturePath;
                    ppModel.SPicture        = sPicturePath;
                    ppModel.OtherPicture    = otherPicturePath;
                    ppModel.LastUpdatedDate = DateTime.Now;
                    ppBll.Insert(ppModel);
                    effect++;
                }

                if (effect == 0)
                {
                    context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}");
                    return;
                }

                context.Response.Write("{\"success\": true,\"message\": \"已成功上传文件数:" + effect + "个\"}");
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }

            if (errorMsg != "")
            {
                context.Response.Write("{\"success\": false,\"message\": \"" + errorMsg + "\"}");
            }
        }
示例#10
0
        static void SaveFiles(LoginUser loginUser, HttpContext context, AttachmentPath.Folder folder, int organizationID, int?itemID)
        {
            List <TeamSupport.Handlers.UploadResult> result = new List <TeamSupport.Handlers.UploadResult>();

            AttachmentProxy.References refType = AttachmentPath.GetFolderReferenceType(folder);

            string path = AttachmentPath.GetPath(LoginUser.Anonymous, organizationID, folder, 3);

            if (itemID != null)
            {
                path = Path.Combine(path, itemID.ToString());
            }
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            HttpFileCollection files = context.Request.Files;

            for (int i = 0; i < files.Count; i++)
            {
                if (files[i].ContentLength > 0)
                {
                    string fileName = TeamSupport.Handlers.UploadUtils.RemoveSpecialCharacters(DataUtils.VerifyUniqueUrlFileName(path, Path.GetFileName(files[i].FileName)));

                    files[i].SaveAs(Path.Combine(path, fileName));
                    if (refType != AttachmentProxy.References.None && itemID != null)
                    {
                        Attachment attachment = (new Attachments(loginUser)).AddNewAttachment();
                        attachment.RefType        = refType;
                        attachment.RefID          = (int)itemID;
                        attachment.OrganizationID = organizationID;
                        attachment.FileName       = fileName;
                        attachment.Path           = Path.Combine(path, fileName);
                        attachment.FileType       = files[i].ContentType;
                        attachment.FileSize       = files[i].ContentLength;
                        attachment.FilePathID     = 3;
                        if (context.Request.Form["description"] != null)
                        {
                            attachment.Description = context.Request.Form["description"].Replace("\n", "<br />");
                        }
                        if (context.Request.Form["productFamilyID"] != null && context.Request.Form["productFamilyID"] != "-1")
                        {
                            attachment.ProductFamilyID = Int32.Parse(context.Request.Form["productFamilyID"]);
                        }

                        attachment.Collection.Save();
                        result.Add(new TeamSupport.Handlers.UploadResult(fileName, attachment.FileType, attachment.FileSize, attachment.AttachmentID));
                    }
                    else
                    {
                        switch (refType)
                        {
                        default:
                            break;
                        }
                    }
                }
            }
            context.Response.Clear();
            context.Response.ContentType = "text/plain";
            context.Response.Write(DataUtils.ObjectToJson(result.ToArray()));
        }
示例#11
0
        public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
        {
            if (GroupName == "")
            {
                throw new InvalidDataException("Group name must be given");
            }
            //throw new NotImplementedException("Old implementation not converted to managed group structures");
            //AccountContainer container = (AccountContainer) sources.GetDefaultSource(typeof(AccountContainer).FullName).RetrieveInformationObject();
            VirtualOwner owner = VirtualOwner.FigureOwner(this);

            if (owner.ContainerName != "acc")
            {
                throw new NotSupportedException("Group creation only supported from account");
            }
            string         accountID   = owner.LocationPrefix;
            TBRAccountRoot accountRoot = TBRAccountRoot.RetrieveFromDefaultLocation(accountID);
            TBAccount      account     = accountRoot.Account;

            if (account.Emails.CollectionContent.Count == 0)
            {
                throw new InvalidDataException("Account needs to have at least one email address to create a group");
            }
            CreateGroup.Execute(new CreateGroupParameters {
                AccountID = accountID, GroupName = this.GroupName
            });
            this.GroupName = "";
            return(true);
        }
示例#12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            usuarioID = Convert.ToInt32(Request.QueryString["usuarioID"]);
            if (Session["logado"] == null)
            {
                Response.Redirect("login.aspx");
            }
            if (!Page.IsPostBack)
            {
                prevPage = Request.UrlReferrer.ToString();
                if (Session["perfil"].ToString() != "Administrador")
                {
                    ClientScript.RegisterStartupScript(GetType(), "Popup", "acessoNegado();", true);
                    Response.Redirect(prevPage);
                }

                secretaria = Session["secretaria"].ToString();

                // Metodo para popular a combobox
                string          conecLocal = "SERVER=10.0.2.9;UID=ura;PWD=ask123;Allow User Variables=True;Pooling=False";
                string          query;
                MySqlConnection con = new MySqlConnection(conecLocal);
                con.Open();
                if (secretaria == "1")
                {
                    query = "SELECT id, nome FROM sema.secretaria order by nome asc";
                }
                else
                {
                    query = "SELECT id, nome FROM sema.secretaria where id=" + Session["secretaria"].ToString() + " ORDER BY nome asc";
                }
                MySqlCommand     cmd = new MySqlCommand(query, con);
                MySqlDataAdapter da  = new MySqlDataAdapter();
                DataTable        dt  = new DataTable();
                da.SelectCommand = cmd;
                da.Fill(dt);

                cboxSecretaria.Items.Insert(0, new ListItem("Selecione", "selecione"));
                foreach (DataRow item in dt.Rows)
                {
                    cboxSecretaria.Items.Add(new ListItem(item["nome"].ToString(), item["id"].ToString()));
                }
                getUsuarios(usuarioID);
            }

            lblCaminhoImg.Visible = false;
            password = senha.Text;

            if (IsPostBack && img.PostedFile != null)
            {
                if (img.PostedFile.ContentLength < 8388608)
                {
                    try
                    {
                        if (img.HasFile)
                        {
                            try
                            {
                                //Aqui ele vai filtrar pelo tipo de arquivo
                                if (img.PostedFile.ContentType == "image/jpeg" ||
                                    img.PostedFile.ContentType == "image/jpg" ||
                                    img.PostedFile.ContentType == "image/png" ||
                                    img.PostedFile.ContentType == "image/gif" ||
                                    img.PostedFile.ContentType == "image/bmp")
                                {
                                    try
                                    {
                                        //Obtem o  HttpFileCollection
                                        HttpFileCollection hfc = Request.Files;
                                        for (int i = 0; i < hfc.Count; i++)
                                        {
                                            HttpPostedFile hpf = hfc[i];
                                            if (hpf.ContentLength > 0)
                                            {
                                                //Pega o nome do arquivo
                                                string nome = Path.GetFileName(hpf.FileName);
                                                //Pega a extensão do arquivo
                                                string extensao = Path.GetExtension(hpf.FileName);
                                                //Gera nome novo do Arquivo numericamente
                                                string filename = string.Format("{0:00000000000000}", GerarID());
                                                //Caminho a onde será salvo
                                                hpf.SaveAs(Server.MapPath("~/dist/img/users/") + filename + i
                                                           + extensao);

                                                //Prefixo p/ img pequena
                                                var prefixoP = "-80x80";
                                                //Prefixo p/ img grande
                                                var prefixoG = "-160x160";

                                                //pega o arquivo já carregado
                                                string pth = Server.MapPath("~/dist/img/users/")
                                                             + filename + i + extensao;

                                                //Redefine altura e largura da imagem e Salva o arquivo + prefixo
                                                ImageResize.resizeImageAndSave(pth, 80, 80, prefixoP);
                                                ImageResize.resizeImageAndSave(pth, 160, 160, prefixoG);
                                                image = filename + i + prefixoG + extensao;
                                            }
                                        }
                                    }
                                    catch (System.Exception ex)
                                    {
                                        mensagem = "Ocerreu o Seguinte erro: " + ex.Message;
                                        ClientScript.RegisterStartupScript(GetType(), "Popup", "erro();", true);
                                    }
                                    // Mensagem se tudo ocorreu bem
                                    imgSel.ImageUrl    = "dist/img/users/" + image;
                                    lblCaminhoImg.Text = image;
                                    mensagem           = "Upload da Imagem feito com Sucesso!!!";
                                    ClientScript.RegisterStartupScript(GetType(), "Popup", "sucesso();", true);
                                }
                                else
                                {
                                    // Mensagem notifica que é permitido carregar apenas
                                    // as imagens definida la em cima.
                                    mensagem = "É permitido carregar apenas imagens!";
                                    ClientScript.RegisterStartupScript(GetType(), "Popup", "erro();", true);
                                }
                            }
                            catch (System.Exception ex)
                            {
                                // Mensagem notifica quando ocorre erros
                                mensagem = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                                ClientScript.RegisterStartupScript(GetType(), "Popup", "erro();", true);
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        // Mensagem notifica quando ocorre erros
                        mensagem = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                        ClientScript.RegisterStartupScript(GetType(), "Popup", "erro();", true);
                    }
                }
                else
                {
                    // Mensagem notifica quando imagem é superior a 8 MB
                    mensagem = "Não é permitido carregar mais do que 8 MB";
                    ClientScript.RegisterStartupScript(GetType(), "Popup", "erro();", true);
                }
            }
            else
            {
                imgSel.ImageUrl    = "dist/img/users/user-160x160.png";
                lblCaminhoImg.Text = "user-160x160.png";
            }
        }
示例#13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["up"] != null)
        {
            HttpFileCollection files = Request.Files;
            if (files.Count == 0)
            {
                Response.Write("请选择要上传的文件");
            }
            else if (Request["kind"] == "img")
            {
                string dir   = Settings.BasePath + "upload\\images\\" + DateTime.Now.ToString("yyyyMM");
                string fname = dir + "\\" + DateTime.Now.ToString("ddhhmmss") + DateTime.Now.Millisecond.ToString();
                string fn    = files[0].FileName;
                fname += fn.Substring(fn.LastIndexOf("."));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                files[0].SaveAs(fname);

                script = "top.loat('" + fname.Replace(Settings.BasePath, Settings.BaseURL).Replace("\\", "/") + "');";
            }
            else if (Request["kind"] == "group")
            {
                string gid = Request["data"];

                string newpath = Server.MapPath("/upload/group/" + gid + ".jpg");
                string s       = newpath.Replace(".jpg", "-s.jpg");

                Tools.MakeThumbnail("", files[0].InputStream, newpath, bigWidth);
                Tools.MakeThumbnail("", files[0].InputStream, s, smallWidth);

                script = "top.loat();";
            }
            else
            {
                string newpath = Server.MapPath("/upload/photo/" + CKUser.Username + ".jpg");
                string b       = newpath.Replace(".jpg", "-b.jpg");
                string s       = newpath.Replace(".jpg", "-s.jpg");

                files[0].SaveAs(b);

                Stream imgStream = files[0].InputStream;

                Tools.MakeThumbnail("", imgStream, newpath, bigWidth);
                Tools.MakeThumbnail("", imgStream, s, smallWidth);

                System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream);
                if (img.Width < bigWidth + 30)
                {
                    script = "top.loat(false);";
                }
                else
                {
                    script = "top.loat(true);";
                }
            }
        }
        if (Request["cutimg"] != null)
        {
            int    x      = int.Parse(Request["x1"]);
            int    y      = int.Parse(Request["y1"]);
            int    width  = int.Parse(Request["x2"]) - x;
            int    height = int.Parse(Request["y2"]) - y;
            string b      = Server.MapPath("/upload/photo/" + CKUser.Username + "-b.jpg");
            string p      = b.Replace("-b.jpg", ".jpg");
            Tools.MakeThumbnail(b, p, x, y, width, height);
            IO.DeleteFile(b);
            Tools.MakeThumbnail(p, null, b.Replace("-b.jpg", "-s.jpg"), smallWidth);

            Response.Write("<img src='/upload/photo/" + CKUser.Username + ".jpg' />");
            Response.End();
        }
    }
示例#14
0
        protected void btnUpdItemsChck_Click(object sender, EventArgs e)
        {
            try
            {
                int    artId      = int.Parse(ListBox4.SelectedValue);
                string name       = updItemsName.Text;
                int    catArtId   = int.Parse(updItemsCatArt.SelectedItem.Value);
                string desc       = updItemsDesc.Text;
                int    supplierId = int.Parse(updItemsSupplier.SelectedItem.Value);
                int    price      = int.Parse(updItemsPrice.Text);

                if (name == "" || catArtId < 0 || desc == "" || supplierId < 0 || price < 0)
                {
                    throw new System.ArgumentException("Nepotpuni podaci ili namerna greška");
                }

                cmd = new SqlCommand("EXECUTE updArt @artId,@name, @catArtId, @desc, @supplierId, @price", conn);
                cmd.Parameters.AddWithValue("@artId", artId);
                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@catArtId", catArtId);
                cmd.Parameters.AddWithValue("@desc", desc);
                cmd.Parameters.AddWithValue("@supplierId", supplierId);
                cmd.Parameters.AddWithValue("@price", price);

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

                cmd.Parameters.Clear();

                /*Uzimanje rednog broja artikla u kategoriji*/
                cmd.CommandText = "EXECUTE getItemPicPath @itemId";
                cmd.Parameters.AddWithValue("@itemId", artId);

                conn.Open();
                int redni = int.Parse(cmd.ExecuteScalar().ToString());
                conn.Close();

                /*Pravljenje putanje*/
                string kategorija = newItemsCatArt.SelectedItem.Text;

                string pathItem = (Server.MapPath("~") + "\\Images\\Kategorija\\" + kategorija + "\\" + redni + "");

                //SELEKTOVANJE SLIKA - za UPDATE NIJE NUZAN PA JE STOGA PRAZAN CATCH
                try
                {
                    HttpFileCollection slikeUpload = Request.Files;

                    for (int i = 0; i < slikeUpload.Count; i++)
                    {
                        HttpPostedFile userPostedFile = slikeUpload[i];

                        /*Dodavanje slika*/
                        int    brojSlika = Directory.GetFiles(pathItem + "\\", "*.png").Length;
                        string naziv     = (brojSlika + 1).ToString();

                        string fileExt = System.IO.Path.GetExtension(fileUploadUpd.FileName).ToString().ToLower();
                        userPostedFile.SaveAs(pathItem + @"\" + naziv + fileExt);
                    }
                }
                catch (Exception)
                {
                }

                Response.Redirect("Podesavanja.aspx");
            }
            catch (Exception)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "neispravan();", true);
            }
        }
示例#15
0
        private static void SaveFilesOld(LoginUser loginUser, int organizationID, int?_id, string _ratingImage, HttpContext context, AttachmentPath.Folder folder)
        {
            StringBuilder builder = new StringBuilder();
            string        path    = AttachmentPath.GetPath(loginUser, organizationID, folder);

            if (_id != null)
            {
                path = Path.Combine(path, _id.ToString());
            }
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            HttpFileCollection files = context.Request.Files;

            for (int i = 0; i < files.Count; i++)
            {
                if (files[i].ContentLength > 0)
                {
                    string fileName = TeamSupport.Handlers.UploadUtils.RemoveSpecialCharacters(DataUtils.VerifyUniqueUrlFileName(path, Path.GetFileName(files[i].FileName)));
                    if (builder.Length > 0)
                    {
                        builder.Append(",");
                    }
                    builder.Append(fileName);

                    if (_ratingImage != "")
                    {
                        fileName = _ratingImage + ".png";
                        AgentRatingsOptions ratingoptions = new AgentRatingsOptions(loginUser);
                        ratingoptions.LoadByOrganizationID(organizationID);

                        if (ratingoptions.IsEmpty)
                        {
                            AgentRatingsOption opt = (new AgentRatingsOptions(loginUser)).AddNewAgentRatingsOption();
                            opt.OrganizationID = organizationID;
                            switch (_ratingImage)
                            {
                            case "ratingpositive":
                                opt.PositiveImage = "/dc/" + organizationID + "/agentrating/ratingpositive";
                                break;

                            case "ratingneutral":
                                opt.NeutralImage = "/dc/" + organizationID + "/agentrating/ratingneutral";
                                break;

                            case "ratingnegative":
                                opt.NegativeImage = "/dc/" + organizationID + "/agentrating/ratingnegative";
                                break;
                            }
                            opt.Collection.Save();
                        }
                        else
                        {
                            switch (_ratingImage)
                            {
                            case "ratingpositive":
                                ratingoptions[0].PositiveImage = "/dc/" + organizationID + "/agentrating/ratingpositive";
                                break;

                            case "ratingneutral":
                                ratingoptions[0].NeutralImage = "/dc/" + organizationID + "/agentrating/ratingneutral";
                                break;

                            case "ratingnegative":
                                ratingoptions[0].NegativeImage = "/dc/" + organizationID + "/agentrating/ratingnegative";
                                break;
                            }
                            ratingoptions[0].Collection.Save();
                        }
                    }

                    fileName = Path.Combine(path, fileName);
                    files[i].SaveAs(fileName);
                }
            }
            context.Response.Write(builder.ToString());
        }
示例#16
0
        public object ImportPersonalfileExcel()
        {
            string             Message = string.Empty;
            string             Error   = string.Empty;
            HttpFileCollection files   = System.Web.HttpContext.Current.Request.Files;

            if (files.Count > 0)
            {
                var    file = files[0];
                string dir  = HttpContext.Current.Server.MapPath("/Temp");
                if (Directory.Exists(dir) == false)
                {
                    Directory.CreateDirectory(dir);
                }
                string filePath = Path.Combine(dir, Guid.NewGuid().ToString() + file.FileName);
                file.SaveAs(filePath);
                List <string> sheetNames = ExcelReader.GetExcelSheetName(filePath);
                DataTable     dt         = ExcelReader.GetExcelContext(filePath, "基础数据$");
                if (dt != null && dt.Rows.Count > 0)
                {
                    List <personalfiles> lstInsertFiles = new List <personalfiles>();
                    List <personalfiles> lstUpdateFiles = new List <personalfiles>();
                    int index = 0;
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row[0] == null || row[0].ToString() == "")
                        {
                            continue;
                        }
                        try
                        {
                            personalfiles personalfiles = new personalfiles()
                            {
                                Name          = row[0].ToString(),
                                Company       = row[1].ToString(),
                                Department    = row[2].ToString(),
                                Duty          = row[3].ToString(),
                                Level         = row[4].ToString(),
                                BrithDate     = DateTime.Parse(row[5].ToString()),
                                Age           = int.Parse(row[6].ToString()),
                                EnlistedDate  = DateTime.Parse(row[7].ToString()),
                                PoliticalFace = row[8].ToString(),
                                Education     = row[9].ToString(),
                                Nation        = row[10].ToString(),
                                NavtivePlace  = row[11].ToString(),
                                Height        = double.Parse(row[12].ToString()),
                                Weight        = int.Parse(row[13].ToString()),
                                Bust          = int.Parse(row[14].ToString()),
                                Waist         = int.Parse(row[15].ToString()),
                                BMI           = double.Parse(row[16].ToString()),
                                PBF           = double.Parse(row[17].ToString()),
                                ModyfiedDate  = DateTime.Now
                            };
                            //姓名年龄一致判断为重复数据,更新
                            personalfiles temp = personalfilesManager.GetList(t => t.Name == personalfiles.Name && t.Age.Value == personalfiles.Age.Value).FirstOrDefault();
                            if (temp == null)
                            {
                                personalfiles.Create();
                                personalfiles.CreateDate = DateTime.Now;
                                lstInsertFiles.Add(personalfiles);
                            }
                            else
                            {
                                personalfiles.Guid = temp.Guid;
                                lstUpdateFiles.Add(personalfiles);
                            }
                            index++;
                        }
                        catch (Exception ex)
                        {
                            Error += $"导入第{index}行数据异常:{ex.Message}";
                            Error += Environment.NewLine;
                        }
                    }
                    if (lstInsertFiles.Count > 0)
                    {
                        personalfilesManager.Insert(lstInsertFiles);
                    }
                    if (lstUpdateFiles.Count > 0)
                    {
                        personalfilesManager.Update(lstUpdateFiles);
                    }
                    Message = $"导入成功,新增人员信息{lstInsertFiles.Count}条,更新人员信息{lstUpdateFiles.Count}条";
                }
                else
                {
                    Error += "模板中未找到人员信息";
                }
            }
            else
            {
                Error = "请求参数错误!";
                throw new ArgumentNullException(typeof(HttpPostedFile).Name);
            }
            return(new
            {
                Message = Message,
                Error = Error
            });
        }
示例#17
0
        public JsonResult <object> UploadFile()
        {
            var                baseInfo  = GetBaseInfo();
            List <string>      listPath  = new List <string>();
            HttpFileCollection filelist  = HttpContext.Current.Request.Files;
            var                Authority = System.Web.HttpContext.Current.Request.Url.Authority;
            string             localhost = System.AppDomain.CurrentDomain.BaseDirectory;

            if (filelist != null && filelist.Count > 0)
            {
                for (int i = 0; i < filelist.Count; i++)
                {
                    HttpPostedFile file        = filelist[i];
                    String         Tpath       = DateTime.Now.ToString("yyyy-MM-dd");
                    string         filename    = file.FileName;
                    string         fileSuffix  = file.FileName.Split('.').Last().ToLower();
                    string         fileName    = Guid.NewGuid().ToString().Replace("-", "");
                    string         FilePath    = "\\Content\\File\\" + fileSuffix + "\\" + Tpath + "\\";
                    string         savePath    = localhost + FilePath;
                    string         servicePath = "/" + (FilePath + fileName + "." + fileSuffix).Replace("\\", "/");
                    //目录是否存在
                    Directory.CreateDirectory(savePath);
                    try
                    {
                        file.SaveAs(savePath + fileName + "." + fileSuffix);
                        listPath.Add(servicePath);


                        FileInfoDomain domain = new FileInfoDomain();
                        domain.FileName   = fileName;
                        domain.FilePath   = servicePath;
                        domain.FileSuffix = fileSuffix;
                        if (fileSuffix == "jpg" || fileSuffix == "webp" || fileSuffix == "jpeg" || fileSuffix == "bmp")
                        {
                            domain.FileType = FileTypeEnumDomain.图片;
                        }
                        else if (fileSuffix == "mp4" || fileSuffix == "avi" || fileSuffix == "wmv")
                        {
                            domain.FileType = FileTypeEnumDomain.视频;
                        }
                        else
                        {
                            domain.FileType = FileTypeEnumDomain.其他;
                        }
                        domain.CreateTime = DateTime.Now;
                        domain.ID         = Guid.NewGuid();
                        domain.UID        = baseInfo.UID;
                        _fileInfoService.NewCreate(domain);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("上传文件写入失败:" + ex.Message);
                    }
                }
            }
            else
            {
                throw new Exception("上传的文件信息不存在! ");
            }

            return(JsonNet(listPath));
        }
示例#18
0
        public void UploadFiles(Page page)
        {
            string filename = string.Empty; string lastItem = string.Empty;

            string[] arr = null; string[] separators = { "\\" }; string ID = string.Empty;



            HttpFileCollection fileCollection = basepage.Request.Files;

            //NetworkCredential NCredentials = new NetworkCredential(ShareLocationUserName, ShareLocationPassword, ShareLocationDomain);

            //using (new NetworkConnection(ShareFolderPath, NCredentials))

            ////using (new ImpersonatedUser(ShareLocationUserName, ShareLocationDomain, ShareLocationPassword))

            //{

            //  DriveMapping.DelDrive("i:", 0, true);
            //DriveMapping.MapDrive(@"\\10.138.74.233\c$\MaqasaAttachmentDocumentUpload", "Y:", @"agilityindia\tmurugesan", "mugil#2302");

            /// using (new NetworkConnection(@"\\server2\write", writeCredentials))

            ImpersonateUser     iU            = new ImpersonateUser();
            string              sPwd          = "";
            SymmetricEncryption CgServices    = ServiceFactory.GetSymmetricEncryptionInstance();;

            sPwd = CgServices.DecryptData(ConfigurationSettings.AppSettings["ShareLocationPassword"].ToString());
            iU.Impersonate(ConfigurationSettings.AppSettings["ShareLocationDomain"].ToString(), ConfigurationSettings.AppSettings["ShareLocationUserName"], sPwd);

            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile uploadfile = fileCollection[i];

                if (uploadfile.ContentLength > 0)
                {
                    if (uploadfile.ContentLength >= FileUploadSizeInKB)
                    {
                        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", "alert('you cannot upload files more than 1MB');", true);
                        //return;
                        filename = uploadfile.FileName;
                        arr      = filename.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                        lastItem = arr[arr.Length - 1];
                        if (Language == "ara")
                        {
                            lblMessage.Text = "أقصى حجم للملفات التي يمكن تحميلها هو 500 كيلوبايت. حجم الملف أكبر من 500 كيلوبايت." + " " + lastItem;
                        }
                        else
                        {
                            lblMessage.Text = lblMessage.Text + lastItem + " " + "Size is too large. Maximum file size of 500 KB is allowed." + " <br/>";
                        }
                        // return;
                    }
                    else
                    {
                        ID = GetNewID("MaqasaDocuments");
                        string fileName     = Path.GetFileName(uploadfile.FileName);
                        string GetFileName  = Path.GetFileNameWithoutExtension(uploadfile.FileName);
                        string GetExtension = Path.GetExtension(uploadfile.FileName);

                        string Date             = DateTime.Now.ToString("yyyy-MM-dd") + "\\" + ParentId;
                        string FullfileName     = GetFileName + ID + GetExtension;
                        string FullPathFileName = Date + "\\" + FullfileName;

                        ShareFolderPath = ShareFolderPath + "\\" + Date;
                        if (!Directory.Exists(ShareFolderPath))
                        {
                            Directory.CreateDirectory(ShareFolderPath);
                        }
                        string strpath = ShareFolderPath + "\\" + FullfileName;
                        uploadfile.SaveAs(strpath);


                        //byte[] buffer = new byte[uploadfile.ContentLength];
                        //uploadfile.InputStream.Read(buffer, 0, uploadfile.ContentLength);



                        //string contentType = uploadfile.ContentType;
                        //Stream FileStream = uploadfile.InputStream;
                        //BinaryReader br = new BinaryReader(FileStream);
                        //byte[] myData = br.ReadBytes((Int32)FileStream.Length);
                        //// byte[] myData = new byte[uploadfile.ContentLength];

                        string query = "insert into " + ProfileName + " (" + TablePrimaryKey + ",DocumentName,ReferenceId,NewFileName,StateId,Description,DateCreated,ReferenceType,MaqasaDocumentType) values (@DocumentId,@DocumentName, @ReferenceId, @NewFileName,@StateId,@Description,@DateCreated,@ReferenceType,@MaqasaDocumentType)";

                        SqlParameter[] commandParameters = new SqlParameter[9];
                        commandParameters[0] = new SqlParameter();
                        commandParameters[0].ParameterName = TablePrimaryKey;
                        commandParameters[0].Value         = ID;

                        commandParameters[1] = new SqlParameter();
                        commandParameters[1].ParameterName = "@DocumentName";
                        commandParameters[1].Value         = fileName;

                        commandParameters[2] = new SqlParameter();
                        commandParameters[2].ParameterName = "@ReferenceId";
                        commandParameters[2].Value         = ReferenceId;

                        commandParameters[3] = new SqlParameter();
                        commandParameters[3].ParameterName = "@NewFileName";
                        commandParameters[3].Value         = FullPathFileName;

                        commandParameters[4] = new SqlParameter();
                        commandParameters[4].ParameterName = "@StateId";
                        commandParameters[4].Value         = ProfileName + "CreatedState";

                        commandParameters[5] = new SqlParameter();
                        commandParameters[5].ParameterName = "@Description";
                        commandParameters[5].Value         = ((TextBox)page.FindControl("txtDescription")).Text;

                        commandParameters[6] = new SqlParameter();
                        commandParameters[6].ParameterName = "@DateCreated";
                        commandParameters[6].Value         = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");

                        commandParameters[7] = new SqlParameter();
                        commandParameters[7].ParameterName = "@ReferenceType";
                        commandParameters[7].Value         = ReferenceType;

                        commandParameters[8] = new SqlParameter();
                        commandParameters[8].ParameterName = "@MaqasaDocumentType";
                        commandParameters[8].Value         = Convert.ToInt32(ddlDocumentTypes.SelectedValue);

                        SQLDataAccessHelper.Instance.ExecuteNonQuery(CommandType.Text, query, commandParameters);

                        //string constr = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
                        //using (SqlConnection con = new SqlConnection(constr))
                        //{
                        //    //Commented by subramanyam for adding MaqasaDocumentType column
                        //    //string query = "insert into " + ProfileName + " (" + TablePrimaryKey + ",DocumentName,ReferenceId,NewFileName,StateId,Description,DateCreated,ReferenceType) values (@DocumentId,@DocumentName, @ReferenceId, @NewFileName,@StateId,@Description,@DateCreated,@ReferenceType)";
                        //string query = "insert into " + ProfileName + " (" + TablePrimaryKey + ",DocumentName,ReferenceId,NewFileName,StateId,Description,DateCreated,ReferenceType,MaqasaDocumentType) values (@DocumentId,@DocumentName, @ReferenceId, @NewFileName,@StateId,@Description,@DateCreated,@ReferenceType,@MaqasaDocumentType)";
                        //using (SqlCommand cmd = new SqlCommand(query))
                        //{
                        //    cmd.Connection = con;
                        //    cmd.Parameters.AddWithValue(TablePrimaryKey, ID);
                        //    cmd.Parameters.AddWithValue("@DocumentName", fileName);
                        //    cmd.Parameters.AddWithValue("@ReferenceId", ReferenceId);
                        //    cmd.Parameters.AddWithValue("@NewFileName", FullPathFileName);
                        //    cmd.Parameters.AddWithValue("@StateId", ProfileName + "CreatedState");
                        //    cmd.Parameters.AddWithValue("@Description", ((TextBox)page.FindControl("txtDescription")).Text);
                        //    cmd.Parameters.AddWithValue("@DateCreated", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                        //    cmd.Parameters.AddWithValue("@ReferenceType", ReferenceType);
                        //    //Added by subramanyam
                        //    cmd.Parameters.AddWithValue("@MaqasaDocumentType", Convert.ToInt32(ddlDocumentTypes.SelectedValue));
                        //    con.Open();
                        //    cmd.ExecuteNonQuery();
                        //    con.Close();
                        //}
                        //}
                    }
                }
                else
                {
                    filename = uploadfile.FileName;
                    arr      = filename.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    lastItem = arr[arr.Length - 1];
                    if (Language == "ara")
                    {
                        lblMessage.Text = lblMessage.Text + lastItem + " " + "الملف فارغ" + " <br/>";
                    }
                    else
                    {
                        lblMessage.Text = lblMessage.Text + lastItem + " " + "file is empty" + " <br/>";
                    }
                    //return;
                    //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", "alert('you did not specify a file to upload?');", true);
                    //return;
                }
            }

            iU.Undo();

            //}
            TextBox stxtDescription = ((TextBox)page.FindControl("txtDescription"));

            stxtDescription.Text           = "";
            ddlDocumentTypes.SelectedIndex = 0;
            BindGrid(GridView1);
        }
        public Dap.RESULT Upload(Guid userId, string grade, string clas, string type, string form, string discipline)
        {
            if (string.IsNullOrEmpty(grade))
            {
                throw new ArgumentException("message", nameof(grade));
            }

            if (string.IsNullOrEmpty(clas))
            {
                throw new ArgumentException("message", nameof(clas));
            }

            if (string.IsNullOrEmpty(form))
            {
                throw new ArgumentException("message", nameof(form));
            }

            if (string.IsNullOrEmpty(discipline))
            {
                throw new ArgumentException("message", nameof(discipline));
            }

            Dap.RESULT result = new Dap.RESULT();
            try
            {
                HttpRequest        request = HttpContext.Current.Request;
                HttpFileCollection files   = request.Files;

                if (files.Count > 0)
                {
                    HttpPostedFile hpf = files[0];

                    //资源放入以上传者命名的文件夹
                    string folder = System.Web.HttpContext.Current.Server.MapPath(".\\" + userId.ToString()); //文件保存路径
                    string name, fileName, extname = Path.GetExtension(hpf.FileName);                         //分别为包括后缀名的文件名,不包括后缀名的文件名、后缀名

                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    name     = hpf.FileName.Substring(hpf.FileName.LastIndexOf("\\") + 1);
                    fileName = hpf.FileName.Substring(hpf.FileName.LastIndexOf("\\") + 1, (hpf.FileName.LastIndexOf(".") - hpf.FileName.LastIndexOf("\\") - 1));
                    //fileName = DateTime.Now.Ticks.ToString() +  extname;

                    hpf.SaveAs(folder + "\\" + name);
                    result.result = fileName;//上传成功返回文件名。
                    using (DataContext dc = new DataContext(Dap.common.conn))
                    {
                        var             tb        = dc.GetTable <Models.Resource>();
                        Models.Resource _resource = new Models.Resource();
                        _resource.Name         = fileName;
                        _resource.Size         = (int)Math.Ceiling((hpf.ContentLength) / 1024m);
                        _resource.UploadUserID = userId;
                        _resource.Grades       = grade;
                        _resource.Clas         = clas;
                        _resource.Type         = type;
                        _resource.Form         = form;
                        _resource.Suffix       = extname;//后缀名
                        _resource.ID           = Guid.NewGuid();
                        _resource.Discipline   = discipline;
                        _resource.CreateTime   = DateTime.Now.ToString("d");//时间以xx-x-x形式显示
                        tb.InsertOnSubmit(_resource);
                        dc.SubmitChanges();
                    }
                }
                else
                {
                    result.state = false;
                    result.msg   = "请先选择需要上传的文件。";
                }
            }
            catch (Exception e)
            {
                result.state = false;
                result.msg   = e.Message;
            }
            return(result);
        }
示例#20
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="httpMethod">Method like <c>POST</c>.</param>
 /// <param name="pathAndQuery">Absolute path and query string (if one exist)</param>
 /// <param name="httpVersion">HTTP version like <c>HTTP/1.1</c></param>
 public HttpRequest(string httpMethod, string pathAndQuery, string httpVersion) : base(httpMethod, pathAndQuery, httpVersion)
 {
     Form    = new ParameterCollection();
     Files   = new HttpFileCollection();
     Cookies = new HttpCookieCollection <IHttpCookie>();
 }
示例#21
0
        public void ProcessRequest(HttpContext context)
        {
            HttpFileCollection uploadedFiles = context.Request.Files;
            var path = string.Empty;

            // actual info: we handle one file
            if (uploadedFiles.Count == 1)
            {
                var postedFile = uploadedFiles[0];
                var parentId   = HttpContext.Current.Request.Form[ParentIdRequestParameterName];

                if (String.IsNullOrEmpty(parentId))
                {
                    parentId = TryToGetParentId(context);
                }

                if (!String.IsNullOrEmpty(parentId))
                {
                    IFolder parentNode   = null;
                    var     parentNodeId = Convert.ToInt32(parentId);
                    parentNode = parentNodeId == 0 ? Repository.Root : Node.LoadNode(parentNodeId) as IFolder;

                    if (parentNode != null)
                    {
                        string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                        path = RepositoryPath.Combine((parentNode as Node).Path, fileName);
                        //PathInfoRemove:
                        //object t = RepositoryPathInfo.GetPathInfo(path);
                        var contentType = UploadHelper.GetContentType(postedFile.FileName, ContentType);
                        var t           = NodeHead.Get(path);
                        if (t == null)
                        {
                            if (!String.IsNullOrEmpty(contentType))
                            {
                                CreateSpecificContent(context, contentType, parentNode, postedFile);
                            }
                            else
                            {
                                SaveNewFile(context, postedFile, parentNode, path);
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(contentType))
                            {
                                ModifySpecificContent(parentNode, postedFile, path);
                            }
                            else
                            {
                                ModifyFile(context, postedFile, parentNode, path);
                            }
                        }
                    }
                    else
                    {
                        this.SetError(context, String.Format("Couldn't find parent node with {0} id.", parentId), 500);
                    }
                }
                else
                {
                    this.SetError(context, "Post parameter error: ParentId is null or empty!", 500);
                }
            }

            var backUrl = PortalContext.Current.BackUrl;

            if (!String.IsNullOrEmpty(backUrl))
            {
                context.Response.Redirect(backUrl);
            }

            // everything's fine
            context.Response.StatusCode = 200;
            context.Response.Write(Environment.NewLine);
            context.Response.End();
        }
示例#22
0
        public List <int> UploadMealPhotos(HttpFileCollection hfc, int mealId, int userId)
        {
            List <int> photoIds = null;

            AmazonS3Client client = new AmazonS3Client(_siteConfigService.AwsAccessKey, _siteConfigService.AwsSecretKey, Amazon.RegionEndpoint.USWest2);

            TransferUtility fileTransferUtility = new TransferUtility(client);

            List <string> photoFiles = null;

            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName  = ExistingBucketName,
                    InputStream = hpf.InputStream,  //where you get the stream
                    Key         = KeyName + "/" + Guid.NewGuid().ToString() + Path.GetFileName(hpf.FileName),
                };

                fileTransferUtility.Upload(fileTransferUtilityRequest);

                if (photoFiles == null)
                {
                    photoFiles = new List <string>();
                }

                photoFiles.Add(fileTransferUtilityRequest.Key);
            }

            Action <SqlParameterCollection> inputParamDelegate = delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@MealId", mealId);
                paramCollection.AddWithValue("@UserId", userId);


                SqlParameter filesParam = new SqlParameter("@Files", SqlDbType.Structured);

                if (photoFiles != null && photoFiles.Any())
                {
                    NVarcharTable fileNames = new NVarcharTable(photoFiles);
                    filesParam.Value = fileNames;
                }

                paramCollection.Add(filesParam);
            };

            Action <IDataReader, short> singleRecMapper = delegate(IDataReader reader, short set)
            {
                if (photoIds == null)
                {
                    photoIds = new List <int>();
                }

                photoIds.Add(reader.GetSafeInt32(0));
            };

            _dataProvider.ExecuteCmd("dbo.Files_MealsPhoto_Insert", inputParamDelegate, singleRecMapper);

            return(photoIds);
        }
示例#23
0
文件: Upload.aspx.cs 项目: XJHSG/SEST
    protected void Page_Load(object sender, EventArgs e)
    {
        UserID = Session["UserID"].ToString();
        string             _targDir       = DateTime.Now.ToString("yyyyMM");
        string             basePath       = Server.MapPath("~/upload/" + _targDir);
        string             FileNames      = "";
        HttpFileCollection files          = System.Web.HttpContext.Current.Request.Files;
        string             allowExtension = ConfigurationManager.AppSettings["PhotoExtension"].ToString();

        //产生随机四位数
        //Random rdm = new Random();
        //int a = rdm.Next(1000, 9999);

        //如果目录不存在,则创建目录
        if (files != null)
        {
            if (!Directory.Exists(basePath))
            {
                //创建文件夹
                Directory.CreateDirectory(basePath);
            }

            for (int i = 0; i < files.Count; i++)
            {
                //文件原名称
                string OldFileName = files[i].FileName;
                //文件大小(字节为单位)
                int    Size = files[i].ContentLength;
                string size;
                if (Size > 1024)
                {
                    Size /= 1024;
                    size  = Size.ToString();
                }
                else
                {
                    size = "0";
                }
                string fileSize = size;
                //文件后缀名
                string Extentsion = Path.GetExtension(files[i].FileName).ToLower();
                //自动命名文件名称
                string fileName = UserID + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + new Random().Next(1000, 10000).ToString() + Extentsion;
                FileNames += "," + fileName;
                string FT = Extentsion.Substring(1);
                //文件上传保存物理路径
                string filePath = "upload" + "/" + _targDir + "/" + fileName;
                //文件类型  FileType

                using (SqlConnection conn = new DB().GetConnection())
                {
                    SqlCommand cmd = conn.CreateCommand();
                    conn.Open();
                    cmd.CommandText = "select * from ResourceTypes where Extension=@Extension";
                    cmd.Parameters.AddWithValue("@Extension", FT);
                    SqlDataReader rd = cmd.ExecuteReader();
                    if (rd.Read())
                    {
                        Label1.Text = rd["TypeName"].ToString();
                    }

                    rd.Close();
                    conn.Close();
                }
                String fileType = Label1.Text;


                //写入文件
                files[i].SaveAs(basePath + "/" + fileName);
                string fileXltPath  = "";
                string fileXltPath3 = "";

                if (allowExtension.Contains(Extentsion))
                {
                    System.IO.Stream     oStream = files[i].InputStream;
                    System.Drawing.Image oImage  = System.Drawing.Image.FromStream(oStream);
                    int oWidth   = oImage.Width;  //原图宽度
                    int oHeight  = oImage.Height; //原图高度
                    int tWidth   = 600;           //设置缩略图初始宽度
                    int t2Height = 150;
                    int t2Width  = 200;
                    int tHeight  = 300; //设置缩略图初始高度
                    //按比例计算出缩略图的宽度和高度
                    if (oWidth >= oHeight)
                    {
                        tHeight  = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                        t2Height = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(t2Width) / Convert.ToDouble(oWidth)));
                    }
                    else
                    {
                        tWidth  = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                        t2Width = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(t2Height) / Convert.ToDouble(oHeight)));
                    }

                    if (oWidth >= 600)
                    {
                        //生成缩略原图
                        Bitmap   tImage = new Bitmap(tWidth, tHeight);
                        Graphics g      = Graphics.FromImage(tImage);
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;    //设置高质量插值法
                        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //设置高质量,低速度呈现平滑程度
                        g.Clear(Color.Transparent);                                               //清空画布并以透明背景色填充
                        g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
                        fileXltPath = basePath + fileName.Replace(Extentsion, "m" + Extentsion);
                        string fileXltPath2 = basePath + "\\" + fileName.Replace(Extentsion, "m" + Extentsion);
                        tImage.Save(fileXltPath2, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    Bitmap tImage2 = new Bitmap(t2Width, t2Height);

                    Graphics g2 = Graphics.FromImage(tImage2);

                    g2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    g2.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    g2.Clear(Color.Transparent);

                    g2.DrawImage(oImage, new Rectangle(0, 0, t2Width, t2Height), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
                    //创建一个图像对象取得上传图片对象
                    //缩略图的保存路径

                    fileXltPath3 = basePath + fileName.Replace(Extentsion, "s" + Extentsion);
                    string fileXltPath4 = basePath + "\\" + fileName.Replace(Extentsion, "s" + Extentsion);
                    //保存缩略图

                    tImage2.Save(fileXltPath4, System.Drawing.Imaging.ImageFormat.Jpeg);

                    using (SqlConnection conn = new DB().GetConnection())
                    {
                        //向resources插入一条记录操作
                        StringBuilder sb = new StringBuilder("Insert into Resources (ResourceName,FileName,FilePath,FileSizeInKB,FileType,Extentsion,FolderID,FolderName,UserID,CDT,Status,UserName,Valid,Thumbnail,Thumbnail2)");
                        sb.Append(" values(@ResourceName,@FileName,@FilePath,@FileSize,@FileType,@Extentsion,@FolderID,@FolderName,@UserID,@CDT,@Status,@UserName,@Valid,@Thumbnail,@Thumbnail2)");
                        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
                        cmd.Parameters.AddWithValue("@ResourceName", OldFileName);
                        cmd.Parameters.AddWithValue("@FileName", fileName);
                        cmd.Parameters.AddWithValue("@FilePath", filePath);
                        cmd.Parameters.AddWithValue("@FileSize", fileSize);
                        cmd.Parameters.AddWithValue("@FileType", fileType);
                        cmd.Parameters.AddWithValue("@Extentsion", Extentsion);
                        cmd.Parameters.AddWithValue("@FolderID", 96);
                        cmd.Parameters.AddWithValue("@FolderName", "默认文件夹");
                        cmd.Parameters.AddWithValue("@UserID", Session["UserID"].ToString());
                        cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
                        cmd.Parameters.AddWithValue("@CDT", DateTime.Now);
                        cmd.Parameters.AddWithValue("@Status", 0);
                        cmd.Parameters.AddWithValue("@Valid", 1);
                        if (oWidth >= 600)
                        {
                            cmd.Parameters.AddWithValue("@Thumbnail", fileXltPath);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@Thumbnail", filePath);
                        }
                        cmd.Parameters.AddWithValue("@Thumbnail2", fileXltPath3);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                        conn.Open();
                        cmd.CommandText = "SELECT count(*) from Resources where FolderID =@FolderID";
                        int count = int.Parse(Convert.ToString(cmd.ExecuteScalar()));
                        cmd.CommandText = "Update ResourceFolders set Counts = " + count.ToString() + " where ID = 96";
                        //cmd.Parameters.AddWithValue("@ID", FolderDDL.SelectedItem.Value);
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        //插入成功
                    }
                }


                else
                {
                    using (SqlConnection conn = new DB().GetConnection())
                    {
                        //向resources插入一条记录操作
                        StringBuilder sb = new StringBuilder("Insert into Resources (ResourceName,FileName,FilePath,FileSizeInKB,FileType,Extentsion,FolderID,FolderName,UserID,CDT,Status,UserName,Valid,Thumbnail,Thumbnail2)");
                        sb.Append(" values(@ResourceName,@FileName,@FilePath,@FileSize,@FileType,@Extentsion,@FolderID,@FolderName,@UserID,@CDT,@Status,@UserName,@Valid,@Thumbnail,@Thumbnail2)");
                        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
                        cmd.Parameters.AddWithValue("@ResourceName", OldFileName);
                        cmd.Parameters.AddWithValue("@FileName", fileName);
                        cmd.Parameters.AddWithValue("@FilePath", filePath);
                        cmd.Parameters.AddWithValue("@FileSize", fileSize);
                        cmd.Parameters.AddWithValue("@FileType", fileType);
                        cmd.Parameters.AddWithValue("@Extentsion", Extentsion);
                        cmd.Parameters.AddWithValue("@FolderID", 96);
                        cmd.Parameters.AddWithValue("@FolderName", "默认文件夹");
                        cmd.Parameters.AddWithValue("@UserID", Session["UserID"].ToString());
                        cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
                        cmd.Parameters.AddWithValue("@CDT", DateTime.Now);
                        cmd.Parameters.AddWithValue("@Status", 0);
                        cmd.Parameters.AddWithValue("@Valid", 1);
                        cmd.Parameters.AddWithValue("@Thumbnail", fileXltPath);
                        cmd.Parameters.AddWithValue("@Thumbnail2", fileXltPath3);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                        conn.Open();
                        cmd.CommandText = "SELECT count(*) from Resources where FolderID =@FolderID";
                        int count = int.Parse(Convert.ToString(cmd.ExecuteScalar()));
                        cmd.CommandText = "Update ResourceFolders set Counts = " + count.ToString() + " where ID = 96";
                        //cmd.Parameters.AddWithValue("@ID", FolderDDL.SelectedItem.Value);
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        //插入成功
                    }
                }
            }
            Util.SetFileName(FileNames);
        }
    }
示例#24
0
        protected void Button1_Click1(object sender, EventArgs e)
        {
            AthleticsEntities1      AthlEnt = new AthleticsEntities1();
            string                  line;
            AthleticCompetitionCRUD AthlCRUD2 = new AthleticCompetitionCRUD();

            HttpFileCollection File_Collection = Request.Files;
            string             BibNos          = "";
            string             RunnerLanes     = "";
            Global             gl    = new Global();
            string             Times = "";
            Int32  LineNo            = 0;
            Int32  CurrentHeatNo     = 1;
            string ImportedHeatNo    = "";
            string ImportedWind      = "";

            WindReading      = 0;
            EventLineNo.Text = Request.QueryString.Get("EventLineNo");
            AthlEvent        = AthlCRUD2.GetCompetitionEvent(CompCode.Text, Convert.ToInt32(EventLineNo.Text));
            Int32 TrackEventNoForLynx = AthlEvent.Númer_hlaupagreinar_f__Lynx + 1000;

            WindReadingRequired = AthlEvent.krefstvindmaelis;

            foreach (string File_Uploader in File_Collection)
            {
                HttpPostedFile Posted_File         = File_Collection[File_Uploader];
                string         FileNameWithoutPath = "";
                Int32          LastSlashPos        = 0;
                for (int ix = 0; ix < Posted_File.FileName.Length; ix++)
                {
                    if (Posted_File.FileName.Substring(ix, 1) == @"\")
                    {
                        LastSlashPos = ix;
                    }
                }
                if (LastSlashPos > 0)
                {
                    FileNameWithoutPath = Posted_File.FileName.Substring(LastSlashPos + 1);
                }
                else
                {
                    FileNameWithoutPath = Posted_File.FileName;
                }
                if (FileNameWithoutPath.Substring(0, 3) == LifFilePrefix.Text)
                {
                    if (Posted_File.ContentLength > 0)
                    {
                        System.IO.StreamReader file = new System.IO.StreamReader(Posted_File.InputStream);
                        while ((line = file.ReadLine()) != null)
                        {  //Example: 5,0,1,"100M Karla R1 w:-0,1",-1.0,M/S S,,,,100,18:34:25.1698  - Með vindi
                           //Example: 2,2,1,60M S15 R1,,,,,,60,10:01:00.4149                        - Án vinds

                            string[] Fields = line.Split(',');
                            if (LineNo == 0)
                            {
                                string EventNameText = Fields[3]; //Example: "60m p12 R2" or "100M S13 R1/2" or "4X100M S13"
                                string HeatText      = EventNameText.Split(' ').Last();
                                if (HeatText.StartsWith("R"))
                                {
                                    string[] HeatTextArr = HeatText.Split('/');
                                    HeatText      = HeatTextArr[0].Substring(1);
                                    CurrentHeatNo = gl.TryConvertStringToInt32(HeatText);
                                }
                                else
                                {
                                    CurrentHeatNo = 1;
                                }
                                if (WindReadingRequired == 1)
                                {
                                    if (Fields.Length == 12)
                                    {
                                        WindReading = gl.TryConvertStringToDecimal(Fields[5]);
                                    }
                                    else
                                    {
                                        WindReading = gl.TryConvertStringToDecimal(Fields[4]);
                                    }
                                    //WindReading = gl.TryConvertStringToDecimal(Fields[4]);
                                    WindReading = WindReading / 10;
                                }
                                else
                                {
                                    WindReading = 0;
                                }
                            }
                            else
                            {
                                Int32 Rank       = 0;
                                bool  SuccessFul = Int32.TryParse(Fields[0], out Rank);
                                if (SuccessFul)
                                {
                                    BibNos      = BibNos + "," + Fields[1];
                                    Times       = Times + "," + Fields[6];
                                    RunnerLanes = RunnerLanes + "," + Fields[2];
                                }
                                else
                                {
                                    BibNos      = BibNos + "," + Fields[1];
                                    Times       = Times + "," + Fields[0];
                                    RunnerLanes = RunnerLanes + "," + Fields[2];
                                }
                                //6,2,2,60m p12 R2,-1.0,M/S W,,,,60,11:39:33.7908
                                //1,179,4,Finnsson,Birnir Vagn,UFA,8.942,UFA,8.942,,,11:39:33.791,,,,8.942,8.942
                                //2,4,5,Eysteinsson,Dagur,AFTURE,9.266,AFTURE,0.324,,,11:39:33.791,,,,0.324,0.324
                                //3,156,3,Olafsson,Karl Hakon,IR,9.702,IR,0.436,,,11:39:33.791,,,,0.436,0.436
                                //4,142,2,Ingolfsson,Ari,HST,10.242,HST,0.540,,,11:39:33.791,,,,0.540,0.540
                                //DNS,188,6,Sigurdarson,Starkadur,UFA,,UFA,,,,11:39:33.791,,,,,
                                //DNS,125,7,Khorchai,Jens Johnny,HSK-SELFOS,,HSK-SELFOS,,,,11:39:33.791,,,,,
                            }
                            LineNo = LineNo + 1;
                        }
                        file.Close();

                        if (BibNos.Substring(0, 1) == ",")
                        {
                            BibNos      = BibNos.Substring(1);
                            Times       = Times.Substring(1);
                            RunnerLanes = RunnerLanes.Substring(1);
                        }
                        //TextBox1.Text = BibNos;
                        //TextBox2.Text = Times;

                        System.Data.Objects.ObjectParameter MsgOut = new System.Data.Objects.ObjectParameter("MessageOut", typeof(string));
                        AthlEnt.UpdateTimesInTrackEvent(CompCode.Text, Convert.ToInt32(EventLineNo.Text), BibNos, Times, RunnerLanes, CurrentHeatNo, WindReading, MsgOut);
                        if (MsgOut.Value.ToString() == "")
                        {
                            Int32 EventTypeInteger = 1;
                            AthlEnt.UpdateOrderAndPointsByResults(CompCode.Text, Convert.ToInt32(EventLineNo.Text), EventTypeInteger);

                            if ((AthlEvent.thrautargrein == 1) && (AthlEvent.nanaritegundargreining != 7))
                            {
                                AthlEnt.ProcessMultiEventCompetitors(CompCode.Text, Convert.ToInt32(EventLineNo.Text));
                                Int32 LineNoOfMultiEv = 0;
                                System.Data.Objects.ObjectParameter LineNoOfMultiEvParameter = new System.Data.Objects.ObjectParameter("LineNoOfMultiEvent", "0");
                                //AthlEntities.ReturnNoOfHeatsInEvent(CompCode, EventLin, OutNoOfHeats);
                                AthlEnt.ReturnLineNumberOfMultiEvent(CompCode.Text, Convert.ToInt32(EventLineNo.Text), LineNoOfMultiEvParameter);
                                LineNoOfMultiEv = Convert.ToInt32(LineNoOfMultiEvParameter.Value);
                                AthlEnt.UpdateOrderAndPointsByResults(CompCode.Text, LineNoOfMultiEv, 2);
                            }
                            if ((AthlEvent.stigagrein == 1) && (AthlCompetitionRec.tegundstigakeppni == 5))
                            {
                                AthlEnt.CalculatePointsInEvent(CompCode.Text, Convert.ToInt32(EventLineNo.Text));
                            }
                            Response.Redirect("UpdateEventResults.aspx?Event=" + EventLineNo.Text);
                        }
                        else
                        {
                            string msg = MsgOut.Value.ToString();
                            Response.Write("<script>alert('" + msg + "')</script>");
                        }
                    }
                }
                else
                {
                    string msg = string.Format("Þú verður að velja .lif skrá sem byrjar á {0}", LifFilePrefix.Text);
                    Response.Write("<script>alert('" + msg + "')</script>");
                }
            }
        }
 protected void Lnupload_Click(object sender, EventArgs e)
 {
     try
     {
         if (m_img_id != 0)
         {
             if (trImage1.Visible)
             {
                 var list = DB.ESHOP_NEWS_IMAGEs.Where(n => n.NEWS_IMG_ID == m_img_id).ToList();
                 if (list.Count > 0)
                 {
                     list[0].NEWS_IMG_DESC  = txtTitle.Value;
                     list[0].NEWS_IMG_ORDER = Utils.CIntDef(txtOrder.Value);
                     DB.SubmitChanges();
                 }
             }
             else
             {
                 HttpFileCollection hfc = Request.Files;
                 for (int i = 0; i < hfc.Count; i++)
                 {
                     HttpPostedFile hpf = hfc[0];
                     if (hpf.ContentLength > 0)
                     {
                         string pathfile     = Server.MapPath("/data/news/" + m_news_id);
                         string fullpathfile = pathfile + "/" + Path.GetFileName(hpf.FileName);
                         if (!Directory.Exists(pathfile))
                         {
                             Directory.CreateDirectory(pathfile);
                         }
                         hpf.SaveAs(fullpathfile);
                         var list = DB.ESHOP_NEWS_IMAGEs.Where(n => n.NEWS_IMG_ID == m_img_id).ToList();
                         if (list.Count > 0)
                         {
                             list[0].NEWS_IMG_DESC   = txtTitle.Value;
                             list[0].NEWS_IMG_ORDER  = Utils.CIntDef(txtOrder.Value);
                             list[0].NEWS_IMG_IMAGE1 = hpf.FileName;
                             DB.SubmitChanges();
                         }
                     }
                 }
             }
         }
         else
         {
             // Get the HttpFileCollection
             HttpFileCollection hfc = Request.Files;
             for (int i = 0; i < hfc.Count; i++)
             {
                 HttpPostedFile hpf = hfc[i];
                 if (hpf.ContentLength > 0)
                 {
                     ESHOP_NEWS_IMAGE g_update     = new ESHOP_NEWS_IMAGE();
                     string           pathfile     = Server.MapPath("/data/news/" + m_news_id);
                     string           fullpathfile = pathfile + "/" + Path.GetFileName(hpf.FileName);
                     if (!Directory.Exists(pathfile))
                     {
                         Directory.CreateDirectory(pathfile);
                     }
                     hpf.SaveAs(fullpathfile);
                     g_update.NEWS_IMG_DESC   = txtTitle.Value;
                     g_update.NEWS_IMG_ORDER  = Utils.CIntDef(txtOrder.Value);
                     g_update.NEWS_ID         = m_news_id;
                     g_update.NEWS_IMG_IMAGE1 = hpf.FileName;
                     DB.ESHOP_NEWS_IMAGEs.InsertOnSubmit(g_update);
                     DB.SubmitChanges();
                 }
             }
         }
         Response.Redirect("news_images.aspx?type=" + _type + "&news_id=" + m_news_id);
     }
     catch (Exception ex)
     {
         clsVproErrorHandler.HandlerError(ex);
     }
 }
示例#26
0
    private bool SaveInvoiceFiles(string dir, bool allowOverwrite)
    {
        string allowedFileTypes = "docx|doc|dot";  // "docx|doc|dot|txt";

        System.Text.StringBuilder _messageToUser = new System.Text.StringBuilder("Files Uploaded:<br>");


        bool hasClinic = false;
        bool hasAC     = false;
        bool hasGP     = false;

        foreach (Site site in SiteDB.GetAll())
        {
            if (site.SiteType.ID == 1)
            {
                hasClinic = true;
            }
            if (site.SiteType.ID == 2)
            {
                hasAC = true;
            }
            if (site.SiteType.ID == 3)
            {
                hasGP = true;
            }
        }


        try
        {
            HttpFileCollection _files = Request.Files;

            if (_files.Count == 0 || (_files.Count == 1 && System.IO.Path.GetFileName(_files[0].FileName) == string.Empty))
            {
                lblUploadInvoiceMessage.Text = " <font color=\"red\">No Files Selected</font> <BR>";
                return(true);
            }

            for (int i = 0; i < _files.Count; i++)
            {
                HttpPostedFile _postedFile = _files[i];
                string         _fileName   = System.IO.Path.GetFileName(_postedFile.FileName);
                if (_fileName.Length == 0)
                {
                    continue;
                }

                if (_postedFile.ContentLength > 8000000)
                {
                    throw new Exception(_fileName + " <font color=\"red\">Failed!! Over allowable file size limit!</font> <BR>");
                }


                if (!hasClinic && !hasGP)
                {
                    if (_fileName != "InvoiceTemplate.docx" && _fileName != "PrivateInvoiceTemplate.docx" && _fileName != "OverdueInvoiceTemplate.docx" && _fileName != "InvoiceTemplateAC.docx" && _fileName != "OverdueInvoiceTemplateAC.docx" && _fileName != "TreatmentList.docx" && _fileName != "ACTreatmentList.docx" && _fileName != "BlankTemplate.docx" && _fileName != "BlankTemplateAC.docx")
                    {
                        throw new Exception(_fileName + " <font color=\"red\">Failed. Only file allowed are 'InvoiceTemplateAC.docx', 'OverdueInvoiceTemplateAC.docx', 'TreatmentList.docx', 'ACTreatmentList.docx', and 'BlankTemplateAC.docx'</font> <BR>");
                    }
                }
                else if (!hasAC)
                {
                    if (_fileName != "InvoiceTemplate.docx" && _fileName != "PrivateInvoiceTemplate.docx" && _fileName != "OverdueInvoiceTemplate.docx" && _fileName != "InvoiceTemplateAC.docx" && _fileName != "OverdueInvoiceTemplateAC.docx" && _fileName != "TreatmentList.docx" && _fileName != "ACTreatmentList.docx" && _fileName != "BlankTemplate.docx" && _fileName != "BlankTemplateAC.docx")
                    {
                        throw new Exception(_fileName + " <font color=\"red\">Failed. Only files allowed are 'InvoiceTemplate.docx', 'PrivateInvoiceTemplate.docx', 'OverdueInvoiceTemplate.docx', 'TreatmentList.docx', and 'BlankTemplate.docx'</font> <BR>");
                    }
                }
                else
                {
                    if (_fileName != "InvoiceTemplate.docx" && _fileName != "PrivateInvoiceTemplate.docx" && _fileName != "OverdueInvoiceTemplate.docx" && _fileName != "InvoiceTemplateAC.docx" && _fileName != "OverdueInvoiceTemplateAC.docx" && _fileName != "TreatmentList.docx" && _fileName != "ACTreatmentList.docx" && _fileName != "BlankTemplate.docx" && _fileName != "BlankTemplateAC.docx")
                    {
                        throw new Exception(_fileName + " <font color=\"red\">Failed. Only files allowed are 'InvoiceTemplate.docx', 'PrivateInvoiceTemplate.docx', 'OverdueInvoiceTemplate.docx', 'InvoiceTemplateAC.docx', 'OverdueInvoiceTemplateAC.docx', 'ACTreatmentList.docx', 'BlankTemplate.docx', and 'BlankTemplateAC.docx'</font> <BR>");
                    }
                }



                if (!ExtIn(System.IO.Path.GetExtension(_fileName), allowedFileTypes))
                {
                    throw new Exception(_fileName + " <font color=\"red\">Failed!! Only " + ExtToDisplay(allowedFileTypes) + " files allowed!</font> <BR>");
                }

                if (!allowOverwrite && File.Exists(dir + "\\" + _fileName))
                {
                    throw new Exception(_fileName + " <font color=\"red\">Failed!! File already exists. To allow overwrite, check the \"Allowed File Overwrite\" box</font> <BR>");
                }
            }

            int countZeroFileLength = 0;
            for (int i = 0; i < _files.Count; i++)
            {
                HttpPostedFile _postedFile = _files[i];
                string         _fileName   = System.IO.Path.GetFileName(_postedFile.FileName);
                if (_fileName.Length == 0)
                {
                    continue;
                }

                if (_postedFile.ContentLength > 0)
                {
                    //_postedFile.SaveAs(Server.MapPath("MyFiles") + "\\" + System.IO.Path.GetFileName(_postedFile.FileName));
                    _postedFile.SaveAs(dir + "\\" + _fileName);
                    _messageToUser.Append(_fileName + "<BR>");
                }
                else
                {
                    countZeroFileLength++;
                }
            }

            if (_files.Count > 0 && countZeroFileLength == _files.Count)
            {
                throw new Exception("<font color=\"red\">File" + (_files.Count > 1 ? "s are" : " is") + " 0 kb.</font>");
            }
            else if (_files.Count > 0 && countZeroFileLength > 0)
            {
                throw new Exception("<font color=\"red\">File(s) of 0 kb were not uploaded.</font>");
            }

            lblUploadInvoiceMessage.Text = _messageToUser.ToString();
            return(true);
        }
        catch (System.Exception ex)
        {
            lblUploadInvoiceMessage.Text = ex.Message;
            return(false);
        }
        finally
        {
            FillCurrentFilesList();
            FillGrid();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "download", @"<script language=javascript>addLoadEvent(function () { window.location.hash = ""invoice_templates_tag""; });</script>");
        }
    }
示例#27
0
        protected void Btn_Save_Click(object sender, EventArgs e)
        {
            HttpFileCollection hfc = Request.Files;

            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile file = hfc[i];

                Stream openStream;

                if ((openStream = file.InputStream) != null)
                {
                    BufferedStream bufferStream = new BufferedStream(openStream);
                    StreamReader   streamReader = new StreamReader(bufferStream);
                    string         str          = streamReader.ReadToEnd();

                    bufferStream.Position = 0;

                    license = SPLicenseFile.LoadFile(bufferStream, null, false, string.Empty);

                    streamReader.Close();
                    //bufferStream.Close();
                    //openStream.Close();
                }

                List <IConstraint> contraints = license.Constraints;

                foreach (IConstraint contraint in contraints)
                {
                    FarmConstraint farmContraint = contraint as FarmConstraint;
                    if (farmContraint != null)
                    {
                        foreach (string farm in farmContraint.Farms)
                        {
                            tbx_Result.Text += farm + Environment.NewLine;
                        }
                    }

                    DomainConstraint domainContraint = contraint as DomainConstraint;
                    if (domainContraint != null)
                    {
                        foreach (string domain in domainContraint.Domains)
                        {
                            tbx_Result.Text += domain + Environment.NewLine;
                        }
                    }
                }
                //SPLicense.LicenseFile.Constraints.FarmConstraint
                //tbx_Result.Text = license.LicenseKey+ Environment.NewLine;
                tbx_Result.Text += license.Product.ShortName + Environment.NewLine;
                tbx_Result.Text += license.User.Organization + Environment.NewLine;
                tbx_Result.Text += license.Issuer.FullName + Environment.NewLine;

                /*
                 * if (license.Validate())
                 * {
                 *  tbx_Result.Text += license.ToXmlString();
                 * }
                 */
            }
        }
示例#28
0
        private void OnUploadPictureBrand(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string errorMsg = "";

            try
            {
                HttpFileCollection files = context.Request.Files;
                if (files.Count == 0)
                {
                    context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}");
                    return;
                }

                int effect            = 0;
                UploadFilesHelper ufh = new UploadFilesHelper();
                ImagesHelper      ih  = new ImagesHelper();

                using (TransactionScope scope = new TransactionScope())
                {
                    foreach (string item in files.AllKeys)
                    {
                        HttpPostedFile file = files[item];
                        if (file == null || file.ContentLength == 0)
                        {
                            continue;
                        }

                        int fileSize       = file.ContentLength;
                        int uploadFileSize = int.Parse(WebConfigurationManager.AppSettings["UploadFileSize"]);
                        if (fileSize > uploadFileSize)
                        {
                            throw new ArgumentException("文件【" + file.FileName + "】大小超出字节" + uploadFileSize + ",无法上传,请正确操作!");
                        }
                        if (!UploadFilesHelper.IsFileValidated(file.InputStream, fileSize))
                        {
                            throw new ArgumentException("文件【" + file.FileName + "】为受限制的文件,请正确操作!");
                        }

                        string fileName = file.FileName;

                        PictureBrand bll = new PictureBrand();
                        if (bll.IsExist(file.FileName, fileSize))
                        {
                            throw new ArgumentException("文件【" + file.FileName + "】已存在,请勿重复上传!");
                        }

                        string originalUrl = UploadFilesHelper.UploadOriginalFile(file, "PictureBrand");

                        //获取随机生成的文件名代码
                        string randomFolder = string.Format("{0}_{1}", DateTime.Now.ToString("MMdd"), UploadFilesHelper.GetRandomFolder("bp"));

                        PictureBrandInfo model = new PictureBrandInfo();
                        model.FileName        = VirtualPathUtility.GetFileName(originalUrl);
                        model.FileSize        = fileSize;
                        model.FileExtension   = VirtualPathUtility.GetExtension(originalUrl).ToLower();
                        model.FileDirectory   = VirtualPathUtility.GetDirectory(originalUrl.Replace("~", ""));
                        model.RandomFolder    = randomFolder;
                        model.LastUpdatedDate = DateTime.Now;

                        bll.Insert(model);

                        CreateThumbnailImage(context, ih, originalUrl, model.FileDirectory, model.RandomFolder, model.FileExtension);

                        effect++;
                    }

                    scope.Complete();
                }

                if (effect == 0)
                {
                    context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}");
                    return;
                }

                context.Response.Write("{\"success\": true,\"message\": \"已成功上传文件数:" + effect + "个\"}");

                return;
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }

            context.Response.Write("{\"success\": false,\"message\": \"" + errorMsg + "\"}");
        }
示例#29
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            HttpFileCollection hfc = Request.Files;

            int totalLength = 0;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (String.IsNullOrEmpty(hpf.FileName))
                {
                    continue;
                }

                if (Path.GetExtension(hpf.FileName).ToLower() != ".cnf")
                {
                    continue;
                }

                totalLength += hpf.ContentLength;
            }

            if (totalLength >= maxTotalContentLength)
            {
                Utils.reportStatus(ref labelStatus, Color.Red, "Opplasting feilet. Vennligst last opp ferre filer av gangen");
                return;
            }

            List <string> uploadedFileNames = new List <string>();

            string uploadPath = Server.MapPath("~/Spectrums/");

            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (String.IsNullOrEmpty(hpf.FileName))
                {
                    continue;
                }

                if (Path.GetExtension(hpf.FileName).ToLower() != ".cnf")
                {
                    continue;
                }

                if (hpf.ContentLength > 0)
                {
                    string saveFileName = Path.Combine(uploadPath, Path.GetFileName(hpf.FileName));
                    uploadedFileNames.Add(Path.GetFileName(hpf.FileName));
                    if (!File.Exists(saveFileName))
                    {
                        hpf.SaveAs(saveFileName);
                    }
                }
            }

            tblUploadFiles.Rows.Clear();

            TableHeaderRow  hrow  = new TableHeaderRow();
            TableHeaderCell hcell = new TableHeaderCell();
            hcell.HorizontalAlign = HorizontalAlign.Left;
            hrow.Cells.Add(hcell);
            hcell.Text = "Følgende filer ble opplastet:";
            tblUploadFiles.Rows.Add(hrow);

            foreach (string fname in uploadedFileNames)
            {
                TableRow  row  = new TableRow();
                TableCell cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Left;
                row.Cells.Add(cell);
                cell.Text = fname;
                tblUploadFiles.Rows.Add(row);
            }
        }
        catch (Exception ex)
        {
            Utils.reportStatus(ref labelStatus, Color.Red, "UploadSpectrums.btnUpload_Click: " + ex.Message);
        }
    }
        /// <summary>
        /// 保存表单及其它功能按钮
        /// </summary>
        private int Save(int state)
        {
            WX.XZ.NotifyFiles.MODEL model = WX.Request.rNotifyFile;
            //1.获取模型
            WX.Flow.Model.Run.MODEL runmodel = WX.Flow.Model.Run.GetModel("select * from FL_Run where Id=" + model.RunID.ToString());
            int stepno = model.StepNo.ToInt32();

            //2.取表单值
            runmodel.LoadMyForm(false);
            WX.Flow.FormFieldCollection ffc = runmodel.MyForm.GetPostedDatas();
            //3.上传附件并取得附件列表
            string             attach_nameList = String.Empty;
            string             attache_idlist  = String.Empty;
            string             uploadUserId    = WX.Main.CurUser.UserID;
            string             uploadIp        = WX.Main.getIp(this);
            HttpFileCollection hfc             = Request.Files;
            //WX.Flow.FormFieldCollection ffc = new WX.Flow.FormFieldCollection();
            //foreach (WX.Flow.FormField ff in runmodel.MyForm.Items_FormFieldCollection)
            //{
            //    ff.Value = this.Request.Form[ff.Id] == null ? "" : this.Request.Form[ff.Id];
            //    ffc.Add(ff);
            //}
            //
            //4.取得手写与签章信息
            string sealData = this.txtSealData.Value;

            WX.Flow.Model.Process.MODEL proc;

            WX.Flow.Model.Process.MODEL process = null;
            int iR = 0;

            if (state == 2)
            {
                model.state.value    = 2;
                model.StepNo.value   = 1;
                model.StepName.value = "文件拟写";
                proc    = WX.Flow.Model.Process.GetModel("select * from FL_Process where FlowID=" + runmodel.FlowId.ToString() + " and StepNo=" + model.StepNo.ToInt32());
                process = WX.Flow.Model.Process.GetModel("select * from FL_Process where FlowID=" + runmodel.FlowId.ToString() + " and StepNo=" + proc.Next_Nodes.ToInt32());
                runmodel.StepNo.value     = model.StepNo.value;
                runmodel.Next_Nodes.value = proc.Next_Nodes.value;
                WX.Main.AddLog(WX.LogType.Default, "文件通知审批未通过!", String.Format("{0}-{1}", model.ID.ToString(), model.Title.ToString()));
                //向拟写人发消息
                WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFiles.aspx?mes=1&NotifyFileId=" + model.ID.ToString() + ">你似写的文件《" + model.Title.ToString() + "》——审批未通过被退回</a>", "/Manage/Main/messagelist.aspx", model.UserID.ToString(), WX.Main.CurUser.UserID, 5, 0);
            }
            else
            {
                proc = WX.Flow.Model.Process.GetModel("select * from FL_Process where FlowID=" + runmodel.FlowId.ToString() + " and StepNo=" + model.StepNo.ToInt32());
                if (proc != null && proc.Next_Nodes.ToString() != "" && proc.Next_Nodes.ToInt32() > 0)
                {
                    process = WX.Flow.Model.Process.GetModel("select * from FL_Process where FlowID=" + runmodel.FlowId.ToString() + " and StepNo=" + proc.Next_Nodes.ToInt32());
                }

                if (process == null)
                {
                    runmodel.Deal_Flag.value = WX.Flow.DealFlag.HasOperated;
                    model.state.value        = 4;
                    model.StepNo.value       = 0;
                    model.StepName.value     = "行政发布";
                    //审批完成,向行政发消息发布文件

                    WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">文件《" + model.Title.ToString() + "》通过审批!请行政尽快发布</a>", "/Manage/Main/messagelist.aspx", WX.CommonUtils.GetCAUserID, WX.Main.CurUser.UserID, 5, 0);
                    WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">文件《" + model.Title.ToString() + "》通过审批!请行政尽快发布</a>", "/Manage/Main/messagelist.aspx", WX.CommonUtils.GetAdminUserID, WX.Main.CurUser.UserID, 5, 0);
                }
                else
                {
                    runmodel.Deal_Flag.value = 1;
                    runmodel.StepNo.value    = model.StepNo.value = process.StepNo.value;
                    if (process.Next_Nodes.ToInt32() > 0)
                    {
                        runmodel.Next_Nodes.value = process.Next_Nodes.value;
                    }
                    else
                    {
                        runmodel.Next_Nodes.value = 0;
                    }
                    iR = 1;
                    model.state.value    = 3;
                    model.StepName.value = process.Name.value;
                    //向下一个人发消息,提醒审批
                    // WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">文件《" + model.Title.ToString() + "》通过审批!请行政尽快发布</a>", "/Manage/Main/messagelist.aspx", WX.CommonUtils.GetCAUserID, WX.Main.CurUser.UserID, 5, 0);
                    WX.Model.User.MODEL squser = WX.Model.User.NewDataModel(model.UserID.ToString());
                    if (process.Auto_Type.ToString() == "1")//经办人为流程发起人的
                    {
                        WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">" + squser.RealName.ToString() + "拟写的文件《" + model.Title.ToString() + "》!申请审批</a>", "/Manage/Main/messagelist.aspx", model.UserID.ToString(), WX.Main.CurUser.UserID, 5, 0);
                    }
                    else if (process.Auto_Type.ToString() == "2")//经办人为部门主管的
                    {
                        WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">" + squser.RealName.ToString() + "拟写的文件《" + model.Title.ToString() + "》申请主管审批!</a>", "/Manage/Main/messagelist.aspx", WX.CommonUtils.GetDeptUserID(1, "[Host]", squser.DepartmentID.ToInt32()), WX.Main.CurUser.UserID, 5, 0);
                    }
                    else if (process.Auto_Type.ToString() == "4")
                    {
                        WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">" + squser.RealName.ToString() + "拟写的文件《" + model.Title.ToString() + "》申请上级审批!</a>", "/Manage/Main/messagelist.aspx", WX.CommonUtils.GetParentDeptHost(squser.DepartmentID.ToInt32(), "Host"), WX.Main.CurUser.UserID, 5, 0);
                    }
                    else if (process.Auto_Type.ToString() == "5")
                    {
                        WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">" + squser.RealName.ToString() + "拟写的文件《" + model.Title.ToString() + "》申请分管领导审批!</a>", "/Manage/Main/messagelist.aspx", WX.CommonUtils.GetParentDeptHost(squser.DepartmentID.ToInt32(), "SubHosts"), WX.Main.CurUser.UserID, 5, 0);
                    }
                    else
                    {
                        System.Data.DataTable dt = ULCode.QDA.XSql.GetDataTable("select UserID from Tu_Users where 1=1" + (process.Priv_UserList.ToString() != "" ? " and UserID in('" + process.Priv_UserList.ToString().Replace(",", "','") + "')" : "") + (process.Priv_DutyList.ToString() != "" ? " and DutyId in(select ID from TE_DutyDetail where DutyID in(" + process.Priv_DutyList.ToString() + "))" : "") + (process.Priv_DeptList.ToString() != "" ? " and Priv_DeptList in(" + process.Priv_DeptList.ToString() + ")" : ""));
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            WX.Main.MessageSend("<a href=/Manage/XZ/NotifyFileDetail.aspx?NotifyFileId=" + model.ID.ToString() + ">" + squser.RealName.ToString() + "拟写的文件《" + model.Title.ToString() + "》!申请审批</a>", "/Manage/Main/messagelist.aspx", dt.Rows[i][0].ToString(), WX.Main.CurUser.UserID, 5, 0);
                        }
                    }
                }
                WX.Main.AddLog(WX.LogType.Default, "文件通知审批通过!", String.Format("{0}-{1}", model.ID.ToString(), model.Title.ToString()));
            }
            model.PublishTime.value = DateTime.Now;
            model.Update();
            runmodel.Save(stepno, ffc, attache_idlist, attach_nameList, this.txt_sign.Text, sealData, 1);

            pageinit();
            return(iR);
        }
示例#31
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            int durum, yeni, firsat, vitrin;
            durum  = (chkDurum.Checked) ? 1 : 0;
            yeni   = (chkYeni.Checked) ? 1 : 0;
            firsat = (chkFirsat.Checked) ? 1 : 0;
            vitrin = (chkVitrin.Checked) ? 1 : 0;


            string dosyaAdi;
            if (fuUrun.HasFile)
            {
                string filenameadd = DateTime.Now.ToString().Replace(" ", "_").Replace(":", "_").Replace(".", "_").Replace("/", "_");
                string uzanti      = Path.GetExtension(fuUrun.FileName);
                dosyaAdi = filenameadd + uzanti;
                fuUrun.PostedFile.SaveAs(Server.MapPath("~/Dosyalar/Urun/") + dosyaAdi);

                System.Drawing.Image imgResim         = null;
                System.Drawing.Image imgOrijinalResim = System.Drawing.Image.FromFile(Server.MapPath("~/Dosyalar/Urun/" + dosyaAdi));
                imgResim = resimboyutlandir.FixedSize(imgOrijinalResim, 250, 250);
                imgResim.Save(Server.MapPath("~/Dosyalar/Urun/Mini/" + dosyaAdi));
                imgResim.Dispose();
            }
            else
            {
                dosyaAdi = "resimyok.jpg";
            }


            ETICARET_Urunler ekle = new ETICARET_Urunler()
            {
                UrunAdi          = txtUrunAdi.Text,
                Sira             = txtSira.Text,
                AlisFiyat        = decimal.Parse(txtAlisFiyat.Text),
                Description      = txtDescription.Text,
                Detay            = txtDetay.Text,
                IndirimliFiyat   = decimal.Parse(txtIndirimliFiyat.Text),
                KargoAgirlik     = txtKArgoAgirlik.Text,
                Kdv              = int.Parse(txtKdv.Text),
                Keywords         = txtKeywords.Text,
                MarkaID          = int.Parse(drpMarkalar.SelectedValue),
                OdemeSecenekleri = txtOdeme.Text,
                KatID            = int.Parse(drpKategoriler.SelectedValue),
                Resim            = dosyaAdi,
                StokKodu         = txtStokKodu.Text,
                Stok             = int.Parse(txtStok.Text),
                Title            = txtTitle.Text,
                Durum            = durum,
                Yeni             = yeni,
                Firsat           = firsat,
                Vitrin           = vitrin,
            };
            db.ETICARET_Urunlers.InsertOnSubmit(ekle);
            db.SubmitChanges();
            pnlHata.Visible     = false;
            pnlBasarili.Visible = true;

            var CokluUrun = db.ETICARET_Urunlers.OrderByDescending(m => m.ID).FirstOrDefault();


            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile files = hfc[i];
                if (files.ContentLength > 0)
                {
                    string benzersiz2 = "";
                    benzersiz2 += DateTime.Now.Day.ToString() + i;
                    benzersiz2 += DateTime.Now.Month.ToString() + i;
                    benzersiz2 += DateTime.Now.Second.ToString() + i;
                    benzersiz2 += DateTime.Now.Millisecond.ToString() + i;
                    benzersiz2 += DateTime.Now.Year.ToString() + i;
                    benzersiz2 += DateTime.Now.Minute.ToString() + i;
                    benzersiz2 += DateTime.Now.Hour.ToString();
                    files.SaveAs(Server.MapPath("~/Dosyalar/CokluResim/") + System.IO.Path.GetFileName(benzersiz2 + fuUrun.FileName));



                    System.Drawing.Image imgResim         = null;
                    System.Drawing.Image imgOrijinalResim = System.Drawing.Image.FromFile(Server.MapPath("~/Dosyalar/CokluResim/" + benzersiz2 + fuUrun.FileName));
                    imgResim = resimboyutlandir.FixedSize(imgOrijinalResim, 350, 310);
                    imgResim.Save(Server.MapPath("~/Dosyalar/CokluResim/Mini/" + benzersiz2 + fuUrun.FileName));
                    imgResim.Dispose();


                    ETICARET_UrunResimleri resimleriEkle = new ETICARET_UrunResimleri()
                    {
                        Resim  = benzersiz2 + fuUrun.FileName,
                        UrunID = CokluUrun.ID,
                    };

                    db.ETICARET_UrunResimleris.InsertOnSubmit(resimleriEkle);
                    db.SubmitChanges();
                }

                Page.Header.Controls.Add(new LiteralControl("<meta http-equiv='refresh' content='2; url=urunler.aspx'/>"));
            }
        }
        catch (Exception)
        {
            pnlHata.Visible     = true;
            pnlBasarili.Visible = false;
        }
    }
示例#32
0
    public List<Int64> UploadPhotos(Int32 FileTypeID, Int32 AccountID, HttpFileCollection Files, Int64 AlbumID)
    {
        List<Int64> result = new List<long>();
        Folder folder = Folder.GetFolderByID(AlbumID);

        saveToFolder = _webContext.FilePath + "Files\\";

        sizesToMake.Add("T", sizeTiny);
        sizesToMake.Add("S", sizeSmall);
        sizesToMake.Add("M", sizeMedium);
        sizesToMake.Add("L", sizeLarge);

        switch (FileTypeID)
        {
            case 1:
                saveToFolder += "Photos\\";
                break;

            case 2:
                saveToFolder += "Videos\\";
                break;

            case 3:
                saveToFolder += "Audios\\";
                break;
        }

        //make sure the directory is ready for use
        saveToFolder += folder.CreateDate.Year.ToString() + folder.CreateDate.Month.ToString() + "\\";

        if (!Directory.Exists(saveToFolder))
            Directory.CreateDirectory(saveToFolder);

        Account account = Account.GetAccountByID(AccountID);

        HttpFileCollection uploadedFiles = Files;
        string Path = saveToFolder;
        for (int i = 0; i < uploadedFiles.Count; i++)
        {
            HttpPostedFile F = uploadedFiles[i];
            if (uploadedFiles[i] != null && F.ContentLength > 0)
            {
                string folderID = AlbumID.ToString();
                string fileType = "1";
                string uploadedFileName = F.FileName.Substring(F.FileName.LastIndexOf("\\") + 1);
                string extension = uploadedFileName.Substring(uploadedFileName.LastIndexOf(".") + 1);
                Guid guidName = Guid.NewGuid();
                string fullFileName = Path + "\\" + guidName.ToString() + "__O." + extension;
                bool goodFile = true;

                //create the file
                Pes.Core.File file = new Pes.Core.File();

                #region "Determine file type"
                switch (fileType)
                {
                    case "1":
                        file.FileSystemFolderID = (int)FileSystemFolder.Paths.Pictures;
                        switch (extension.ToLower())
                        {
                            case "jpg":
                                file.FileTypeID = (int)File.Types.JPG;
                                break;
                            case "gif":
                                file.FileTypeID = (int)File.Types.GIF;
                                break;
                            case "jpeg":
                                file.FileTypeID = (int)File.Types.JPEG;
                                break;
                            default:
                                goodFile = false;
                                break;
                        }
                        break;

                    case "2":
                        file.FileSystemFolderID = (int)FileSystemFolder.Paths.Videos;
                        switch (extension.ToLower())
                        {
                            case "wmv":
                                file.FileTypeID = (int)File.Types.WMV;
                                break;
                            case "flv":
                                file.FileTypeID = (int)File.Types.FLV;
                                break;
                            case "swf":
                                file.FileTypeID = (int)File.Types.SWF;
                                break;
                            default:
                                goodFile = false;
                                break;
                        }
                        break;

                    case "3":
                        file.FileSystemFolderID = (int)FileSystemFolder.Paths.Audios;
                        switch (extension.ToLower())
                        {
                            case "wav":
                                file.FileTypeID = (int)File.Types.WAV;
                                break;
                            case "mp3":
                                file.FileTypeID = (int)File.Types.MP3;
                                break;
                            case "flv":
                                file.FileTypeID = (int)File.Types.FLV;
                                break;
                            default:
                                goodFile = false;
                                break;
                        }
                        break;
                }
                #endregion

                file.Size = F.ContentLength;
                file.AccountID = account.AccountID;
                file.DefaultFolderID = Convert.ToInt32(folderID);
                file.FileName = uploadedFileName;
                file.FileSystemName = guidName;
                file.Description = "";
                file.IsPublicResource = false;

                if (goodFile)
                {
                    result.Add(File.SaveFile(file));

                    F.SaveAs(fullFileName);

                    if (Convert.ToInt32(fileType) == ((int)Folder.Types.Picture))
                    {
                        Resize(F, saveToFolder, guidName, extension);
                    }
                }
            }
        }

        return result;
    }