Advertisement
lovebyte

ChimporterCMD

Nov 5th, 2012
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.59 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data.SqlClient;
  6. using MailChimp;
  7. using System.Web;
  8. using PerceptiveMCAPI;
  9. using PerceptiveMCAPI.Methods;
  10. using PerceptiveMCAPI.Types;
  11. using PerceptiveMCAPI.Types.Internal;
  12. using System.Threading;
  13. using Newtonsoft.Json.Linq;
  14. using System.Runtime.InteropServices;
  15. using System.IO;
  16.  
  17. namespace ChimporterCMD
  18. {
  19.     class Program
  20.     {
  21.         static void Main(string[] args)
  22.         {
  23.             string path = System.IO.Directory.GetCurrentDirectory();
  24.             //Load ini file
  25.             IniFile ini = new IniFile(path + @"\settings\config.ini");
  26.  
  27.             // create a writer and open the file
  28.             StreamWriter log = new StreamWriter(path + @"\logs\log.text", true);
  29.             StreamWriter errorlog = new StreamWriter(path + @"\logs\error-log.text", true);
  30.             StreamReader SQL = new StreamReader(path + @"\settings\emailSQL.text", true);
  31.  
  32.             string Server = ini.IniReadValue("Database", "server");
  33.             string Database = ini.IniReadValue("Database", "dbname");
  34.             string Username = ini.IniReadValue("Database", "dbusername");
  35.             string Password = ini.IniReadValue("Database", "dbpassword");
  36.             bool Trusted = false;
  37.             //string accept = "n";
  38.             List<string> emails = new List<string>();
  39.             //var batch = new List<MailChimp.Types.List.Merges>();
  40.             var options = new MailChimp.Types.List.SubscribeOptions { DoubleOptIn = false, EmailType = MailChimp.Types.List.EmailType.Html, UpdateExisting = true, ReplaceInterests = true };
  41.  
  42.             string key = ini.IniReadValue("MailChimp", "apikey");
  43.             string ListID = ini.IniReadValue("MailChimp", "listid");
  44.  
  45.             log.WriteLine(DateTime.Now + " Application started");
  46.             log.Flush();
  47.             //log.Close();
  48.  
  49.             // input parameters
  50.             listMembersInput Startinput = new listMembersInput();
  51.             Startinput.api_AccessType = EnumValues.AccessType.Serial;       // access
  52.             Startinput.api_OutputType = EnumValues.OutputType.JSON;       // output
  53.             Startinput.api_MethodType = EnumValues.MethodType.POST;        // method
  54.             Startinput.api_EncodeRequest = false;  // encode
  55.             Startinput.api_Validate = false;     // validate
  56.             Startinput.parms.limit = 15000;
  57.             //Key and List info
  58.             Startinput.parms.apikey = key;
  59.             Startinput.parms.id = ListID;
  60.  
  61.             // -------------------------
  62.             // Histinput.parms.batch = Histbatch;
  63.             //--------------------------------------------------------------
  64.             // execution
  65.             listMembers Startcmd = new listMembers(Startinput);
  66.             listMembersOutput Startout = Startcmd.Execute();
  67.             int startCount = Startout.result.Count;
  68.  
  69.  
  70.  
  71.             /*
  72.              * Title
  73.              */
  74.             Console.WriteLine("|************************|");
  75.             Console.WriteLine("|**** ChimporterCMD *****|");
  76.             Console.WriteLine("|************************|");
  77.             Console.WriteLine("\r\n");
  78.            
  79.             Console.WriteLine("Testing connection...");
  80.  
  81.             string ConnectionString = "user id=" + Username +
  82.                            ";password=" + Password + ";server=" + Server +
  83.                            ";Trusted_Connection=yes;" +
  84.                            "database=" + Database +
  85.                            ";connection timeout=1000";
  86.             // Try connecting to the database using form values
  87.             log.WriteLine(DateTime.Now + " Checking connection to server");
  88.             log.Flush();
  89.             SqlConnection SQLConnection = new SqlConnection("Server=" + Server + ";Database=" + Database + ";User ID=" + Username + ";Password=" + Password + ";Trusted_Connection=" + Trusted + ";");            
  90.  
  91.             try
  92.             {
  93.                
  94.                 SQLConnection.Open();
  95.                 Console.WriteLine("ServerVersion: {0}", SQLConnection.ServerVersion);
  96.                 Console.WriteLine("State: {0}", SQLConnection.State);
  97.                 log.WriteLine(DateTime.Now + " Connected to server");
  98.                 log.Flush();
  99.                 //Console.ReadLine();
  100.                 Thread.Sleep(2000);
  101.             }
  102.             catch ( SqlException ex )
  103.             {
  104.                 Console.SetCursorPosition(0, Console.CursorTop - 1);
  105.                 Console.WriteLine("Error {0} ErrorCode {1} LineNumber {2}  Number {3}",ex.Message,ex.ErrorCode,ex.LineNumber,ex.Number);
  106.                 Console.WriteLine("\r\nPress any key to exit...");
  107.                 log.WriteLine(DateTime.Now + " Error occured, Check the error log");
  108.                 log.Flush();
  109.                 errorlog.WriteLine(DateTime.Now + "  Failed to connect to server");
  110.                 errorlog.Flush();
  111.  
  112.                 //Send faialure email
  113.                 System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  114.                 message.To.Add(ini.IniReadValue("Email", "to"));
  115.                 message.Subject = "ChimporterCMD error";
  116.                 message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
  117.                 message.Body = "Could not connect to server! \r\nError " + ex.Message + " ErrorCode " + ex.ErrorCode + " LineNumber " + ex.LineNumber + "  Number " + ex.Number + "";
  118.                 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
  119.                 smtp.Send(message);
  120.                 //Console.ReadLine();
  121.             }
  122.  
  123.             /*
  124.             * The list grabbing code goes here
  125.             */
  126.             var mc = new MCApi(key, true);
  127.  
  128.             try
  129.             {
  130.                 SqlDataReader myReader = null;
  131.                 String emailSQL = SQL.ReadToEnd();
  132.                 SqlCommand myCommand = new SqlCommand(emailSQL, SQLConnection);
  133.                 log.WriteLine(DateTime.Now + " Fetching emails from database");
  134.                 log.Flush();
  135.                 myReader = myCommand.ExecuteReader();
  136.                 while (myReader.Read())
  137.                 {
  138.                     emails.Add(myReader["AlphaNumericCol"].ToString());                
  139.                 }
  140.             }
  141.             catch (Exception e)
  142.             {
  143.                 Console.WriteLine(e.ToString());
  144.                 log.WriteLine(DateTime.Now + " Error occured, Check the error log");
  145.                 log.Flush();
  146.                 errorlog.WriteLine(DateTime.Now + " Failed to fetch emails: " + e.ToString());
  147.                 errorlog.Flush();
  148.                 //Send faialure email
  149.                 System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  150.                 message.To.Add(ini.IniReadValue("Email", "to"));
  151.                 message.Subject = "ChimporterCMD error";
  152.                 message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
  153.                 message.Body = "Failed to fetch emails! \r\nError " + e.ToString();
  154.                 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
  155.                 smtp.Send(message);
  156.                 //Console.ReadLine();
  157.             }
  158.  
  159.  
  160.             // input parameters
  161.             listBatchSubscribeInput input = new listBatchSubscribeInput();
  162.             input.api_AccessType = EnumValues.AccessType.Serial;       // access
  163.             input.api_OutputType = EnumValues.OutputType.JSON;       // output
  164.             input.api_MethodType = EnumValues.MethodType.POST;        // method
  165.             input.api_EncodeRequest = false;  // encode
  166.             input.api_Validate = false;     // validate
  167.             //Key and List info
  168.             input.parms.apikey = key;
  169.             input.parms.id = ListID;
  170.             //Optional params
  171.             input.parms.double_optin = false;
  172.             input.parms.replace_interests = true;
  173.             input.parms.update_existing = true;
  174.  
  175.             // ------------------------------ address
  176.             List<Dictionary<string, object>> batch = new List<Dictionary<string, object>>();
  177.             Dictionary<string, object> entry = new Dictionary<string, object>();
  178.             //entry = new Dictionary<string, object>();
  179.             Console.WriteLine("\n");
  180.             Console.WriteLine("Compiling emails...\n");
  181.             log.WriteLine(DateTime.Now + " Compiling email list");
  182.             log.Flush();
  183.             for (int i = 0; i < emails.Count; i++) // Loop through List with for
  184.             {
  185.                 int percent = (100 * (i + 1)) / emails.Count;  
  186.                 //Console.Clear();
  187.                 entry.Add("EMAIL", emails[i]);
  188.                 entry.Add("EMAIL_TYPE", "html");
  189.                 batch.Add(entry);
  190.                 entry = new Dictionary<string, object>();
  191.                 Console.Write("\rAdding email:  " + emails[i]);
  192.                 Console.Write("\rComplete: {0}%   ", percent);
  193.                 Thread.Sleep(5);
  194.             }
  195.             Thread.Sleep(100);          
  196.             // -------------------------
  197.             input.parms.batch = batch;
  198.             //--------------------------------------------------------------
  199.             // execution
  200.             Console.WriteLine("\r\n\nUploading...");
  201.             log.WriteLine(DateTime.Now + " Uploading to MailChimp");
  202.             log.Flush();
  203.             listBatchSubscribe cmd = new listBatchSubscribe(input);
  204.             listBatchSubscribeOutput output = cmd.Execute();
  205.             // Format output
  206.             string response = output.api_Response.ToString();
  207.             JObject o = JObject.Parse(response);
  208.             //Try get a response from the server
  209.             try {
  210.             int errCount = (int)o["error_count"];
  211.                 if (errCount > 0)
  212.                 {
  213.                     int errCode = (int)o["errors"][0]["code"];
  214.                     string errMsg = (string)o["errors"][0]["message"];
  215.                     log.WriteLine(DateTime.Now + " Error occured, Check the error log");
  216.                     log.Flush();
  217.                     errorlog.WriteLine(DateTime.Now + "Some emails failed to upload: " + errMsg);
  218.                     errorlog.Flush();
  219.                     Console.WriteLine("\nSome emails failed to upload!");
  220.                     Console.WriteLine("\rCheck the error-log.text!");
  221.  
  222.                     //Send faialure email
  223.                     System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  224.                     message.To.Add(ini.IniReadValue("Email", "to"));
  225.                     message.Subject = "ChimporterCMD error";
  226.                     message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
  227.                     message.Body = "Some emails failed to upload! \r\nError " + errMsg;
  228.                     System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
  229.                     smtp.Send(message);
  230.                 }
  231.                 else
  232.                 {
  233.                     log.WriteLine(DateTime.Now + " Succesfully uplaoded emails to MailChimp");
  234.                     log.Flush();
  235.                     Thread.Sleep(100);
  236.                     Console.WriteLine("\r\n\nEmails Added!");
  237.                     //Send faialure email
  238.                     System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  239.                     message.To.Add(ini.IniReadValue("Email", "to"));
  240.                     message.Subject = "ChimporterCMD Success";
  241.                     message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
  242.                     message.Body = "Succesfully uplaoded emails to MailChimp! \r\nDate added: " + DateTime.Now;
  243.                     System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
  244.                     smtp.Send(message);
  245.                 }      
  246.             } catch(Exception ec) {                
  247.                 Console.WriteLine("\nFailed to connect to MailChimp!");
  248.                 Console.WriteLine("\rCheck that your API Key or List ID are correct");
  249.                 //Send faialure email
  250.                 System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  251.                 message.To.Add(ini.IniReadValue("Email", "to"));
  252.                 message.Subject = "ChimporterCMD error";
  253.                 message.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
  254.                 message.Body = "Failed to connect to MailChimp! \r\nCheck that your API Key or List ID are correct!  Error: " + ec.ToString();
  255.                 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
  256.                 smtp.Send(message);
  257.             }
  258.            
  259.             //Console.ReadLine();
  260.             log.WriteLine(DateTime.Now + " Application closed");
  261.             log.Flush();
  262.             // close the stream
  263.            
  264.             log.Close();
  265.            
  266.             errorlog.Close();
  267.  
  268.             /* List history
  269.             // input parameters
  270.             listGrowthHistoryInput Histinput = new listGrowthHistoryInput();
  271.             Histinput.api_AccessType = EnumValues.AccessType.Serial;       // access
  272.             Histinput.api_OutputType = EnumValues.OutputType.JSON;       // output
  273.             Histinput.api_MethodType = EnumValues.MethodType.POST;        // method
  274.             Histinput.api_EncodeRequest = false;  // encode
  275.             Histinput.api_Validate = false;     // validate
  276.             //Key and List info
  277.             Histinput.parms.apikey = key;
  278.             Histinput.parms.id = ListID;
  279.  
  280.             // -------------------------
  281.            // Histinput.parms.batch = Histbatch;
  282.             //--------------------------------------------------------------
  283.             // execution
  284.             Console.WriteLine("\r\nList Growth History:\r");
  285.             listGrowthHistory Histcmd = new listGrowthHistory(Histinput);
  286.             listGrowthHistoryOutput Histout = Histcmd.Execute();
  287.             // Format output
  288.             string Histresponse = Histout.api_Response.ToString();
  289.             JArray histo = JArray.Parse(Histresponse);
  290.             //Get a response            
  291.             string histMonth = (string)histo.Last["month"];
  292.             string histImports = (string)histo.Last["imports"];
  293.             string histOptins = (string)histo.Last["optins"];
  294.             Console.WriteLine("Month: " + histMonth);
  295.             Console.WriteLine("Imports : " + histImports);
  296.             Console.WriteLine("Optins : " + histOptins);*/
  297.  
  298.             // input parameters
  299.             listMembersInput Membersinput = new listMembersInput();
  300.             Membersinput.api_AccessType = EnumValues.AccessType.Serial;       // access
  301.             Membersinput.api_OutputType = EnumValues.OutputType.JSON;       // output
  302.             Membersinput.api_MethodType = EnumValues.MethodType.POST;        // method
  303.             Membersinput.api_EncodeRequest = false;  // encode
  304.             Membersinput.api_Validate = false;     // validate
  305.             Membersinput.parms.limit = 15000;
  306.             //Key and List info
  307.             Membersinput.parms.apikey = key;
  308.             Membersinput.parms.id = ListID;
  309.  
  310.             // -------------------------
  311.             // Histinput.parms.batch = Histbatch;
  312.             //--------------------------------------------------------------
  313.             // execution
  314.             listMembers Memberscmd = new listMembers(Membersinput);
  315.             listMembersOutput Membersout = Memberscmd.Execute();
  316.  
  317.             int totalAdded = Membersout.result.Count - startCount;
  318.  
  319.             Console.WriteLine("\r\nList Before: {0}\r", startCount);
  320.             Console.WriteLine("\rList After: {0}\r", Membersout.result.Count);
  321.             Console.WriteLine("\rTotal Added: {0}\r", totalAdded);
  322.  
  323.  
  324.             System.Net.Mail.MailMessage closeEmail = new System.Net.Mail.MailMessage();
  325.             closeEmail.To.Add(ini.IniReadValue("Email", "to"));
  326.             closeEmail.Subject = "ChimporterCMD Success";
  327.             closeEmail.From = new System.Net.Mail.MailAddress(ini.IniReadValue("Email", "from"));
  328.             closeEmail.Body = "Program completed successfully!\r List Before: " + startCount + "\r List After: " + Membersout.result.Count + "\r Total Added: " + totalAdded.ToString();
  329.             System.Net.Mail.SmtpClient CloseSmtp = new System.Net.Mail.SmtpClient(ini.IniReadValue("Email", "smtphost"));
  330.             CloseSmtp.Send(closeEmail);
  331.             //Console.ReadLine();
  332.         }
  333.     }
  334. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement