initial add

This commit is contained in:
Jonathan Ouellette
2022-09-27 14:10:30 -07:00
parent 91fd8a50a9
commit 580e90f6a2
3941 changed files with 954648 additions and 19 deletions

View File

@ -0,0 +1,39 @@
using Fab2ApprovalSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
public class DemoHelper
{
public static List<string> GetCountries()
{
return new List<string>
{
"USA", "England", "Belguim", "France", "Italy"
};
}
public List<TestModel> ListOfModels = new List<TestModel>();
private static DemoHelper m_dHelper = new DemoHelper();
public static DemoHelper Instance
{
get { return m_dHelper; }
}
private DemoHelper()
{
TestModel A1 = new TestModel();
A1.Name = "Eran";
A1.Countries = new List<string>();
A1.Countries.Add("England");
A1.Countries.Add("Belguim");
ListOfModels.Add(A1);
}
}
}

View File

@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//using DFClib.DfException;
//using DFCLib.DfId;
//using DFCLib.IDfId;
//using DFCLib.IDfList;
//using DFCLib.IDfLoginInfo;
//using DFCLib.IDfClient;
//using DFCLib.IDfDocument;
//using DFCLib.IDfSession;
//using DFCLib.IDfSessionManager;
//using DFCLib.DfClientX;
//using DFCLib.IDfClientX;
//using DFCLib.IDfFile;
//using DFCLib.IDfImportNode;
//using DFCLib.IDfImportOperation;
namespace Fab2ApprovalSystem.Misc
{
public class Documentum
{
//public static void Process(string m_fileName)
//{
// String username = "rkotian1";
// String password = "";
// String repoName = "globaldocudms";
// String filename = m_fileName; // for example {"C:\\devprog\\ECN12345.zip"};
// String destFldrId = "0c00359980061536";
// try
// {
// DFCLib.IDfSessionManager sessMgr = createSessionManager();
// addIdentity(sessMgr, username, password, repoName);
// importFiles(sessMgr, repoName, filename, destFldrId);
// }
// catch (Exception ex)
// {
// //string s = ex.InnerException.ToString();
// }
//}
///**
// * Imports a single file in the repository
// *
// */
//private static void importFiles(DFCLib.IDfSessionManager sessMgr, String repoName, String filename, String destFldrId)
//{
// DFCLib.IDfSession sess = null;
// try
// {
// DFCLib.IDfClientX clientX = new DFCLib.DfClientX();
// DFCLib.IDfImportOperation impOper = clientX.getImportOperation();
// //DFCLib.IDfId destId = new DfId(destFldrId);
// DFCLib.IDfId destId = clientX.getId(destFldrId);
// //This will import all files to a single destination.
// //To import each file to a different destination
// //set call this method on the import node.
// //impOper.setDestinationFolderId(destId);
// DFCLib.IDfFile localFile = clientX.getFile(filename);
// DFCLib.IDfImportNode impNode = (DFCLib.IDfImportNode)impOper.add(localFile);
// //You can set different destination ids here for each import node
// //This way files get imported to different destinations.
// impNode.setDestinationFolderId(destId);
// //set custom object type. If not called dm_document is used.
// impNode.setDocbaseObjectType("dp_text");
// int randomName = ((int)(new Random().Next(int.MinValue, int.MaxValue) * 100));
// //set custom object name.
// impNode.setNewObjectName(localFile.getName() + "" + randomName.ToString());
// //The import operation determines the file format.
// //It is also possible to explicitly set the format.
// //impNode.setFormat("");
// sess = sessMgr.getSession(repoName);
// impOper.setSession(sess);
// if (impOper.execute())
// {
// Console.WriteLine("Import Operation Succeeded");
// DFCLib.IDfList newObjLst = impOper.getNewObjects();
// for (int i = 0; i < newObjLst.getCount(); i++)
// {
// DFCLib.IDfDocument newObj = (DFCLib.IDfDocument)newObjLst.get(i);
// //you can set any custom/standard attr values on the document now
// //newObj.setString("my_attr","someValue");
// //newObj.save();
// Console.WriteLine("Created Object: " + newObj.getObjectId());
// }
// }
// else
// {
// Console.WriteLine("Import Operation Failed");
// DFCLib.IDfList errList = impOper.getErrors();
// for (int i = 0; i < errList.getCount(); i++)
// {
// DFCLib.IDfOperationError err = (DFCLib.IDfOperationError)errList.get(i);
// Console.WriteLine(err.getMessage());
// }
// }
// }
// finally
// {
// if (sess != null)
// {
// sessMgr.release(sess);
// }
// }
//}
///**
// * Creates a new session manager instance. The session manager does not have
// * any identities associated with it.
// * @return a new session manager object.
//*/
//private static DFCLib.IDfSessionManager createSessionManager()
//{
// DFCLib.IDfClientX clientX = new DFCLib.DfClientX();
// DFCLib.IDfClient localClient = clientX.getLocalClient();
// DFCLib.IDfSessionManager sessMgr = localClient.newSessionManager();
// return sessMgr;
//}
///**
// * Adds a new identity to the session manager.
// *
// */
//private static void addIdentity(DFCLib.IDfSessionManager sm, String username,
// String password, String repoName)
//{
// DFCLib.IDfClientX clientX = new DFCLib.DfClientX();
// DFCLib.IDfLoginInfo li = clientX.getLoginInfo();
// li.setUser(username);
// li.setPassword(password);
// // check if session manager already has an identity.
// // if yes, remove it.
// if (sm.hasIdentity(repoName))
// {
// sm.clearIdentity(repoName);
// }
// sm.setIdentity(repoName, li);
//}
}
}

View File

@ -0,0 +1,736 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
public class EmailNotification
{
#region Variabls
protected string _subject = null;
protected string _TemplatesPath = null;
#endregion
/// <summary>
/// Email subject
/// </summary>
public string EmailSubject
{
set { _subject = value; }
}
/// <summary>
/// This function will read the content of a file name
/// </summary>
/// <param name="FileName">File Name</param>
/// <returns>String: Containing the Entire content of the file</returns>
protected string ReadEmailFile(string FileName)
{
string retVal = null;
try
{
//setting the file name path
string path = _TemplatesPath + FileName;
FileInfo TheFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
//check if the file exists in the location.
if (!TheFile.Exists)
throw new Exception("Could Not Find the file : " + FileName + " in the location " + _TemplatesPath); // throw an exception here.
//start reading the file. i have used Encoding 1256 to support arabic text also.
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(@path), System.Text.Encoding.GetEncoding(1256));
retVal = sr.ReadToEnd(); // getting the entire text from the file.
sr.Close();
}
catch (Exception ex)
{
throw new Exception("Error Reading File." + ex.Message);
}
return retVal;
}
/// <summary>
/// this function will send email. it will read the mail setting from the web.config
/// </summary>
/// <param name="SenderEmail">Sender Email ID</param>
/// <param name="SenderName">Sender Name</param>
/// <param name="Recep">Recepient Email ID</param>
/// <param name="cc">CC ids</param>
/// <param name="email_title">Email Subject</param>
/// <param name="email_body">Email Body</param>
protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body)
{
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
// setting the Sender Email ID
//msg.From = new MailAddress(SenderEmail, SenderName);
msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval");
msg.Sender = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval");
// adding the Recepient Email ID
msg.To.Add(Recep);
//msg.To.Add("Jonathan.Ouellette@infineon.com");
// add CC email ids if supplied.
if (!string.IsNullOrEmpty(cc))
msg.CC.Add(cc);
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient("mailrelay-external.infineon.com");
// sending the message.
try
{
SmtpMail.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="Recep"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachmentPath"></param>
protected void SendEmailWithAttachment(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, string attachmentPath)
{
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
// setting the Sender Email ID
msg.From = new MailAddress(SenderEmail, SenderName);
// adding the Recepient Email ID
msg.To.Add(Recep);
// add CC email ids if supplied.
if (!string.IsNullOrEmpty(cc))
msg.CC.Add(cc);
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
msg.Attachments.Add(new Attachment(attachmentPath));
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
#if(!DEBUG)
// sending the message.
SmtpMail.Send(msg);
#endif
}
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientList"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
protected void SendEmail(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body)
{
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
// setting the Sender Email ID
//msg.From = new MailAddress(SenderEmail, SenderName);
msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval");
// adding the Recepient Email ID
foreach (string recepient in RecepientList)
{
msg.To.Add(recepient);
}
// add CC email ids if supplied.
if (!string.IsNullOrEmpty(cc))
msg.CC.Add(cc);
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
// sending the message.
try
{
SmtpMail.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientList"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachmentPath"></param>
protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body, string attachmentPath)
{
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
// setting the Sender Email ID
msg.From = new MailAddress(SenderEmail, SenderName);
// adding the Recepient Email ID
foreach (string recepient in RecepientList)
{
if (recepient != null)
msg.To.Add(recepient);
}
// add CC email ids if supplied.
if (!string.IsNullOrEmpty(cc))
msg.CC.Add(cc);
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
msg.Attachments.Add(new Attachment(attachmentPath));
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
// sending the message.
SmtpMail.Send(msg);
}
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="Recep"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachments"></param>
protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List<string> attachments)
{
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
// setting the Sender Email ID
msg.From = new MailAddress(SenderEmail, SenderName);
// adding the Recepient Email ID
msg.To.Add(Recep);
// add CC email ids if supplied.
if (!string.IsNullOrEmpty(cc))
msg.CC.Add(cc);
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
foreach (string attachment in attachments)
{
msg.Attachments.Add(new Attachment(attachment));
}
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
#if(!DEBUG)
// sending the message.
SmtpMail.Send(msg);
#endif
}
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientList"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachments"></param>
protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body, List<string> attachments)
{
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
// setting the Sender Email ID
msg.From = new MailAddress(SenderEmail, SenderName);
// adding the Recepient Email ID
foreach (string recepient in RecepientList)
{
if (recepient != null)
msg.To.Add(recepient);
}
// add CC email ids if supplied.
if (!string.IsNullOrEmpty(cc))
msg.CC.Add(cc);
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
foreach (string attachment in attachments)
{
msg.Attachments.Add(new Attachment(attachment));
}
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
// sending the message.
SmtpMail.Send(msg);
}
public EmailNotification()
{
}
/// <summary>
/// The Constructor Function
/// </summary>
/// <param name="EmailHeaderSubject">Email Header Subject</param>
/// <param name="TemplatesPath">Emails Files Templates</param>
public EmailNotification(string EmailHeaderSubject, string TemplatesPath)
{
_subject = EmailHeaderSubject;
_TemplatesPath = TemplatesPath;
}
/// <summary>
/// This function will send the email notification by reading the email template and substitute the arguments
/// </summary>
/// <param name="EmailTemplateFile">Email Template File</param>
/// <param name="SenderEmail">Sender Email</param>
/// <param name="SenderName">Sender Name</param>
/// <param name="RecepientEmail">Recepient Email ID</param>
/// <param name="CC">CC IDs</param>
/// <param name="Subject">EMail Subject</param>
/// <param name="Args">Arguments</param>
/// <returns>String: Return the body of the email to be send</returns>
public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args)
{
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject + " for: " + RecepientEmail : _subject), retVal);
}
else
{
#if(!DEBUG)
SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
#endif
}
}
catch (Exception ex)
{
throw ex;
}
return retVal;
}
/// <summary>
/// This function will send the email notification by reading the email template and substitute the arguments along with the attachments
/// </summary>
/// <param name="EmailTemplateFile"></param>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientEmail"></param>
/// <param name="CC"></param>
/// <param name="Subject"></param>
/// <param name="attachmentPath"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args)
{
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachmentPath);
}
else
{
#if(!DEBUG)
SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath);
#endif
}
}
catch (Exception ex)
{
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
/// <param name="EmailTemplateFile"></param>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientEmail"></param>
/// <param name="CC"></param>
/// <param name="Subject"></param>
/// <param name="attachmentPath"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args)
{
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
foreach(string email in RecepientEmail)
{
Subject += email + ";";
}
RecepientEmail.Clear();
SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachmentPath);
}
else
{
#if (!DEBUG)
SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath);
#endif
}
}
catch (Exception ex)
{
throw ex;
}
return retVal;
}
/////////============================================================
public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, List<string> attachments, params string[] Args)
{
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachments);
}
else
{
#if(!DEBUG)
SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments);
#endif
}
}
catch (Exception ex)
{
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
/// <param name="EmailTemplateFile"></param>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientEmail"></param>
/// <param name="CC"></param>
/// <param name="Subject"></param>
/// <param name="attachmentPath"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, List<string> attachments, params string[] Args)
{
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
foreach(string email in RecepientEmail)
{
Subject += email + ";";
}
RecepientEmail.Clear();
SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachments);
}
else
{
#if (!DEBUG)
SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments);
#endif
}
}
catch (Exception ex)
{
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
/// <param name="EmailTemplateFile"></param>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientEmail"></param>
/// <param name="CC"></param>
/// <param name="Subject"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, params string[] Args)
{
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
foreach (string email in RecepientEmail)
{
Subject += email + ";";
}
RecepientEmail.Clear();
SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
}
else
{
#if (!DEBUG)
SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
#endif
}
}
catch (Exception ex)
{
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="importance"></param>
public void SendNotificationEmailToAdmin(string subject, string body, MailPriority importance)
{
try
{
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTP Server"]);
MailMessage msg = new MailMessage();
string toList = ConfigurationManager.AppSettings["Admin Notification Recepient"];
msg.From = new MailAddress(ConfigurationManager.AppSettings["Notification Sender"]); ;
string[] recipients = toList.Split(',');
foreach (string recipient in recipients)
msg.To.Add(new MailAddress(recipient.Trim()));
DateTime now = DateTime.Now;
string temp = now.ToString() + " - " + body;
msg.Subject = subject;
msg.Body = temp;
msg.Priority = importance;
//#if(!DEBUG)
client.Send(msg);
//#endif
}
catch (Exception ex)
{
throw ex;
}
}
public List<string> GetTestRecipientsList()
{
var r = new List<string>();
try
{
string emails = ConfigurationManager.AppSettings["Test Email Recipients"];
foreach (string s in emails.Split(';', ','))
{
if (!String.IsNullOrWhiteSpace(s))
r.Add(s);
}
}
catch
{
r.Add("dhuang2@infineon.com");
}
return r;
}
}
}

View File

@ -0,0 +1,144 @@
using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
public class ExcelData
{
string _path;
public ExcelData(string path)
{
_path = path;
}
public IExcelDataReader getExcelReader()
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
FileStream stream = File.Open(_path, FileMode.Open, FileAccess.Read);
// We return the interface, so that
IExcelDataReader reader = null;
try
{
if (_path.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
if (_path.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
return reader;
}
catch (Exception)
{
throw;
}
}
public class ExcelLotInfo
{
public string LotNo { get; set; }
public string LotDispo { get; set; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerable<ExcelLotInfo> ReadData()
{
var r = new List<ExcelLotInfo>();
var excelData = new ExcelData(_path);
var lots = excelData.getData().ToList();
int lotDispoColumnIndex = -1;
foreach (DataColumn col in lots[0].Table.Columns)
{
if (col.ColumnName.ToLower().Contains("dispo"))
{
lotDispoColumnIndex = col.Ordinal;
break;
}
}
foreach (var row in lots)
{
string temValue = row[0].ToString();
if (temValue.Trim().Length > 0 && temValue.Trim().Length <= 10 )
{
r.Add(new ExcelLotInfo()
{
LotNo = row[0].ToString(),
LotDispo = (lotDispoColumnIndex >= 0 ? row[lotDispoColumnIndex].ToString() : "")
});
}
}
return r;
}
public IEnumerable<string> ReadQDBFlagData()
{
List<string> s = new List<string>();
// We return the interface, so that
var excelData = new ExcelData(_path);
//var albums = excelData.getData("Sheet1");
var lotNos = excelData.getData();
foreach (var row in lotNos)
{
string temValue = row[0].ToString();
if (temValue.Trim().Length > 0 && temValue.Trim().Length == 9)
{
if (row[2].ToString().ToUpper() != "YES" && row[2].ToString().ToUpper() != "NO")
{
throw new Exception("Invalid data in the file");
}
else
{
s.Add(row[0].ToString() + "~" + row[1] + "~" + row[2]);
}
}
}
return s;
}
//public IEnumerable<DataRow> getData(string sheet, bool firstRowIsColumnNames = true)
//{
// var reader = this.getExcelReader();
// reader.IsFirstRowAsColumnNames = firstRowIsColumnNames;
// var workSheet = reader.AsDataSet().Tables[sheet];
// var rows = from DataRow a in workSheet.Rows select a;
// return rows;
//}
/// <summary>
///
/// </summary>
/// <param name="firstRowIsColumnNames"></param>
/// <returns></returns>
public IEnumerable<DataRow> getData(bool firstRowIsColumnNames = true)
{
var reader = this.getExcelReader();
reader.IsFirstRowAsColumnNames = firstRowIsColumnNames;
var workSheet = reader.AsDataSet().Tables[0];
var rows = from DataRow a in workSheet.Rows select a;
return rows;
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
class FTPWrapper
{
string m_OutputFile;
string m_DestinationFileName;
//Functions functions = new Functions();
public FTPWrapper(string outputFile, string destinationFileName)
{
m_OutputFile = outputFile;
m_DestinationFileName = destinationFileName;
}
/// <summary>
///
/// </summary>
public void FTPToSPN()
{
FTP ftpLib = new FTP();
//Connect to the FTP server
try
{
ftpLib.Connect(Functions.FTPServer(), Functions.FTPUser(), Functions.FTPPassword());
}
catch (Exception ec)
{
Functions.WriteEvent("Listener - ProcessFile(): FTP Connection Error " + m_OutputFile + " - " + ec.Source +
": " + ec.Message, System.Diagnostics.EventLogEntryType.Error);
}
//Upload the file
try
{
int pct = 0;
ftpLib.OpenUpload(m_OutputFile, m_DestinationFileName);
while (ftpLib.DoUpload() > 0)
pct = (int)((ftpLib.BytesTotal * 100) / ftpLib.FileSize);
Functions.WriteEvent(m_OutputFile + " was sucessfully FTPed to SPN.", System.Diagnostics.EventLogEntryType.Information);
}
catch (Exception eu)
{
Functions.WriteEvent("MRB - FTPToSPN(): FTP Upload Error " + m_OutputFile + " - " + eu.Source +
": " + eu.Message, System.Diagnostics.EventLogEntryType.Error);
throw new Exception(eu.Source + ": " + eu.Message);
}
}
}
}

View File

@ -0,0 +1,450 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.IO;
using System.Net.Mail;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace Fab2ApprovalSystem.Misc
{
public static class Functions
{
/// <summary>
/// Writes to the Application Event Log and sends an email notification if appropriate
/// </summary>
/// <param name="logtext"></param>
/// <param name="eventType"></param>
public static void WriteEvent(string logtext, System.Diagnostics.EventLogEntryType eventType)
{
//#if(!DEBUG)
EmailNotification en = new EmailNotification();
EventLog ev = new EventLog("Application");
ev.Source = "Fab Approval System";
try
{
//Write to the Event Log
ev.WriteEntry(logtext, eventType);
////Send an email notification if appropriate
////Don't attempt to send an email if the error is pertaining to an email problem
if (!logtext.Contains("SendEmailNotification()"))
{
//Only send email notifications for Error and Warning level events
if (eventType == System.Diagnostics.EventLogEntryType.Error)
en.SendNotificationEmailToAdmin(ev.Source + " - Error Notification", logtext, MailPriority.High);
//else if (eventType == System.Diagnostics.EventLogEntryType.Warning)
// SendEmailNotification(ErrorRecipient(), ev.Source + " Warning Event Logged", logtext, NORMAL_PRI);
}
}
catch
{
//throw;
}
finally
{
ev = null;
}
//#endif
}
/// <summary>
/// Returns the FTP Server Name
/// </summary>
/// <returns></returns>
public static string FTPServer()
{
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTP Server"];
}
/// <summary>
/// Returns the FTP User Name
/// </summary>
/// <returns></returns>
public static string FTPUser()
{
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTP User"];
}
/// <summary>
/// Returns the FTP Password
/// </summary>
/// <returns></returns>
public static string FTPPassword()
{
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTP Password"];
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string GetAttachmentFolder()
{
ConfigurationManager.RefreshSection("appSettings");
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
return ConfigurationManager.AppSettings["AttachmentFolderTest"];
}
else
return ConfigurationManager.AppSettings["AttachmentFolder"];
}
/// <summary>
///
/// </summary>
/// <param name="oldECNNumber"></param>
/// <param name="newECNNumber"></param>
public static void CopyAttachments(int oldECNNumber, int newECNNumber)
{
// The Name of the Upload component is "files"
string oldFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + oldECNNumber.ToString();
string newFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + newECNNumber.ToString() ;
DirectoryInfo newdi = new DirectoryInfo(newFolderPath);
if (!newdi.Exists)
newdi.Create();
FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath ).GetFiles();
foreach (FileInfo file in existingFiles)
{
if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString()))
//var fileName = Path.GetFileName(file.FullName);
file.CopyTo(Path.Combine(newFolderPath, file.Name));
}
}
/// <summary>
///
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public static bool CheckITARAccess(string userID)
{
MembershipProvider domainProvider = Membership.Providers["ADMembershipProvider"];
MembershipUser mu = domainProvider.GetUser(userID, false);
if (mu == null)
return false;
else
return true;
}
/// <summary>
///
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public static bool NA_HasITARAccess(string userID, string pwd)
{
string ECDomain = ConfigurationManager.AppSettings["ECDomain"];
string ECADGroup = ConfigurationManager.AppSettings["ECADGroup"];
string naContainer = ConfigurationManager.AppSettings["NAContainer"];
string naDomain = ConfigurationManager.AppSettings["NADomain"];
//WriteEvent("NA - Before PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextGroup = new PrincipalContext(ContextType.Domain, ECDomain);
//WriteEvent("NA - After PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("NA - Before PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
naDomain,
naContainer,
ContextOptions.Negotiate, userID, pwd);
//WriteEvent("NA - After PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("NA - Before check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(contextGroup, ECADGroup);
//WriteEvent("NA - After check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("NA - Before check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
//WriteEvent("NA - After check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
if (null == up)
{
//WriteEvent("NA - User not in NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
return false;
}
else
{
//WriteEvent("NA - Member of EC group is " + up.IsMemberOf(gp).ToString() + " for " + userID, System.Diagnostics.EventLogEntryType.Information);
return up.IsMemberOf(gp);
}
}
//public static bool NA_GetUsers()
//{
// //string ECDomain = ConfigurationManager.AppSettings["ECDomain"];
// //string ECADGroup = ConfigurationManager.AppSettings["ECADGroup"];
// string naContainer = ConfigurationManager.AppSettings["NAContainer"];
// string naDomain = ConfigurationManager.AppSettings["NADomain"];
// //WriteEvent("NA - Before PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //PrincipalContext contextGroup = new PrincipalContext(ContextType.Domain, ECDomain);
// //WriteEvent("NA - After PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //WriteEvent("NA - Before PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
// PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
// naDomain,
// naContainer,
// ContextOptions.Negotiate, userID, pwd);
// //WriteEvent("NA - After PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //WriteEvent("NA - Before check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// GroupPrincipal gp = GroupPrincipal.FindByIdentity(contextGroup, ECADGroup);
// //WriteEvent("NA - After check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //WriteEvent("NA - Before check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
// //WriteEvent("NA - After check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// if (null == up)
// {
// //WriteEvent("NA - User not in NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
// return false;
// }
// else
// {
// //WriteEvent("NA - Member of EC group is " + up.IsMemberOf(gp).ToString() + " for " + userID, System.Diagnostics.EventLogEntryType.Information);
// return up.IsMemberOf(gp);
// }
//}
public static bool IFX_HasITARAccess(string userID, string pwd)
{
string ECDomain = ConfigurationManager.AppSettings["ECDomain"];
string ECADGroup = ConfigurationManager.AppSettings["ECADGroup"];
string ifxcontainer = ConfigurationManager.AppSettings["IFXContainer"];
string ifxdomain = ConfigurationManager.AppSettings["IFXDomain"];
//WriteEvent("IFX - Before PrincipalContext for EC for user " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextGroup = new PrincipalContext(ContextType.Domain, ECDomain);
//WriteEvent("IFX - After PrincipalContext for EC for user " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("IFX - Before PrincipalContext for IFX for user " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
ifxdomain,
ifxcontainer,
ContextOptions.Negotiate, userID, pwd);
//WriteEvent("IFX - After PrincipalContext for IFX for user " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("IFX - Before check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(contextGroup, ECADGroup);
//WriteEvent("IFX - After check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("IFX - Before check user in IFX for " + userID, System.Diagnostics.EventLogEntryType.Information);
UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
//WriteEvent("IFX - After check user in IFX for " + userID, System.Diagnostics.EventLogEntryType.Information);
if (null == up)
{
//WriteEvent("IFX - not a member of IFX for " + userID, System.Diagnostics.EventLogEntryType.Information);
return false;
}
else
{
//WriteEvent("IFX - Member of EC group is " + up.IsMemberOf(gp).ToString() + " for " + userID, System.Diagnostics.EventLogEntryType.Information);
return up.IsMemberOf(gp);
}
}
/// <summary>
///
/// </summary>
/// <param name="userID"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static bool NA_ADAuthenticate(string userID, string pwd)
{
string naContainer = ConfigurationManager.AppSettings["NAContainer"];
string naDomain = ConfigurationManager.AppSettings["NADomain"];
try
{
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
naDomain,
naContainer,
ContextOptions.Negotiate, userID, pwd);
UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
if (null == up)
return false;
else
return true;
}
catch
{
return false;
}
}
/// <summary>
///
/// </summary>
/// <param name="userID"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static bool IFX_ADAuthenticate(string userID, string pwd)
{
string container = ConfigurationManager.AppSettings["IFXContainer"];
string domain = ConfigurationManager.AppSettings["IFXDomain"];
try
{
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
domain,
container,
ContextOptions.Negotiate, userID, pwd);
UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
if (null == up)
return false;
else
return true;
}
catch
{
return false;
}
}
public static string FTPSPNBatch()
{
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTPSPNBatchFileName"];
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string FTPSPNBatch_Test()
{
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"];
}
/// <summary>
///
/// </summary>
/// <param name="casection"></param>
/// <returns></returns>
public static string CASectionMapper(GlobalVars.CASection casection)
{
switch (casection)
{
case GlobalVars.CASection.D1:
return "D1";
case GlobalVars.CASection.D2:
return "D2";
case GlobalVars.CASection.D3:
return "D3";
case GlobalVars.CASection.D4:
return "D4";
case GlobalVars.CASection.D5:
return "D5";
case GlobalVars.CASection.D6:
return "D6";
case GlobalVars.CASection.D7:
return "D7";
case GlobalVars.CASection.D8:
return "D8";
case GlobalVars.CASection.CF: // CA Findings
return "CF";
}
return "";
}
public static string DocumentTypeMapper(GlobalVars.DocumentType docType)
{
switch (docType)
{
case GlobalVars.DocumentType.Audit:
return "Audit";
case GlobalVars.DocumentType.ChangeControl:
return "ChangeControl";
case GlobalVars.DocumentType.CorrectiveAction:
return "CorrectiveAction";
case GlobalVars.DocumentType.ECN:
return "ECN";
case GlobalVars.DocumentType.EECN:
return "EECN";
case GlobalVars.DocumentType.LotDisposition:
return "LotDisposition";
case GlobalVars.DocumentType.MRB:
return "MRB";
case GlobalVars.DocumentType.TECNCancelledExpired:
return "TECNCancelledExpired";
}
return "";
}
/// <summary>
/// Converts the CA No to the C00000 format
/// </summary>
/// <param name="caNo"></param>
/// <returns></returns>
public static string ReturnCANoStringFormat(int caNo)
{
string caNoString = "";
if(caNo == 0)
return "";
caNoString = "C" + caNo.ToString().PadLeft(5, '0');
return caNoString;
}
public static string ReturnAuditNoStringFormat(int auditNo)
{
string auditNoString = "";
if (auditNo == 0)
return "";
auditNoString = "A" + auditNo.ToString().PadLeft(5, '0');
return auditNoString;
}
public static string ReturnPartsRequestNoStringFormat(int PRNumber)
{
if (PRNumber == 0)
return "";
return String.Format("PR{0:000000}", PRNumber);
}
}
}

View File

@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
public class GlobalVars
{
public int USER_ID;
public const string SESSION_USERNAME = "UserName";
public const string ApplicationName = "LotDisposition";
public const string SESSION_USERID = "UserID";
public const string ECN_VIEW_OPTION = "ECN_ViewOption";
public const string IS_ADMIN = "IsAdmin";
public const string OOO = "OOO";
public const string SUCCESS = "Success";
public const string CAN_CREATE_PARTS_REQUEST = "CanCreatePartsRequest";
public static bool USER_ISADMIN = false;
public static string hostURL = "";
public static string DBConnection = "TEST";
public static string AttachmentUrl = "";
public static string NDriveURL = "";
public static string WSR_URL = "";
public static string CA_BlankFormsLocation = "";
public static string MesaTemplateFiles = "D:\\WebSites\\FabApprovalAttachments\\Template5Why";
//public static string DevWebSiteUrl = "";
//public static string ProdWebSiteUrl = "";
//public static string DevAttachmentUrl = "";
//public static string ProdAttachmentUrl = "";
public static string LOT_NO = "LotNo";
public static string LOCATION = "Location";
public static string SENDER_EMAIL = "MesaFabApproval@infineon.com";
//public static List<UserProfileDTO> UserProfileDTO { get; set; }
public enum LotStatusOption
{
Release = 1,
Scrap,
NotAvailable,
M_Suffix,
Select_Wafers,
CloseToQDB,
SplitOffHold
}
public enum ApprovalOption
{
Pending = 0,
Approved = 1,
Denied = 2,
Waiting = 3, //waiting on other approver to approve first
Skipped = 4, //set to this state if the original approval is no longer needed.
ReAssigned = 5, //set to this state if current approver got reassigned
Terminated = 6, //future use
Closed = 7,
Recalled = 8
}
public enum WorkFLowStepNumber
{
Step1 = 1,
Step2,
Step3
}
public enum DocumentType
{
LotDisposition = 1,
MRB=2,
ECN=3,
EECN = 4,
TECNCancelledExpired = 5,
LotTraveler = 6,
ChangeControl = 7,
Audit = 8,
CorrectiveAction = 9,
PartsRequest = 10,
CorrectiveActionSection = 12
}
public enum TECNExpirationCancellation
{
Cancellation = 1,
Expiration = 2
}
public enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
public enum NotificationType
{
WorkRequest = 1,
LotTraveler = 2
}
public enum CASection
{
D1, D2, D3, D4, D5,D6, D7, D8, CF
}
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
public class LotNoTemplate
{
public string LotNo { get; set; }
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Fab2ApprovalSystem.Misc
{
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
HttpContext ctx = HttpContext.Current;
// check if session is supported
if (session[GlobalVars.SESSION_USERNAME] == null)
{
// check if a new session id was generated
// this will force MVC to use the standard login redirect, enabling ReturnURL functionality
System.Web.Security.FormsAuthentication.SignOut();
filterContext.Result = new System.Web.Mvc.HttpUnauthorizedResult();
return;
}
base.OnActionExecuting(filterContext);
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
//public class UserProfileDTO
//{
// public int SysUserId { get; set; }
// public string UserName { get; set; }
// public string FullName { get; set; }
//}
public static class CollectionExtensions
{
public static IEnumerable<T> SetValue<T>(this IEnumerable<T> items, Action<T> updateMethod)
{
foreach (T item in items)
{
updateMethod(item);
}
return items;
}
}
}

View File

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
namespace Fab2ApprovalSystem.Misc
{
/// <summary>
///
/// </summary>
public class Zipper
{
/// <summary>
/// Compresses the files in the nominated folder, and creates a zip file on disk named as outPathname.
/// </summary>
/// <param name="outPathname"></param>
/// <param name="folderName"></param>
public void CreateZip(string outPathname, string folderName) {
// TODO Try and Catch block
FileStream fsOut = File.Create(outPathname);
ZipOutputStream zipStream = new ZipOutputStream(fsOut);
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
//zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES.
// This setting will strip the leading part of the folder path in the entries, to
// make the entries relative to the starting folder.
// To include the full path for each entry up to the drive root, assign folderOffset = 0.
int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1);
CompressFolder(folderName, zipStream, folderOffset);
zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
zipStream.Close();
}
/// <summary>
/// Recurses down the folder structure
/// </summary>
/// <param name="path"></param>
/// <param name="zipStream"></param>
/// <param name="folderOffset"></param>
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset)
{
// TODO Try and Catch block
string[] files = Directory.GetFiles(path);
foreach (string filename in files)
{
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity
// Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
// A password on the ZipOutputStream is required if using AES.
// newEntry.AESKeySize = 256;
// To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
// you need to do one of the following: Specify UseZip64.Off, or set the Size.
// If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
// but the zip will be in Zip64 format which not all utilities can understand.
// zipStream.UseZip64 = UseZip64.Off;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
// the "using" will close the stream even if an exception occurs
byte[] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename))
{
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[] folders = Directory.GetDirectories(path);
foreach (string folder in folders)
{
CompressFolder(folder, zipStream, folderOffset);
}
}
}
}

File diff suppressed because it is too large Load Diff