using BLL;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Net;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
namespace FineUIPro.Web.SES
{
public partial class StandardTemplate : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetButtonPower();//按钮权限
InitTreeMenu();
}
}
#region 加载树
private void InitTreeMenu()
{
this.tvStandardTemp.Nodes.Clear();
TreeNode rootRole = new TreeNode();
rootRole.Text = "TemplateType";
rootRole.NodeID = "0";
rootRole.Expanded = true;
this.tvStandardTemp.Nodes.Add(rootRole);
BoundTree(rootRole.Nodes);
}
///
/// 遍历节点
///
///
///
///
private void BoundTree(TreeNodeCollection nodes)
{
var types = BLL.TemplateTypeService.GetTemplateTypeList();
if (types.Count() > 0)
{
TreeNode tn = null;
foreach (var q in types)
{
tn = new TreeNode();
tn.Text = q.TemplateType;
tn.NodeID = q.TemplateTypeId;
tn.EnableClickEvent = true;
nodes.Add(tn);
}
}
}
#endregion
#region Tree点击事件
///
/// 选择角色事件
///
///
///
protected void tvStandardTemp_NodeCommand(object sender, TreeCommandEventArgs e)
{
this.BindGrid(this.tvStandardTemp.SelectedNodeID);
}
#endregion
private void BindGrid(string temp)
{
string strSql = @"SELECT t.TemplateId,
t.UploadMan,
t.UploadDate,
t.AttachUrl,
U.UserName AS UploadManName,
typ.TemplateType
FROM dbo.StandardTemplate AS t
LEFT JOIN Sys_User AS U ON U.UserId = t.UploadMan
LEFT JOIN dbo.Base_TemplateType typ ON typ.TemplateTypeId = t.TemplateTypeId
WHERE 1=1 ";
List listStr = new List();
if (tvStandardTemp.SelectedNodeID != "0" && tvStandardTemp.SelectedNodeID!=null)
{
strSql += " AND t.TemplateTypeId = @TemplateTypeId";
listStr.Add(new SqlParameter("@TemplateTypeId", tvStandardTemp.SelectedNodeID));
}
//listStr.Add(new SqlParameter("@TemplateName", temp));
//if (!string.IsNullOrEmpty(txtRemark.Text))
//{
// strSql += " AND t.Remark like @Remark";
// listStr.Add(new SqlParameter("@Remark", "%" + this.txtRemark.Text.Trim() + "%"));
//}
strSql += " ORDER BY t.UploadDate DESC";
SqlParameter[] parameter = listStr.ToArray();
DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
Grid1.RecordCount = tb.Rows.Count;
var table = this.GetPagedDataTable(Grid1, tb);
Grid1.DataSource = table;
Grid1.DataBind();
for (int i = 0; i < Grid1.Rows.Count; i++)
{
System.Web.UI.WebControls.LinkButton lbtnUrl = ((System.Web.UI.WebControls.LinkButton)(this.Grid1.Rows[i].FindControl("lbtnUrl1")));
string url = lbtnUrl.CommandArgument.ToString();
if (!string.IsNullOrEmpty(url))
{
url = url.Replace('\\', '/');
lbtnUrl.Text = BLL.UploadAttachmentService.ShowAttachment("../", url);
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.tvStandardTemp.SelectedNodeID))
{
BindGrid(this.tvStandardTemp.SelectedNodeID);
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (tvStandardTemp.SelectedNodeID != "0" && tvStandardTemp.SelectedNodeID != null && tvStandardTemp.SelectedNodeID != string.Empty)
{
PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader3.aspx?type=add&toKeyId={0}&path=FileUpload/SES/StandardTemplate&menuId={1}", tvStandardTemp.SelectedNodeID, BLL.Const.StandardTemplateMenuId)));
}
else
{
Alert.ShowInTop("Please Select Template Type!", MessageBoxIcon.Warning);
return;
}
//PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("StandardTemplateEdit.aspx", "增加 - ")));
}
protected void btnEdit_Click(object sender, EventArgs e)
{
string rowId = Grid1.SelectedRowID;
if (!string.IsNullOrEmpty(rowId))
{
PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader3.aspx?type=edit&toKeyId={0}&path=FileUpload/SES/StandardTemplate&menuId={1}", rowId, BLL.Const.StandardTemplateMenuId)));
}
else
{
Alert.ShowInTop("Please select the record to modify!", MessageBoxIcon.Warning);
return;
}
//PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("StandardTemplateEdit.aspx?templateId={0}", rowId, "编辑 - ")));
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (Grid1.SelectedRowIndexArray.Length > 0)
{
foreach (int rowIndex in Grid1.SelectedRowIndexArray)
{
string rowID = Grid1.DataKeys[rowIndex][0].ToString();
var t = BLL.StandardTemplateService.GetStandardTemplateById(rowID);
if (t != null)
{
BLL.StandardTemplateService.DeleteStandardTemplateById(rowID);
}
}
BindGrid(this.tvStandardTemp.SelectedNodeID);
BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Delete Standard Template");
ShowNotify("Deleted successfully!");
}
else
{
Alert.ShowInTop("Please select the record to Delete!", MessageBoxIcon.Warning);
return;
}
}
protected void Grid1_RowDoubleClick(object sender, EventArgs e)
{
string rowId = Grid1.SelectedRowID;
if (!string.IsNullOrEmpty(rowId))
{
PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader3.aspx?type=edit&toKeyId={0}&path=FileUpload/SES/StandardTemplate&menuId={1}", rowId, BLL.Const.StandardTemplateMenuId)));
}
else
{
Alert.ShowInTop("Please select the record to modify!", MessageBoxIcon.Warning);
return;
}
//PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("StandardTemplateEdit.aspx?templateId={0}", rowId, "编辑 - ")));
}
protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
{
Grid1.PageIndex = e.NewPageIndex;
BindGrid(this.tvStandardTemp.SelectedNodeID);
}
///
/// 分页显示条数下拉框
///
///
///
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
BindGrid(this.tvStandardTemp.SelectedNodeID);
}
protected void Window1_Close(object sender, WindowCloseEventArgs e)
{
BindGrid(this.tvStandardTemp.SelectedNodeID);
}
#region 权限设置
///
/// 菜单按钮权限
///
private void GetButtonPower()
{
var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.StandardTemplateMenuId);
if (buttonList.Count() > 0)
{
if (buttonList.Contains(BLL.Const.BtnAdd))
{
this.btnNew.Hidden = false;
}
if (buttonList.Contains(BLL.Const.BtnModify))
{
this.btnEdit.Hidden = false;
}
if (buttonList.Contains(BLL.Const.BtnBatchDownload))
{
this.btnBatchDownload.Hidden = false;
}
if (buttonList.Contains(BLL.Const.BtnDelete))
{
this.btnDelete.Hidden = false;
}
}
}
#endregion
protected void btnBatchDownload_Click(object sender, EventArgs e)
{
string rootPath = Server.MapPath("~/").Replace('\\', '/');
if (Grid1.SelectedRowIDArray.Count() == 0)
{
Alert.ShowInParent("Please select Download Row!");
return;
}
else
{
string[] rowList = Grid1.SelectedRowIDArray;
List durl = new List();
List urlList = (from x in Funs.DB.StandardTemplate where rowList.Contains(x.TemplateId) && x.AttachUrl != null && x.AttachUrl != "" select x.AttachUrl).ToList();
string date = DateTime.Now.ToString("yyyyMMddHHmmss");
string destFile = rootPath + "FileUpload\\Temp\\StandardTemplate_" + date;
string zipFileName = "StandardTemplate_" + date;
if (!Directory.Exists(destFile))
{
Directory.CreateDirectory(destFile);
}
foreach (string url in urlList)
{
string sourceFileName = rootPath + url.Replace('\\', '/');
string[] subUrl = sourceFileName.Split('/');
string fileName = subUrl[subUrl.Count() - 1];
string newFileName = fileName.Substring(fileName.IndexOf("~") + 1);
if (newFileName.Contains("_"))
{
if (newFileName.Substring(0, 1) == "_")
{
newFileName = newFileName.Substring(1, newFileName.Length - 1);
}
else
{
newFileName = newFileName.Replace(newFileName.Split('_')[0], "");
newFileName = newFileName.Substring(1);
}
}
string destFileName = destFile +"/"+ newFileName;
if (File.Exists(sourceFileName))
{
File.Copy(sourceFileName,destFileName,true);
}
}
FileZipDownload(destFile.Replace('\\', '/'), zipFileName);
//foreach (string url in urlList)
//{
// string fullUrl = rootPath + url.Replace('\\', '/');
// if (File.Exists(fullUrl))
// {
// durl.Add(url);
// }
//}
//string strcon = DownloadFileByHttpUrl(durl);
//ShowNotify(strcon);
}
}
public string DownloadFileByHttpUrl(List HttpUrlList)
{
if (HttpUrlList == null || HttpUrlList.Count == 0)
{
return "没有附件";
}
try
{
var random = new Random();
var zipMs = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(zipMs);
zipStream.SetLevel(6);//压缩率0~9
foreach (var url in HttpUrlList)
{
if (!string.IsNullOrWhiteSpace(url))
{
string rootPath = System.Configuration.ConfigurationManager.AppSettings["RootUrl"];
string surl = rootPath + url.Replace('\\', '/');
var urlStr = HttpUtility.UrlDecode(surl);
Console.WriteLine(urlStr);
string fileExt = Path.GetExtension(urlStr).ToLower();
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(urlStr);
var strName = fileNameWithoutExtension.Substring(fileNameWithoutExtension.LastIndexOf("/") + 1) + random.Next(1000, 9999) + fileExt;
zipStream.PutNextEntry(new ZipEntry(strName));
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlStr);
request.AllowAutoRedirect = true;
WebProxy proxy = new WebProxy();
proxy.BypassProxyOnLocal = true;
proxy.UseDefaultCredentials = true;
request.Proxy = proxy;
WebResponse response = request.GetResponse();
using (Stream streams = response.GetResponseStream())
{
Byte[] buffer = new Byte[1024];
int current = 0;
while ((current = streams.Read(buffer, 0, buffer.Length)) != 0)
{
zipStream.Write(buffer, 0, current);
}
zipStream.Flush();
}
}
}
zipStream.Finish();
zipMs.Position = 0;
//下边为打包压缩
MemoryStream stream = zipMs;
byte[] srcBuf = new Byte[stream.Length];
stream.Read(srcBuf, 0, srcBuf.Length);
stream.Seek(0, SeekOrigin.Begin);
string filePath = "C:/DownLoad";//Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string date = DateTime.Now.ToString("yyyyMMddHHmmss");
string con = "StandardTemplate";
var file_name = con + "_" + date + ".zip";
using (FileStream fs = new FileStream(filePath + "\\" + file_name, FileMode.Create, FileAccess.Write))
{
fs.Write(srcBuf, 0, srcBuf.Length);
fs.Close();
return "已下载到C盘Download文件下!";
}
}
catch (Exception ex)
{
return "下载失败:" + ex.ToString();
}
}
private void FileZipDownload(string destFilePath, string zipFileName)
{
//string rootPath = Funs.RootPath;
//if (!Directory.Exists(destFilePath))
//{
// Directory.CreateDirectory(destFilePath);
//}
string zipFilePath = destFilePath+".zip";
System.IO.Compression.ZipFile.CreateFromDirectory(destFilePath, zipFilePath);
FileInfo info = new FileInfo(zipFilePath);
long fileSize = info.Length;
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(zipFileName + ".zip", System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
System.Web.HttpContext.Current.Response.TransmitFile(zipFilePath, 0, fileSize);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
Funs.DeleteDir(destFilePath);
File.Delete(zipFilePath);
}
}
}