Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data.SqlClient;
- using MailChimp;
- using System.Web;
- using PerceptiveMCAPI;
- using PerceptiveMCAPI.Methods;
- using PerceptiveMCAPI.Types;
- using PerceptiveMCAPI.Types.Internal;
- using System.Threading;
- using Newtonsoft.Json.Linq;
- using System.Runtime.InteropServices;
- using System.IO;
- namespace ChimporterCMD
- {
- class Program
- {
- static void Main(string[] args)
- {
- string path = System.IO.Directory.GetCurrentDirectory();
- //Load ini file
- IniFile ini = new IniFile(path + @"\settings\config.ini");
- // create a writer and open the file
- StreamWriter log = new StreamWriter(path + @"\logs\log.text", true);
- StreamWriter errorlog = new StreamWriter(path + @"\logs\error-log.text", true);
- StreamReader SQL = new StreamReader(path + @"\settings\emailSQL.text", true);
- string Server = ini.IniReadValue("Database", "server");
- string Database = ini.IniReadValue("Database", "dbname");
- string Username = ini.IniReadValue("Database", "dbusername");
- string Password = ini.IniReadValue("Database", "dbpassword");
- bool Trusted = false;
- //string accept = "n";
- List<string> emails = new List<string>();
- //var batch = new List<MailChimp.Types.List.Merges>();
- var options = new MailChimp.Types.List.SubscribeOptions { DoubleOptIn = false, EmailType = MailChimp.Types.List.EmailType.Html, UpdateExisting = true, ReplaceInterests = true };
- string key = ini.IniReadValue("MailChimp", "apikey");
- string ListID = ini.IniReadValue("MailChimp", "listid");
- log.WriteLine(DateTime.Now + " Application started");
- log.Flush();
- //log.Close();
- // input parameters
- listMembersInput Startinput = new listMembersInput();
- Startinput.api_AccessType = EnumValues.AccessType.Serial; // access
- Startinput.api_OutputType = EnumValues.OutputType.JSON; // output
- Startinput.api_MethodType = EnumValues.MethodType.POST; // method
- Startinput.api_EncodeRequest = false; // encode
- Startinput.api_Validate = false; // validate
- Startinput.parms.limit = 15000;
- //Key and List info
- Startinput.parms.apikey = key;
- Startinput.parms.id = ListID;
- // -------------------------
- // Histinput.parms.batch = Histbatch;
- //--------------------------------------------------------------
- // execution
- listMembers Startcmd = new listMembers(Startinput);
- listMembersOutput Startout = Startcmd.Execute();
- int startCount = Startout.result.Count;
- /*
- * Title
- */
- Console.WriteLine("|************************|");
- Console.WriteLine("|**** ChimporterCMD *****|");
- Console.WriteLine("|************************|");
- Console.WriteLine("\r\n");
- Console.WriteLine("Testing connection...");
- string ConnectionString = "user id=" + Username +
- ";password=" + Password + ";server=" + Server +
- ";Trusted_Connection=yes;" +
- "database=" + Database +
- ";connection timeout=1000";
- // Try connecting to the database using form values
- log.WriteLine(DateTime.Now + " Checking connection to server");
- log.Flush();
- SqlConnection SQLConnection = new SqlConnection("Server=" + Server + ";Database=" + Database + ";User ID=" + Username + ";Password=" + Password + ";Trusted_Connection=" + Trusted + ";");
- try
- {
- SQLConnection.Open();
- Console.WriteLine("ServerVersion: {0}", SQLConnection.ServerVersion);
- Console.WriteLine("State: {0}", SQLConnection.State);
- log.WriteLine(DateTime.Now + " Connected to server");
- log.Flush();
- //Console.ReadLine();
- Thread.Sleep(2000);
- }
- catch ( SqlException ex )
- {
- Console.SetCursorPosition(0, Console.CursorTop - 1);
- Console.WriteLine("Error {0} ErrorCode {1} LineNumber {2} Number {3}",ex.Message,ex.ErrorCode,ex.LineNumber,ex.Number);
- Console.WriteLine("\r\nPress any key to exit...");
- log.WriteLine(DateTime.Now + " Error occured, Check the error log");
- log.Flush();
- errorlog.WriteLine(DateTime.Now + " Failed to connect to server");
- errorlog.Flush();
- //Send faialure email
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- message.To.Add(ini.IniReadValue("Email", "to"));
- message.Subject = "ChimporterCMD error";
- message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
- message.Body = "Could not connect to server! \r\nError " + ex.Message + " ErrorCode " + ex.ErrorCode + " LineNumber " + ex.LineNumber + " Number " + ex.Number + "";
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
- smtp.Send(message);
- //Console.ReadLine();
- }
- /*
- * The list grabbing code goes here
- */
- var mc = new MCApi(key, true);
- try
- {
- SqlDataReader myReader = null;
- String emailSQL = SQL.ReadToEnd();
- SqlCommand myCommand = new SqlCommand(emailSQL, SQLConnection);
- log.WriteLine(DateTime.Now + " Fetching emails from database");
- log.Flush();
- myReader = myCommand.ExecuteReader();
- while (myReader.Read())
- {
- emails.Add(myReader["AlphaNumericCol"].ToString());
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- log.WriteLine(DateTime.Now + " Error occured, Check the error log");
- log.Flush();
- errorlog.WriteLine(DateTime.Now + " Failed to fetch emails: " + e.ToString());
- errorlog.Flush();
- //Send faialure email
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- message.To.Add(ini.IniReadValue("Email", "to"));
- message.Subject = "ChimporterCMD error";
- message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
- message.Body = "Failed to fetch emails! \r\nError " + e.ToString();
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
- smtp.Send(message);
- //Console.ReadLine();
- }
- // input parameters
- listBatchSubscribeInput input = new listBatchSubscribeInput();
- input.api_AccessType = EnumValues.AccessType.Serial; // access
- input.api_OutputType = EnumValues.OutputType.JSON; // output
- input.api_MethodType = EnumValues.MethodType.POST; // method
- input.api_EncodeRequest = false; // encode
- input.api_Validate = false; // validate
- //Key and List info
- input.parms.apikey = key;
- input.parms.id = ListID;
- //Optional params
- input.parms.double_optin = false;
- input.parms.replace_interests = true;
- input.parms.update_existing = true;
- // ------------------------------ address
- List<Dictionary<string, object>> batch = new List<Dictionary<string, object>>();
- Dictionary<string, object> entry = new Dictionary<string, object>();
- //entry = new Dictionary<string, object>();
- Console.WriteLine("\n");
- Console.WriteLine("Compiling emails...\n");
- log.WriteLine(DateTime.Now + " Compiling email list");
- log.Flush();
- for (int i = 0; i < emails.Count; i++) // Loop through List with for
- {
- int percent = (100 * (i + 1)) / emails.Count;
- //Console.Clear();
- entry.Add("EMAIL", emails[i]);
- entry.Add("EMAIL_TYPE", "html");
- batch.Add(entry);
- entry = new Dictionary<string, object>();
- Console.Write("\rAdding email: " + emails[i]);
- Console.Write("\rComplete: {0}% ", percent);
- Thread.Sleep(5);
- }
- Thread.Sleep(100);
- // -------------------------
- input.parms.batch = batch;
- //--------------------------------------------------------------
- // execution
- Console.WriteLine("\r\n\nUploading...");
- log.WriteLine(DateTime.Now + " Uploading to MailChimp");
- log.Flush();
- listBatchSubscribe cmd = new listBatchSubscribe(input);
- listBatchSubscribeOutput output = cmd.Execute();
- // Format output
- string response = output.api_Response.ToString();
- JObject o = JObject.Parse(response);
- //Try get a response from the server
- try {
- int errCount = (int)o["error_count"];
- if (errCount > 0)
- {
- int errCode = (int)o["errors"][0]["code"];
- string errMsg = (string)o["errors"][0]["message"];
- log.WriteLine(DateTime.Now + " Error occured, Check the error log");
- log.Flush();
- errorlog.WriteLine(DateTime.Now + "Some emails failed to upload: " + errMsg);
- errorlog.Flush();
- Console.WriteLine("\nSome emails failed to upload!");
- Console.WriteLine("\rCheck the error-log.text!");
- //Send faialure email
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- message.To.Add(ini.IniReadValue("Email", "to"));
- message.Subject = "ChimporterCMD error";
- message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
- message.Body = "Some emails failed to upload! \r\nError " + errMsg;
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
- smtp.Send(message);
- }
- else
- {
- log.WriteLine(DateTime.Now + " Succesfully uplaoded emails to MailChimp");
- log.Flush();
- Thread.Sleep(100);
- Console.WriteLine("\r\n\nEmails Added!");
- //Send faialure email
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- message.To.Add(ini.IniReadValue("Email", "to"));
- message.Subject = "ChimporterCMD Success";
- message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
- message.Body = "Succesfully uplaoded emails to MailChimp! \r\nDate added: " + DateTime.Now;
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
- smtp.Send(message);
- }
- } catch(Exception ec) {
- Console.WriteLine("\nFailed to connect to MailChimp!");
- Console.WriteLine("\rCheck that your API Key or List ID are correct");
- //Send faialure email
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- message.To.Add(ini.IniReadValue("Email", "to"));
- message.Subject = "ChimporterCMD error";
- message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
- message.Body = "Failed to connect to MailChimp! \r\nCheck that your API Key or List ID are correct! Error: " + ec.ToString();
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
- smtp.Send(message);
- }
- //Console.ReadLine();
- log.WriteLine(DateTime.Now + " Application closed");
- log.Flush();
- // close the stream
- log.Close();
- errorlog.Close();
- /* List history
- // input parameters
- listGrowthHistoryInput Histinput = new listGrowthHistoryInput();
- Histinput.api_AccessType = EnumValues.AccessType.Serial; // access
- Histinput.api_OutputType = EnumValues.OutputType.JSON; // output
- Histinput.api_MethodType = EnumValues.MethodType.POST; // method
- Histinput.api_EncodeRequest = false; // encode
- Histinput.api_Validate = false; // validate
- //Key and List info
- Histinput.parms.apikey = key;
- Histinput.parms.id = ListID;
- // -------------------------
- // Histinput.parms.batch = Histbatch;
- //--------------------------------------------------------------
- // execution
- Console.WriteLine("\r\nList Growth History:\r");
- listGrowthHistory Histcmd = new listGrowthHistory(Histinput);
- listGrowthHistoryOutput Histout = Histcmd.Execute();
- // Format output
- string Histresponse = Histout.api_Response.ToString();
- JArray histo = JArray.Parse(Histresponse);
- //Get a response
- string histMonth = (string)histo.Last["month"];
- string histImports = (string)histo.Last["imports"];
- string histOptins = (string)histo.Last["optins"];
- Console.WriteLine("Month: " + histMonth);
- Console.WriteLine("Imports : " + histImports);
- Console.WriteLine("Optins : " + histOptins);*/
- // input parameters
- listMembersInput Membersinput = new listMembersInput();
- Membersinput.api_AccessType = EnumValues.AccessType.Serial; // access
- Membersinput.api_OutputType = EnumValues.OutputType.JSON; // output
- Membersinput.api_MethodType = EnumValues.MethodType.POST; // method
- Membersinput.api_EncodeRequest = false; // encode
- Membersinput.api_Validate = false; // validate
- Membersinput.parms.limit = 15000;
- //Key and List info
- Membersinput.parms.apikey = key;
- Membersinput.parms.id = ListID;
- // -------------------------
- // Histinput.parms.batch = Histbatch;
- //--------------------------------------------------------------
- // execution
- listMembers Memberscmd = new listMembers(Membersinput);
- listMembersOutput Membersout = Memberscmd.Execute();
- int totalAdded = Membersout.result.Count - startCount;
- Console.WriteLine("\r\nList Before: {0}\r", startCount);
- Console.WriteLine("\rList After: {0}\r", Membersout.result.Count);
- Console.WriteLine("\rTotal Added: {0}\r", totalAdded);
- System.Net.Mail.MailMessage closeEmail = new System.Net.Mail.MailMessage();
- closeEmail.To.Add(ini.IniReadValue("Email", "to"));
- closeEmail.Subject = "ChimporterCMD Success";
- closeEmail.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
- closeEmail.Body = "Program completed successfully!\r List Before: " + startCount + "\r List After: " + Membersout.result.Count + "\r Total Added: " + totalAdded.ToString();
- System.Net.Mail.SmtpClient CloseSmtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
- CloseSmtp.Send(closeEmail);
- //Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement