using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Club365Web.BaseClass;
using Club365.Common;
using Club365.Business;
using Club365.DataLinq;
using System.Globalization;
using Microsoft.Office.Interop.Excel;
using Microsoft.Reporting.WebForms;
using System.Data;
using System.Xml;
namespace Club365Web.Member
{
public partial class MemberImport : PageBase
{
/// <summary>
/// On PreInit page event
/// </summary>
/// <param name="e"></param>
protected override void OnPreInit(EventArgs e)
{
AuthenticationRequired = true;
base.OnPreInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDowns();
}
}
/// <summary>
/// Binds the drop downs.
/// </summary>
protected void BindDropDowns()
{
//get exclude fields
string fields = System.Configuration.ConfigurationManager.AppSettings["FieldsExcludeFromMemberexport"];
string[] excludeFields = fields.Split(',');
MemberManager objMemberManager;
try
{
ddlFields.Items.Clear();
objMemberManager = new MemberManager();
IEnumerable<string> columns = objMemberManager.GetColumnNameFromTable("persons");
foreach (string c in columns)
{
if (!excludeFields.Contains(c))
{
ListItem item = new ListItem(c, c);
ddlFields.Items.Add(item);
}
}
}
catch (Exception ex)
{
// Error logging
WriteSystemLog(AppConstant.EXCEPTION + ex.Message, Convert.ToChar(AppEnum.LogType.E.ToString()));
throw ex;
}
finally
{
objMemberManager = null;
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
MemberManager objMemberManager;
try
{
string ddlField = Request["ctl00$ContentPlaceHolder1$ddlFields"];
string[] ddlFields = ddlField.Split(',');
if (CurrentSession.SiteID != 0)
{
objMemberManager = new MemberManager();
System.Data.DataTable dt = (System.Data.DataTable)Session["Exceltable"];
int columns = dt.Columns.Count;
for (int i = 0; i < columns; i++)
{
dt.Columns[i].ColumnName = ddlFields[i];
}
bool isNotAllowNullFieldExist = true;
string allowFieldNotExsitErrorMessage = "";
if (!dt.Columns.Contains("PERSONID"))
{
isNotAllowNullFieldExist = false;
allowFieldNotExsitErrorMessage += "Fiele PERSONID not allow null"+",";
}
if (!dt.Columns.Contains("MEMBERTYPE"))
{
isNotAllowNullFieldExist = false;
allowFieldNotExsitErrorMessage += "Fiele MEMBERTYPE not allow null" + ",";
}
if (!dt.Columns.Contains("MEMBERSTATUS"))
{
isNotAllowNullFieldExist = false;
allowFieldNotExsitErrorMessage += "Fiele MEMBERSTATUS not allow null" + ",";
}
//check column that not allow null exsit
if (isNotAllowNullFieldExist)
{
int rows = dt.Rows.Count;
string fields = "siteid,SENDEINVOICE,";
if (!string.IsNullOrEmpty(ddlField))
{
fields += ddlField;
}
int notImportRows = 0;
string errorNo = "";
for (int i = 0; i < rows; i++)
{
string values = CurrentSession.SiteID.ToString() + "," + "0" + ",";
for (int j = 0; j < columns; j++)
{
if (dt.Columns[j].DataType.Name=="String")
{
values += "'" + dt.Rows[i][j].ToString()+"'"+",";
}
else
{
values += dt.Rows[i][j].ToString() + ",";
}
}
//prime key check
int personId = Convert.ToInt32(dt.Rows[i]["PERSONID"]);
var isPrimeKeyExsit = objMemberManager.IsPrimeKeyExisted(CurrentSession.SiteID, personId);
if (isPrimeKeyExsit)
{
notImportRows += 1;
errorNo += (i+1).ToString() + ",";
this.lbMessage.Text += string.Format("This personID has already exsited line {0}", i) +
",";
}
else
{
//check column name FIRSTNAME,LASTNAME,DATEOFBIRTH all exsit and it's value all exsit
if (ddlField.IndexOf("FIRSTNAME") != -1 && ddlField.IndexOf("LASTNAME") != -1 &&
ddlField.IndexOf("DATEOFBIRTH") != -1 && !(dt.Rows[i]["FIRSTNAME"] is System.DBNull) && !(dt.Rows[i]["LASTNAME"] is System.DBNull) && !(dt.Rows[i]["DATEOFBIRTH"] is System.DBNull) )
{
//if alread exsit and check box ticked, then update this item
if (objMemberManager.IsPersonExisted(dt.Rows[i]["FIRSTNAME"].ToString(),
dt.Rows[i]["LASTNAME"].ToString(),
Convert.ToDateTime(
dt.Rows[i]["DATEOFBIRTH"]))==1 && cbValidate.Checked)
{
//TODO: update item
//if (!objMemberManager.UpdatePersonInfo(fields,values,CurrentSession.SiteID,personId))
//{
// notImportRows += 1;
// errorNo += (i + 1).ToString() + ",";
//}
}
else
{
//import data
if (!objMemberManager.ImportDataIntoDatabase(fields, values.TrimEnd(',')))
{
notImportRows += 1;
errorNo += (i + 1).ToString() + ",";
}
}
}
else
{
//import data
if (!objMemberManager.ImportDataIntoDatabase(fields, values.TrimEnd(',')))
{
notImportRows += 1;
errorNo += (i + 1).ToString() + ",";
}
}
}
}
if (notImportRows > 0)
{
this.lbMessage.Text = notImportRows + " lines import failed, please check line: " +
errorNo.TrimEnd(',');
}
else
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message",
"<script language='javascript' defer>alert('Import succeed!');window.location='/Member/MemberImport.aspx'</script>");
}
}
else
{
this.lbMessage.Text = isNotAllowNullFieldExist.ToString().TrimEnd(',');
}
}
else
{
this.lbMessage.Text = "SiteID lost, please login in again.";
}
}
catch (Exception ex)
{
// Error logging
WriteSystemLog(AppConstant.EXCEPTION + ex.Message, Convert.ToChar(AppEnum.LogType.E.ToString()));
throw ex;
}
finally
{
objMemberManager = null;
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
ExcelUpload();
}
/// <summary>
/// upload file
/// </summary>
protected void ExcelUpload()
{
String filepath = "";
string fileExtName = "";
string mFileName = "";
string mPath = "";
if (fu_excel.PostedFile.FileName != "")
{
filepath = fu_excel.PostedFile.FileName;
fileExtName = filepath.Substring(filepath.LastIndexOf(".") + 1);
mPath = this.Request.PhysicalApplicationPath + "UpLoadFiles\\";
mFileName = filepath.Substring(filepath.LastIndexOf("\\") + 1);
if (!Directory.Exists(mPath))
{
try
{
Directory.CreateDirectory(mPath);
}
catch (Exception ex)
{
throw ex;
}
}
if (File.Exists(mPath + mFileName))
{
try
{
File.Delete(mPath + mFileName);
}
catch (Exception ex)
{
throw ex;
}
}
#region get file extension name
Boolean fileOK = false;
String fileExtension = System.IO.Path.GetExtension(fu_excel.FileName).ToLower();
if (fu_excel.HasFile)
{
//String fileExtension = System.IO.Path.GetExtension(fu_excel.FileName).ToLower();
String[] allowedExtensions = { ".xls",".xml" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
#endregion
#region Is file upload succeed?
bool fileUpOK = false;
if (fileOK)
{
try
{
fu_excel.PostedFile.SaveAs(mPath + mFileName);
fileUpOK = true;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
this.lbMessage.Text = "Upload file format error, should be. Xls or .Xml format";
}
#endregion
#region Excel will fill the dataset
if (fileUpOK)
{
System.Data.DataTable dt_User = new System.Data.DataTable();
try
{
if (fileExtension == ".xls")
{
dt_User = GetList(mPath + mFileName);
}
else if (fileExtension == ".xml")
{
dt_User = CXmlToDataTable(mPath + mFileName);
}
if (dt_User == null)
{
return;
}
}
catch (Exception ex)
{
throw ex;
}
int rowNum = 0;
try
{
rowNum = dt_User.Rows.Count;
}
catch (Exception ex)
{
throw ex;
}
if (rowNum == 0)
{
this.lbMessage.Text = "Excel table is empty, no data";
}
else
{
this.Panel1.Visible = false;
this.Panel2.Visible = true;
Session["Exceltable"] = dt_User;
string fields = "";
foreach (DataColumn dc in dt_User.Columns)
{
fields += dc.ColumnName + ",";
}
Session["fields"] = fields.TrimEnd(',');
}
}
#endregion
}
}
#region Get data from excel
/// <summary>
/// Gets the list.
/// </summary>
/// <param name="FilePath">The file path.</param>
/// <returns></returns>
public System.Data.DataTable GetList(string FilePath)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;";
string strSql = string.Empty;
Application app = new ApplicationClass();
Workbook workBook = app.Workbooks.Add(Type.Missing); ;
Worksheet workSheet = (Worksheet)workBook.Sheets.get_Item(1);
string workSheetName = string.Empty;
if (!File.Exists(FilePath))
{
this.lbMessage.Text = "Excel file specified path does not exist!";
}
Workbook tmpworkBook;
Worksheet tmpworkSheet;
try
{
object missing = System.Reflection.Missing.Value;
//open a WorkBook
tmpworkBook = app.Workbooks.Open(FilePath,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, missing);
// tmpworkSheet = (Worksheet) workBook.Sheets.get_Item ( 1 );
app.Visible = false;
tmpworkSheet = (Worksheet)tmpworkBook.Worksheets[1];
workSheetName = tmpworkSheet.Name;
if (workSheetName != "")
{
strSql = "select * from [" + workSheetName + "$]";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbDataAdapter myCommand = null;
myCommand = new OleDbDataAdapter(strSql, connectionString);
System.Data.DataTable dt = new System.Data.DataTable();
myCommand.Fill(dt);
conn.Close();
conn.Dispose();
return dt;
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
throw ex;
}
finally
{
Kill(app); //kill Excel process
}
}
public string Get_FistWorkBookName(string fileName)
{
Application app = new ApplicationClass();
Workbook workBook = app.Workbooks.Add(Type.Missing); ;
Worksheet workSheet = (Worksheet)workBook.Sheets.get_Item(1);
string rev = string.Empty;
if (!File.Exists(fileName))
{
this.lbMessage.Text = "Excel file specified path does not exist!";
}
Workbook tmpworkBook;
Worksheet tmpworkSheet;
try
{
object missing = System.Reflection.Missing.Value;
//open a WorkBook
tmpworkBook = app.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, missing);
// tmpworkSheet = (Worksheet) workBook.Sheets.get_Item ( 1 );
app.Visible = false;
tmpworkSheet = (Worksheet)tmpworkBook.Worksheets[1];
rev = tmpworkSheet.Name;
}
catch (Exception ex)
{
rev = "";
throw ex;
}
finally
{
tmpworkSheet = null;
tmpworkBook = null;
this.Dispose();
}
return rev;
}
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public void Kill(Application excel)
{
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}
#endregion
#region Get data from xml
public DataSet CXmlFileToDataSet(string xmlFilePath)
{
if (!string.IsNullOrEmpty(xmlFilePath))
{
string path = xmlFilePath;
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
XmlDocument xmldoc = new XmlDocument();
//根据地址加载Xml文件
xmldoc.Load(path);
DataSet ds = new DataSet();
//读取文件中的字符流
StrStream = new StringReader(xmldoc.InnerXml);
//获取StrStream中的数据
Xmlrdr = new XmlTextReader(StrStream);
//ds获取Xmlrdr中的数据
ds.ReadXml(Xmlrdr);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
//释放资源
if (Xmlrdr != null)
{
Xmlrdr.Close();
StrStream.Close();
StrStream.Dispose();
}
}
}
else
{
return null;
}
}
public System.Data.DataTable CXmlToDataTable(string xmlFilePath)
{
return CXmlFileToDataSet(xmlFilePath).Tables[0];
}
#endregion
}
}