using AttachmentPage.AttachmentService;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AttachmentPage
{
public partial class Attachment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
LblError.Visible = false;
if (IsPostBack)
{
Literal cssFile = new Literal() { Text = "" };
Page.Header.Controls.Add(cssFile);
Title = "Documentos Adjuntos (Proceso: " + ProcessName() + ", Incidente: " + Incident() + ")";
}
if (!IsPostBack)
{
LoadParameters();
navTitle.Visible = VisibleTitleBar();
Literal cssFile = new Literal() { Text = "" };
Page.Header.Controls.Add(cssFile);
string processName = ProcessName();
string incident = Incident();
if(string.IsNullOrEmpty(processName) || string.IsNullOrEmpty(incident))
{
navUpload.Visible = false;
ShowErrorMessage("Debe especificar proceso e incidente");
return;
}
int attachmentMaxSizeMB = AttachmentMaxSize();
Title = "Documentos Adjuntos (Proceso: " + processName + ", Incidente: " + incident + ")";
LblProcessName.InnerText = processName;
LblIncident.InnerText = incident;
BtnUpload.OnClientClick = "var f=document.getElementById('" + FupAttach.ClientID + "'); if(f.files.length == 0) { alert('Seleccione el archivo a adjuntar'); return false;} if(f.files[0].size <= " + (attachmentMaxSizeMB * 1048576) + ") return true; alert('El archivo no puede exceder de " + attachmentMaxSizeMB + "MB'); return false;";
navUpload.Visible = EnableUpload();
LoadFileList(processName, incident);
}
}
catch (Exception ex)
{
WriteLog(ex);
ShowErrorMessage(ex.Message);
}
}
protected void BtnGetFile_Click(object sender, ImageClickEventArgs e)
{
try
{
string fileName = ((WebControl)sender).Attributes["data-file-name"];
GetFile(ProcessName(), Incident(), fileName);
}
catch (Exception ex)
{
WriteLog(ex);
ShowErrorMessage(ex.Message);
}
}
protected void BtnDeleteFile_Click(object sender, ImageClickEventArgs e)
{
try
{
string fileName = ((WebControl)sender).Attributes["data-file-name"];
DeleteFile(ProcessName(), Incident(), fileName);
}
catch (Exception ex)
{
WriteLog(ex);
ShowErrorMessage(ex.Message);
}
}
protected void BtnUpload_Click(object sender, EventArgs e)
{
try
{
UploadFile(ProcessName(), Incident());
}
catch (Exception ex)
{
WriteLog(ex);
ShowErrorMessage(ex.Message);
}
}
private void LoadFileList(string processName, string incident)
{
AttachmentServiceClient client = new AttachmentServiceClient();
string[] files = client.GetFileList(processName, incident);
bool enableDelete = EnableDelete();
int styleView = StyleView();
LblCount.InnerText = files.Length.ToString();
view1.Visible = styleView == 1;
view2.Visible = styleView == 2;
if (styleView == 1)
{
RptFiles1.DataSource = from f in files
select new
{
FileName = f,
FileType = f.Substring(f.LastIndexOf(".") + 1),
EnableDelete = enableDelete
};
RptFiles1.DataBind();
}
if (styleView == 2)
{
RptFiles2.DataSource = from f in files
select new
{
FileName = f,
FileType = f.Substring(f.LastIndexOf(".") + 1),
EnableDelete = enableDelete
};
RptFiles2.DataBind();
}
}
private void GetFile(string processName, string incident, string fileName)
{
AttachmentServiceClient client = new AttachmentServiceClient();
byte[] fileData = client.GetFile(processName, incident, fileName);
if (fileData != null)
{
Response.ClearContent();
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
}
}
private void DeleteFile(string processName, string incident, string fileName)
{
AttachmentServiceClient client = new AttachmentServiceClient();
if (!client.DeleteFile(processName, incident, fileName))
throw new Exception("No se pudo eliminar el archivo");
LoadFileList(processName, incident);
}
private void UploadFile(string processName, string incident)
{
if (!FupAttach.HasFile)
return;
AttachmentServiceClient client = new AttachmentServiceClient();
client.UploadFile(processName, incident, FupAttach.FileName, FupAttach.FileBytes);
LoadFileList(processName, incident);
}
private void ShowErrorMessage(string message)
{
LblError.Visible = true;
LblError.InnerText = message;
}
private void LoadParameters()
{
if (string.IsNullOrEmpty(Request.QueryString.ToString()))
return;
string[] parameters = DecryptString(Server.UrlDecode(Request.QueryString.ToString())).Split('&');
foreach (string s in parameters)
{
string key = s.Substring(0, s.IndexOf("="));
string value = s.Substring(key.Length + 1);
ViewState[key] = value;
}
}
private string GetParameterValue(string parameterName)
{
const string pathKey = "SOFTWARE\\ParametrosProcesoUltimus";
string value = string.Empty;
RegistryKey rk = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32).OpenSubKey(pathKey);
if (rk != null)
{
value = (string)rk.GetValue(parameterName);
rk.Close();
}
return value;
}
private void WriteLog(Exception e)
{
const string applicationName = "UltimusAttachmentService";
try
{
string logDirectoryPath = LogPath();
if (!Directory.Exists(logDirectoryPath))
Directory.CreateDirectory(logDirectoryPath);
string logFilePath = Path.Combine(logDirectoryPath, applicationName + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
StreamWriter sw = new StreamWriter(logFilePath, true);
string message = string.Format("{0} \r\n {1}", e.Message, e.StackTrace);
sw.WriteLine(string.Format("\r\nFecha:{0} \r\n {1}", DateTime.Now, message));
sw.Close();
sw.Dispose();
}
catch
{ }
}
private string DecryptString(string message)
{
const string key = "ultimusPanama";
MD5CryptoServiceProvider HashProvider = null;
TripleDESCryptoServiceProvider TDESAlgorithm = null;
try
{
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(key));
TDESAlgorithm = new TripleDESCryptoServiceProvider() { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };
byte[] DataToDecrypt = Convert.FromBase64String(message);
return UTF8.GetString(TDESAlgorithm.CreateDecryptor().TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length));
}
catch(Exception ex)
{
WriteLog(ex);
return string.Empty;
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
private int AttachmentMaxSize()
{
return int.Parse(GetParameterValue("UltimusAttachmentMaxSize"));
}
private string ProcessName()
{
return (string)ViewState["process"];
}
private string Incident()
{
return (string)ViewState["incident"];
}
private bool EnableUpload()
{
return (string)ViewState["upload"] == "1";
}
private bool EnableDelete()
{
return (string)ViewState["delete"] == "1";
}
public bool VisibleTitleBar()
{
return (string)ViewState["title"] == "1";
}
public int StyleView()
{
return string.IsNullOrEmpty((string)ViewState["style"]) ? 1 : int.Parse((string)ViewState["style"]);
}
private string LogPath()
{
return GetParameterValue("RutaLogGenerados");
}
/*#region ATTACHMENTS
public static string attachments(string id, string urlAttachmentPage, string process, string incident, bool upload, bool delete, bool title, int style, int height)
{
string parameters = "process=" + process + "&incident=" + incident + "&upload=" + (upload ? "1" : "0") + "&delete=" + (delete ? "1" : "0") + "&title=" + (title ? "1" : "0") + "&style=" + style;
urlAttachmentPage += "?" + HttpUtility.UrlEncode(EncryptString(parameters));
string control = "";
return control;
}
#endregion*/
}
}