protected void InsertPhoneNumber() { try { StringBuilder sbSqlStmt = new StringBuilder(); sbSqlStmt.AppendFormat("INSERT INTO MasterDNC (PhoneNum,DateTimeOfImport) VALUES ('{0}','{1}')", hdnPhone.Value, DateTime.Now); string sqlStmt = sbSqlStmt.ToString(); ActivityLogger.WriteAdminEntry(null, "Insert Statement to Execute: '{0}'", sqlStmt); //string campaignMasterDBConn = ConfigurationManager.AppSettings["MasterConnectionString"]; //dsMainGrid.ConnectionString = campaignMasterDBConn; dsMainGrid.ConnectionString = ConfigurationManager.AppSettings["MasterConnectionString"]; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); hdnAction.Value = "add"; //hdnPhone.Value = txtPhoneNumber.Text; Response.Redirect("~/Campaign/MasterDNC.aspx?action=add&phonenumber=" + txtPhoneNumber.Text); } catch (Exception ex) { PageMessage = "Exception adding record: " + ex.Message; } }
protected void DeletePhoneNumber() { try { StringBuilder sbSqlStmt = new StringBuilder(); sbSqlStmt.AppendFormat("DELETE FROM MasterDNC Where PhoneNum = '{0}'", hdnPhoneDelete.Value); string sqlStmt = sbSqlStmt.ToString(); ActivityLogger.WriteAdminEntry(null, "Delete Statement to Execute: '{0}'", sqlStmt); //string campaignMasterDBConn = ConfigurationManager.AppSettings["MasterConnectionString"]; //dsMainGrid.ConnectionString = campaignMasterDBConn; dsMainGrid.ConnectionString = ConfigurationManager.AppSettings["MasterConnectionString"]; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); hdnPhoneDelete.Value = txtPhoneNumber.Text; Response.Redirect("~/Campaign/MasterDNC.aspx?action=delete&phonenumber=" + txtPhoneNumber.Text); } catch (Exception ex) { PageMessage = "Exception adding record: " + ex.Message; } }
protected void lbtnShutdown_Click(object sender, EventArgs e) { ActivityLogger.WriteAdminEntry(null, "Admin Action: lbtnShutdown button clicked by Admin. Global shutdown to idle all campaigns has been initiated."); CampaignService campaignService = new CampaignService(); campaignService.ShutdownAllCampaigns(); }
//------------------------------------------------------------- // // //------------------------------------------------------------- /*protected void grdDataPortal_EditCommand(object source, DataGridCommandEventArgs e) * { * ActivityLogger.WriteAdminEntry(null, "grdDataPortal_EditCommand '{0}'", "triggered"); * * //----------------------------------------------------- * // Don: forcing the name to away, back to numbers * // for the result codes. * //----------------------------------------------------- * * * BuildFieldList(); * BuildDataGridQuery(); * * grdDataPortal.EditItemIndex = e.Item.ItemIndex; * grdDataPortal.Columns[1].Visible = false; * BindDataGrid(); * * * }*/ //------------------------------------------------------------- // // //------------------------------------------------------------- /*protected void grdDataPortal_CancelEdit(object source, DataGridCommandEventArgs e) * { * BuildFieldList(); * BuildDataGridQuery(); * * grdDataPortal.EditItemIndex = -1; * grdDataPortal.Columns[1].Visible = true; * BindDataGrid(); * } * * //------------------------------------------------------------- * // * // * //------------------------------------------------------------- * protected void grdDataPortal_UpdateRecord(object source, DataGridCommandEventArgs e) * { * ActivityLogger.WriteAdminEntry(null, "grdDataPortal_UpdateRecord '{0}'", "triggered"); * try * { * bool bContinue = true; * * * * if (Session["GridFields"] != null) * { * StringBuilder sbSqlStmt = new StringBuilder(); * string[] strFieldNames = Session["GridFields"].ToString().Split(','); * sbSqlStmt.AppendFormat("UPDATE MasterDNC SET "); * * // Formatting as sql string types for now ... handle data types? * sbSqlStmt.AppendFormat("{0} = '{1}'", strFieldNames[0].Trim(), ((TextBox)e.Item.Cells[3].Controls[0]).Text.prepSQL()); * //DataRow dr = ((DataRowView)e.Item.DataItem).Row; * * for (int i = 3; i < (e.Item.Cells.Count - 1); i++) * { * if (((TextBox)e.Item.Cells[i].Controls[0]).Text.Length > 0) * sbSqlStmt.AppendFormat(", {0} = '{1}'", strFieldNames[i - 2].Trim(), ((TextBox)e.Item.Cells[i].Controls[0]).Text.prepSQL()); * else * sbSqlStmt.AppendFormat(", {0} = NULL", strFieldNames[i - 2].Trim()); * } * * sbSqlStmt.AppendFormat(" WHERE UniqueKey = {0}", ((TextBox)e.Item.Cells[e.Item.Cells.Count - 2].Controls[0]).Text.prepSQL()); * * string sqlStmt = sbSqlStmt.ToString(); * string campaignMasterDBConn = ConfigurationManager.AppSettings["MasterConnectionString"]; * dsMainGrid.ConnectionString = "Server=leadsweeper-dev\\SQLEXPRESS;Database=RainmakerMaster;User Id=sa;Password=R@inM@ker;"; * dsMainGrid.SelectCommand = sqlStmt; * dsMainGrid.Select(DataSourceSelectArguments.Empty); * /* * D. Pollastrini * 2012-04-18 * * Update validation code to determine whether CallResultCode is NULL or digits. If so, OK to continue. */ //bContinue = new Regex(@"CallResultCode\s*=\s*(NULL|'\d+'),").IsMatch(sqlStmt); /*if (bContinue == true) * { * ActivityLogger.WriteAdminEntry(null, "Update Statement to Execute: '{0}'", sqlStmt); * dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; * dsMainGrid.SelectCommand = sqlStmt; * dsMainGrid.Select(DataSourceSelectArguments.Empty); * * } * else * { * PageMessage = "Invalid Call Result Code - numeric value required."; * bContinue = false; * }*/ /*} * * if (bContinue == true) * { * BuildFieldList(); * BuildDataGridQuery(); * * grdDataPortal.EditItemIndex = -1; * grdDataPortal.Columns[1].Visible = true; * BindDataGrid(); * * } * } * catch (Exception ex) * { * PageMessage = "Exception updating record: " + ex.Message; * * } * }*/ protected void grdDataPortal_DeleteRecord(object source, DataGridCommandEventArgs e) { // Update the database here try { string[] strFieldNames = Session["GridFields"].ToString().Split(','); int ColumnCount = 0; foreach (string str in strFieldNames) { ColumnCount++; } StringBuilder sbSqlStmt = new StringBuilder(); sbSqlStmt.AppendFormat("DELETE FROM MasterDNC "); sbSqlStmt.AppendFormat(" WHERE UniqueKey = {0}", e.Item.Cells[ColumnCount].Text); string sqlStmt = sbSqlStmt.ToString(); ActivityLogger.WriteAdminEntry(null, "Delete Statement to Execute: '{0}'", sqlStmt); //string campaignMasterDBConn = ConfigurationManager.AppSettings["MasterConnectionString"]; //dsMainGrid.ConnectionString = campaignMasterDBConn; dsMainGrid.ConnectionString = ConfigurationManager.AppSettings["MasterConnectionString"]; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); lblMessage.Text = "Phone number " + e.Item.Cells[ColumnCount + 1].Text + " has been successfully deleted."; txtPhoneNumber.Focus(); BuildFieldList(); BuildDataGridQuery(); grdDataPortal.EditItemIndex = -1; BindDataGrid(); } catch (Exception ex) { PageMessage = "Exception deleting record: " + ex.Message; } }
/// <summary> /// It plays the selected wave file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { Campaign objCampaign = (Campaign)Session["Campaign"]; if (Request.QueryString["IsEditAudioFileName"] != null) { //string strFilePath = Request.Url.ToString(); //strFilePath = strFilePath.Substring(0, strFilePath.IndexOf("/Campaign")); //Audio = strFilePath + Request.QueryString["IsEditAudioFileName"].ToString(); Audio = Request.QueryString["IsEditAudioFileName"].ToString(); ActivityLogger.WriteAdminEntry(objCampaign, "Playing media file: '{0}'", Audio); //Audio = Audio.Replace(@"\\\\", @"\"); hdnFileToPlay.Value = Audio; //lblFileToPlay.Text = Audio; } if (Request.QueryString["IsBrowseAudioFileName"] != null) { Audio = Request.QueryString["IsBrowseAudioFileName"].ToString(); } }
/// <summary> /// Bind Queries. /// </summary> private void BindQueries(Campaign objCampaign, bool IsActive) { //if (IsCampaignRunning()) //{ // Isrunning = true; //} DataSet dsQuerList; try { CampaignService objCampService = new CampaignService(); XmlDocument xDocCampaign = new XmlDocument(); xDocCampaign.LoadXml(Serialize.SerializeObject(objCampaign, "Campaign")); ActivityLogger.WriteAdminEntry(objCampaign, "Getting campaign query status, generic."); dsQuerList = objCampService.GetCampaignQueryStatus(xDocCampaign); DataView dvQueries = new DataView(); try { SetQueryStatsInPerc(objCampaign); } catch { } // Added 11/12/10 for preventing 0 available queries to be activated - enhancement DataView dvExhaustedQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1 AND Available = 0"); if (dvExhaustedQueries == null) { PageMessage = "This campaign has no queries, please create a dialing query to begin dialing."; return; } if (dvExhaustedQueries.Count > 0) { DataRowView dr = dvExhaustedQueries[0]; long campaignQueryStatusId = Convert.ToInt64(dr["CampaignQueryID"]); string queryName = dr["QueryName"].ToString(); UpdateQueryStatus(campaignQueryStatusId, false, false, false); ActivityLogger.WriteAdminEntry(objCampaign, "Getting campaign query status, exhausted queries exist."); dsQuerList = objCampService.GetCampaignQueryStatus(xDocCampaign); PageMessage = string.Format("\"{0}\" has no available numbers, it will remain on hold.", queryName, campaignQueryStatusId); ActivityLogger.WriteAdminEntry(objCampaign, "Query '{0}' has no available numbers when user attempted to activate, moving to on hold.", queryName, campaignQueryStatusId); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "QueryAlert", "alert('" + PageMessage + "');", true); } if (IsActive) { dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1"); dvQueries.Sort = "DateModified ASC"; grdActiveQueries.DataSource = dvQueries; grdActiveQueries.DataBind(); } else { dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1"); dvQueries.Sort = "DateModified ASC"; grdActiveQueries.DataSource = dvQueries; grdActiveQueries.DataBind(); dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 AND IsStandby = 1"); dvQueries.Sort = "DateModified ASC"; grdStandbyQueries.DataSource = dvQueries; grdStandbyQueries.DataBind(); dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 OR IsActive = 1"); dvQueries.Sort = "DateModified ASC"; grdAllQueries.DataSource = dvQueries; grdAllQueries.DataBind(); } if (grdActiveQueries.Items.Count < 1) { lblNoActive.Visible = true; grdActiveQueries.Visible = false; } else { lblNoActive.Visible = false; grdActiveQueries.Visible = true; } if (grdStandbyQueries.Items.Count < 1) { lblNoStanByQueries.Visible = true; grdStandbyQueries.Visible = false; } else { lblNoStanByQueries.Visible = false; grdStandbyQueries.Visible = true; } // *** Bonus add query conditions as tooltips dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 1"); dvQueries.Sort = "Priority ASC"; for (int i = 0; i < grdActiveQueries.Items.Count; i++) { LinkButton lbtnQuery = (LinkButton)grdActiveQueries.Items[i].FindControl("lbtnQuery"); string strSubQueryConditions = dvQueries.Table.Rows[i]["QueryCondition"].ToString();; string strFilteredSubQueryConditions = ""; if (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } if (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } strFilteredSubQueryConditions = strFilteredSubQueryConditions.Trim(); lbtnQuery.ToolTip = strFilteredSubQueryConditions; } dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 AND IsStandby = 1"); dvQueries.Sort = "Priority ASC"; for (int i = 0; i < grdStandbyQueries.Items.Count; i++) { LinkButton lbtnQuery = (LinkButton)grdStandbyQueries.Items[i].FindControl("lbtnQuery"); string strSubQueryConditions = dvQueries.Table.Rows[i]["QueryCondition"].ToString();; string strFilteredSubQueryConditions = ""; if (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } if (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } strFilteredSubQueryConditions = strFilteredSubQueryConditions.Trim(); lbtnQuery.ToolTip = strFilteredSubQueryConditions; } dvQueries = FilterData(dsQuerList.Tables[0], "IsActive = 0 OR IsActive = 1"); dvQueries.Sort = "Priority ASC"; for (int i = 0; i < grdAllQueries.Items.Count; i++) { LinkButton lbtnQuery = (LinkButton)grdAllQueries.Items[i].FindControl("lbtnQuery"); string strSubQueryConditions = dvQueries.Table.Rows[i]["QueryCondition"].ToString();; string strFilteredSubQueryConditions = ""; if (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("And ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } if (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") > 0) { strFilteredSubQueryConditions = strSubQueryConditions.Substring((strSubQueryConditions.IndexOf("WHERE (") + 7), (strSubQueryConditions.IndexOf("AND ((DATEPART(hour, GETDATE()) < 13") - (strSubQueryConditions.IndexOf("WHERE (") + 7))); } strFilteredSubQueryConditions = strFilteredSubQueryConditions.Trim(); lbtnQuery.ToolTip = strFilteredSubQueryConditions; } } catch (Exception ex) { ActivityLogger.WriteException(ex, "Admin"); } }
protected void grdCampaignFields_DeleteRecord(object source, DataGridCommandEventArgs e) { Campaign objCampaign; if (Session["Campaign"] != null) { objCampaign = (Campaign)Session["Campaign"]; anchHome.InnerText = objCampaign.Description;// Replaced Short description if (IsCampaignRunning()) { Isrunning = true; } } if (Isrunning) { PageMessage = "Fields may not be changed while the campaign is running. Please stop the campaign and try again."; return; } // Update the database here try { if (Session["Campaign"] != null) { // we have an existing campaign currentCampaign = (Campaign)Session["Campaign"]; } string strOriginalFieldName = ""; dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = string.Format("SELECT FieldName FROM CampaignFields WHERE FieldID = {0}", e.Item.Cells[7].Text); DataView dv1 = (DataView)dsMainGrid.Select(DataSourceSelectArguments.Empty); DataRow dr = dv1.Table.Rows[0]; strOriginalFieldName = dr["FieldName"].ToString(); // Udelete the field in the campaign table StringBuilder sbSqlStmt2 = new StringBuilder(); sbSqlStmt2.AppendFormat("ALTER TABLE Campaign DROP COLUMN {0}", strOriginalFieldName); string sqlStmt = sbSqlStmt2.ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "Change columns Statement to Execute: '{0}'", sqlStmt); dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); StringBuilder sbSqlStmt = new StringBuilder(); sbSqlStmt.AppendFormat("DELETE FROM CampaignFields "); sbSqlStmt.AppendFormat(" WHERE FieldID = {0}", e.Item.Cells[7].Text); sqlStmt = sbSqlStmt.ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "Delete statement to execute: '{0}'", sqlStmt); dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); string sortDirection = (string)Session["SortDir"]; string sortQueryAppend = ""; if (Session["SortExp"] != null) { if (Session["SortExp"].ToString().Length > 0) { sortQueryAppend = string.Format(" ORDER BY {0} {1}", Session["SortExp"].ToString(), sortDirection); } } grdCampaignFields.EditItemIndex = -1; BindDataGrid(sortQueryAppend); } catch (Exception ex) { PageMessage = "Exception deleting record: " + ex.Message; } }
protected void grdCampaignFields_UpdateRecord(object source, DataGridCommandEventArgs e) { try { // Update the database here if (Session["Campaign"] != null) { // we have an existing campaign currentCampaign = (Campaign)Session["Campaign"]; } string sqlStmt = ""; string strOriginalFieldName = ""; string strOriginalLength = ""; dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = string.Format("SELECT FieldName, FieldTypeID, Value FROM CampaignFields WHERE FieldID = {0}", ((TextBox)e.Item.Cells[e.Item.Cells.Count - 1].Controls[0]).Text); DataView dv1 = (DataView)dsMainGrid.Select(DataSourceSelectArguments.Empty); DataRow dr = dv1.Table.Rows[0]; strOriginalFieldName = dr["FieldName"].ToString(); strOriginalLength = dr["Value"].ToString(); StringBuilder sbSqlStmt = new StringBuilder(); sbSqlStmt.AppendFormat("UPDATE CampaignFields SET "); // *** CHeck how nulls will work ... alert? EMpty string? // Formatting as sql string types for now ... handle data types? if (((TextBox)e.Item.Cells[2].Controls[0]).Text.Length > 0) { sbSqlStmt.AppendFormat("FieldName = '{0}', ", ((TextBox)e.Item.Cells[2].Controls[0]).Text); } else { PageMessage = "Field Name cannot be blank. Please enter a name."; return; } sbSqlStmt.AppendFormat("FieldTypeID = {0}, ", ((DropDownList)e.Item.Cells[3].Controls[1]).SelectedValue); if (((CheckBox)e.Item.Cells[5].Controls[1]).Checked) { sbSqlStmt.AppendFormat("ReadOnly = 1"); } else { sbSqlStmt.AppendFormat("ReadOnly = 0"); } // Update the field name if it has changed if (strOriginalFieldName != ((TextBox)e.Item.Cells[2].Controls[0]).Text) { StringBuilder sbSqlStmt2 = new StringBuilder(); sbSqlStmt2.AppendFormat("EXEC sp_rename 'Campaign.{0}', '{1}', 'COLUMN'", strOriginalFieldName, ((TextBox)e.Item.Cells[2].Controls[0]).Text); sqlStmt = sbSqlStmt2.ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "Change columns Statement to Execute: '{0}'", sqlStmt); dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); } // Update the field name if it has changed if (strOriginalLength != ((TextBox)e.Item.Cells[4].Controls[0]).Text) { int numeric; bool isNumeric = int.TryParse(((TextBox)e.Item.Cells[4].Controls[0]).Text, out numeric); if (isNumeric) { StringBuilder sbSqlStmt2 = new StringBuilder(); sbSqlStmt2.AppendFormat("ALTER TABLE Campaign ALTER COLUMN [{0}] varchar({1})", ((TextBox)e.Item.Cells[2].Controls[0]).Text, ((TextBox)e.Item.Cells[4].Controls[0]).Text); sqlStmt = sbSqlStmt2.ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "Change columns Statement to Execute: '{0}'", sqlStmt); dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = sqlStmt; dsMainGrid.Select(DataSourceSelectArguments.Empty); if (((TextBox)e.Item.Cells[4].Controls[0]).Text.Length > 0) { sbSqlStmt.AppendFormat(", Value = '{0}' ", ((TextBox)e.Item.Cells[4].Controls[0]).Text); } else { sbSqlStmt.AppendFormat(", Value = NULL "); } } } sbSqlStmt.AppendFormat(" WHERE FieldID = {0}", ((TextBox)e.Item.Cells[e.Item.Cells.Count - 1].Controls[0]).Text); string sqlStmtFinal = sbSqlStmt.ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "Update Statement to Execute: '{0}'", sqlStmtFinal); dsMainGrid.ConnectionString = currentCampaign.CampaignDBConnString; dsMainGrid.SelectCommand = sqlStmtFinal; dsMainGrid.Select(DataSourceSelectArguments.Empty); string sortQueryAppend = ""; if (Session["SortExp"] != null) { if (Session["SortExp"].ToString().Length > 0) { string sortDirection = (string)Session["SortDir"]; sortQueryAppend = string.Format(" ORDER BY {0} {1}", Session["SortExp"].ToString(), sortDirection); } } grdCampaignFields.EditItemIndex = -1; grdCampaignFields.Columns[1].Visible = true; BindDataGrid(sortQueryAppend); } catch (Exception ex) { PageMessage = "Exception updating record: " + ex.Message; } }
/// <summary> /// Saves result code for call, /// update agent Stat, /// and update status to Ready for waiting for call agent, /// update call campaign fields /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lbtnSave_Click(object sender, EventArgs e) { try { string exportFilePath = ""; string exportFileName = txtFileName.Text; if (txtFileName.Text.Length < 1) { Response.Write("<script>alert('You must specify a valid file name.');</script>"); return; } try { exportFilePath = Path.Combine(Server.MapPath("~/campaign/DataExports/"), exportFileName); } catch { Response.Write("<script>alert('Error creating a file path on the server. Your filename may have invalid characters or saving on the server may not be permitted.');</script>"); return; } Campaign currentCampaign = new Campaign(); if (Session["Campaign"] != null) { // we have an existing campaign currentCampaign = (Campaign)Session["Campaign"]; } else { Response.Write("<script>alert('There is no campaign selected to export from. Please go back to Data Manager and select one.');</script>"); return; } if (Session["SelectStmt"] == null || Session["SelectStmt"].ToString().Length < 2) { Response.Write("<script>alert('There is no query selected to export from. Please go back to Data Manager and select one.');</script>"); return; } //Response.Write("<script>alert('Please wait for the Save As dialog to appear. \n The system is working on your export.\n Depending on your export size, this may take a few minutes. \n Only close the window after you have been prompted to save.');</script>"); string selectStatement = Session["SelectStmt"].ToString(); // Load up the query dsExportData.ConnectionString = currentCampaign.CampaignDBConnString; dsExportData.SelectCommand = selectStatement; DataView dv = new DataView(); dv = (DataView)dsExportData.Select(DataSourceSelectArguments.Empty); // add csv extension unless another extension exists if (exportFilePath.LastIndexOf('.') < (exportFilePath.Length - 4)) { exportFilePath = exportFilePath + ".csv"; exportFileName = exportFileName + ".csv"; } // Make the file FileInfo file = new FileInfo(exportFilePath); file.Directory.Create(); //Response.Write("<script>displayLoading();</script>"); // Open the file stream object to start writing StreamWriter sw = new StreamWriter(exportFilePath, false); DataRowView drv = dv[0]; // Write out column names int iColCount = dv.Table.Columns.Count; string fieldContents = ""; for (int i = 0; i < iColCount; i++) { fieldContents = dv.Table.Columns[i].ToString(); // Remove commas fieldContents = fieldContents.Replace(",", " "); sw.Write(fieldContents); if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); ActivityLogger.WriteAdminEntry(currentCampaign, "Exporting {0} record to file '{1}'", dv.Table.Rows.Count, exportFilePath); // Now write all the rows. foreach (DataRow dr in dv.Table.Rows) { for (int i = 0; i < iColCount; i++) { if (!Convert.IsDBNull(dr[i])) { string fieldname = dv.Table.Columns[i].ToString(); fieldContents = dr[i].ToString(); if (Session["EncryptedFields"] != null) { string encryptedfields = Session["EncryptedFields"].ToString(); string[] fieldListArray = encryptedfields.Split(','); string passPhrase = "whatevesfasdfasdfr23"; // can be any string string initVector = "Qt@&^SDF15F6g7H8"; // must be 16 bytes // Before encrypting data, we will append plain text to a random // salt value, which will be between 4 and 8 bytes long (implicitly // used defaults). RijndaelEnhanced rijndaelKey = new RijndaelEnhanced(passPhrase, initVector); foreach (string strField in fieldListArray) { if (fieldname.Trim() == strField.Trim()) { int index = dr.Table.Columns[strField.Trim()].Ordinal; string currentvalue = dr[index].ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "ExportDMData - Column and current text: '{0}'", strField + " " + currentvalue); if (currentvalue != " " && currentvalue != "") { fieldContents = rijndaelKey.Decrypt(currentvalue); break; } } } } // Remove commas fieldContents = fieldContents.Replace(",", " "); sw.Write(fieldContents); } if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); } sw.Close(); if (rdoDelete.Checked) { try { dsExportData.ConnectionString = currentCampaign.CampaignDBConnString; string uniqueKeySelectStmt = string.Format("SELECT UniqueKey FROM Campaign {0}", selectStatement.Substring(selectStatement.IndexOf("WHERE"), (selectStatement.Length - selectStatement.IndexOf("WHERE")))); dsExportData.SelectCommand = uniqueKeySelectStmt; DataView dv1 = new DataView(); dv1 = (DataView)dsExportData.Select(DataSourceSelectArguments.Empty); // Execute WS method to delete everything in the DB List <long> keyList = new List <long>(); foreach (DataRow dr in dv1.Table.Rows) { keyList.Add(Convert.ToInt64(dr[0])); } ActivityLogger.WriteAdminEntry(currentCampaign, "Key List complete, contains {0} keys.", keyList.Count); string deleteStatement = string.Format("DELETE {0}", selectStatement.Substring(selectStatement.IndexOf("FROM"), (selectStatement.Length - selectStatement.IndexOf("FROM")))); dsExportData.SelectCommand = deleteStatement; dv = (DataView)dsExportData.Select(DataSourceSelectArguments.Empty); ActivityLogger.WriteAdminEntry(currentCampaign, "Bulk delete complete."); long totalKeys = keyList.Count; if (keyList.Count > 0) { int chunkSize = 1000; try { chunkSize = Convert.ToInt32(ConfigurationManager.AppSettings["ChunkSize"]); } catch { } CampaignService campService = new CampaignService(); XmlDocument xDocKeysToDelete = new XmlDocument(); campService.Timeout = System.Threading.Timeout.Infinite; while (keyList.Count > 0) { if (keyList.Count < chunkSize) { xDocKeysToDelete.LoadXml(Serialize.SerializeObject(keyList, typeof(List <long>))); campService.DeleteExportedLeads(xDocKeysToDelete, currentCampaign.CampaignDBConnString); keyList.Clear(); } else { List <long> templist = keyList.GetRange(0, chunkSize); keyList.RemoveRange(0, chunkSize); xDocKeysToDelete.LoadXml(Serialize.SerializeObject(templist, typeof(List <long>))); campService.DeleteExportedLeads(xDocKeysToDelete, currentCampaign.CampaignDBConnString); templist.Clear(); } } } hdnDeleteConfirmed.Value = "False"; Session["ViewChanged"] = "yes"; } catch (Exception ex) { ActivityLogger.WriteException(ex, "Admin"); } } // Download file here Response.ContentType = "application/ms-excel"; Response.AddHeader("content-disposition", "attachment; filename=" + exportFileName); Response.TransmitFile(exportFilePath); Response.End(); //file.Delete(); } catch (Exception ex) { PageMessage = "Exception saving view: " + ex.Message; } }