Click here to Skip to main content
15,743,541 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello Im recieving an "}" expected error, im trying to end my main method after the public class starter. Why am i receiving this error?



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;

namespace MainPDF
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main()
        {







        public class starter
        {
            private System.Timers.Timer withEventsField_tmrCheckMailOdd = new System.Timers.Timer();
            public System.Timers.Timer tmrCheckMailOdd
            {
                get { return withEventsField_tmrCheckMailOdd; }
                set
                {
                    if (withEventsField_tmrCheckMailOdd != null)
                    {
                        withEventsField_tmrCheckMailOdd.Elapsed -= tmrCheckMailOdd_Elapsed;
                    }
                    withEventsField_tmrCheckMailOdd = value;
                    if (withEventsField_tmrCheckMailOdd != null)
                    {
                        withEventsField_tmrCheckMailOdd.Elapsed += tmrCheckMailOdd_Elapsed;
                    }
                }
            }
            private System.Timers.Timer withEventsField_tmrCheckMailEven = new System.Timers.Timer();
            public System.Timers.Timer tmrCheckMailEven
            {
                get { return withEventsField_tmrCheckMailEven; }
                set
                {
                    if (withEventsField_tmrCheckMailEven != null)
                    {
                        withEventsField_tmrCheckMailEven.Elapsed -= tmrCheckMailEven_Elapsed;
                    }
                    withEventsField_tmrCheckMailEven = value;
                    if (withEventsField_tmrCheckMailEven != null)
                    {
                        withEventsField_tmrCheckMailEven.Elapsed += tmrCheckMailEven_Elapsed;
                    }
                }

            }
            //'Dim WithEvents tmrAPN As New System.Timers.Timer()
            //'Dim WithEvents tmrAPNAndroid As New System.Timers.Timer()
            //'Dim WithEvents scMail As SqlConnection

            Dictionary<string, string> EmailMerchants = new Dictionary<string, string>();
            int EmailMerchantRefreshMaxIndex = 120;

            int EmailMerchantRefreshIndex = 0;
            SqlDataAdapter daAdapter = new SqlDataAdapter();
            /// <summary>
            /// Global value to hold the start date and time of the service
            /// </summary>
            /// <remarks></remarks>

            System.DateTime gServiceStartDate;
            /// <summary>
            /// Works in conjunction with the app setting 'ReportStatusIntervalInSeconds' to determine when to log a status message
            /// </summary>
            /// <remarks></remarks>

            System.DateTime gLastStatusReportDate;
            /// <summary>
            /// Holds the root path to images of receipts in the system
            /// </summary>
            /// <remarks></remarks>

            string strRootUploadedImagePath = "";

            /// <summary>
            /// Works in conjunction with the app setting 'ReportStatusIntervalInSeconds' to determine when to log a status message
            /// </summary>
            /// <remarks></remarks>

            System.DateTime gLastUserNotifcationDate = DateTime.Now.AddDays(-1);

            int intThumbnailHeight = 200;

            int intThumbnailWidth = 200;
            //'Dim scmd As New SqlCommand("", scMail)

            string MailHost = "";
            string ReplyEmail = "";
            string SMTPUserName = "";
            string SMTPPassword = "";
            int SMTPPort = 25;

            bool bUseSSL = false;
            private string GetMachineName()
            {
                return System.Environment.MachineName;
            }

            protected void OnStart(string[] args)
            {
                try
                {

                    //if (My.Settings.Debug_Flag == true)
                    //{
                    //Add Wait to allow time to get attached to process before ONStart executes
                    System.Threading.Thread.Sleep(20000);
                    // }

                    //Store the start date of the service
                    gServiceStartDate = DateTime.Now;

                    //Set the last report date to now...
                    gLastStatusReportDate = DateTime.Now;


                    using (SqlConnection scMail = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myDigiStuff"].ConnectionString))


                        for (int x = 1; x <= 5; x++)
                        {

                            try
                            {
                                Console.Write("Attempting to open database connection to " + scMail.Database, TraceEventType.Information);
                                if (scMail.State != ConnectionState.Open)
                                {
                                    scMail.Open();
                                    Console.Write("Connection established to [" + scMail.Database + "]", TraceEventType.Information);
                                }

                                break; // TODO: might not be correct. Was : Exit For

                            }
                            catch (Exception ex)
                            {
                                if (x < 5)
                                {
                                    Console.Write("Failed connecting to [" + scMail.Database + "] on attempt [" + x + "]. Will retry in 5 seconds..." + System.Environment.NewLine + ex.Message, TraceEventType.Warning);
                                    System.Threading.Thread.Sleep(5000);
                                    //Wait for 5 seconds hoping the connection will become available
                                }
                                else
                                {
                                    //TODO: Send Email! There is an issue connecting to the database
                                    Console.Write("Failed connecting to [" + scMail.Database + "] on final attempt. Service is shutting down..." + System.Environment.NewLine + ex.Message, TraceEventType.Error);

                                    return;
                                }
                            }
                        }




                    Console.Write("Getting global variables for configuration", TraceEventType.Information);

                    DataTable dtGlobalSettings = GetGlobalVariables("AdminEmails, EmailPollTimerIntervalInSeconds, MailHosts, ReplyEmail, SMTPUserName, SMTPPassword, SMTPPort, SMTPUseSSL,dbo.NextIntervalTimertoAPN(getdate()) APNTimerIntervalInSeconds ");
                    tmrCheckMailOdd.Interval = (double)dtGlobalSettings.Rows[0]["EmailPollTimerIntervalInSeconds"] * 1000;
                    //Interval is in milliseconds
                    tmrCheckMailEven.Interval = (double)dtGlobalSettings.Rows[0]["EmailPollTimerIntervalInSeconds"] * 1000;
                    //Interval is in milliseconds

                    //tmrAPN.Interval = dtGlobalSettings.Rows(0)("APNTimerIntervalInSeconds") * 1000
                    //tmrAPN.Enabled = True
                    //tmrAPN.Start()
                    //My.Application.Log.WriteEntry("APN timer set to poll every [" & dtGlobalSettings.Rows(0)("APNTimerIntervalInSeconds") & "] seconds based on GlobalConfig setting", TraceEventType.Information)


                    //tmrAPNAndroid.Interval = dtGlobalSettings.Rows(0)("APNTimerIntervalInSeconds") * 1000
                    //tmrAPNAndroid.Enabled = True
                    //tmrAPNAndroid.Start()
                    //My.Application.Log.WriteEntry("Android APN timer set to poll every [" & dtGlobalSettings.Rows(0)("APNTimerIntervalInSeconds") & "] seconds based on GlobalConfig setting", TraceEventType.Information)


                    MailHost = dtGlobalSettings.Rows[0]["MailHosts"].ToString(); //-------------------???????????????----------------
                    ReplyEmail = dtGlobalSettings.Rows[0]["ReplyEmail"].ToString();
                    SMTPUserName = dtGlobalSettings.Rows[0]["SMTPUserName"].ToString();
                    SMTPPassword = dtGlobalSettings.Rows[0]["SMTPPassword"].ToString();
                    SMTPPort = (int)dtGlobalSettings.Rows[0]["SMTPPort"];
                    bUseSSL = (bool)dtGlobalSettings.Rows[0]["SMTPUseSSL"];


                    Console.Write("Email polling timer set to poll every [" + dtGlobalSettings.Rows[0]["EmailPollTimerIntervalInSeconds"] + "] seconds based on GlobalConfig setting", TraceEventType.Information);

                    tmrCheckMailOdd.Enabled = true;
                    tmrCheckMailOdd.Start();
                    tmrCheckMailEven.Enabled = true;
                    tmrCheckMailEven.Start();
                    Console.Write("Application" + " started successfully!", TraceEventType.Information);

                    // EmailMerchants = GetEmailMerchantDomains();
                    Console.Write("Email merchants loaded [" + EmailMerchants.Count().ToString() + "].", TraceEventType.Information);

                    string strUserEmails = dtGlobalSettings.Rows[0]["AdminEmails"].ToString();
                    CSUtilities objCSUtilities = new CSUtilities();
                    //objCSUtilities.SendEmail(dtGlobalSettings.Rows[0], strUserEmails, GetMachineName() + " : Starting Email Monitor", "");

                }
                catch (Exception ex)
                {
                    //Default Catch all. If anything happens that is not handled... 
                    Console.Write(ex.ToString(), TraceEventType.Error, "There was an error trying to start the service. " + GetErrorInfo(ex));
                }
            }

            protected void OnStop()
            {
                DataTable dtGlobalSettings = null;
                dtGlobalSettings = GetGlobalVariables("AdminEmails,EmailPollTimerIntervalInSeconds, MailHosts, ReplyEmail, SMTPUserName, SMTPPassword, SMTPPort, SMTPUseSSL,APNTimerIntervalInSeconds");
                string strUserEmails = dtGlobalSettings.Rows[0]["AdminEmails"].ToString();

                Console.Write("Application" + " stopping.", TraceEventType.Information);

                Console.Write("Stopping Timer.", TraceEventType.Information);

                try
                {
                    tmrCheckMailOdd.Stop();
                    tmrCheckMailOdd.Enabled = false;
                    Console.Write("Odd Timer Stopped.", TraceEventType.Information);

                    tmrCheckMailEven.Stop();
                    tmrCheckMailEven.Enabled = false;
                    Console.Write("Even Timer Stopped.", TraceEventType.Information);

                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString(), TraceEventType.Warning, "Timer could not be stopped gracefully. " + GetErrorInfo(ex));
                }

                //If scMail.State <> ConnectionState.Closed Then
                //    Try
                //        'Before we close the connection, we need to get the users to be notified by email...
                //        scMail.Close()
                //        My.Application.Log.WriteEntry("Closed " & scMail.Database & " connection.", TraceEventType.Information)
                //    Catch ex As Exception
                //        My.Application.Log.WriteEntry("Error closing " & scMail.Database & " connection.", TraceEventType.Warning)
                //    Finally
                //        scMail.Dispose()
                //    End Try
                //End If

                //string strServiceStoppedMessage = GetGlobalVariables("AdminEmails").Rows[0]("AdminEmails").ToString();

                // Console.Write(strServiceStoppedMessage, TraceEventType.Information);

                //CSUtilities objCSUtilities = new CSUtilities();
                //objCSUtilities.SendEmail(dtGlobalSettings.Rows[0], strUserEmails, GetMachineName() + " : Stopping Email Monitor", "");

                // Console.Write("Application" + " Stopped.", TraceEventType.Information);
            }


            public void tmrCheckMailOdd_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                try
                {
                    //Stop the timer while we process..
                    tmrCheckMailOdd.Stop();


                    DataTable dtGlobalSettings = GetGlobalVariables("EmailPollTimerIntervalInSeconds, MailHosts, ReplyEmail, SMTPUserName, SMTPPassword, SMTPPort, SMTPUseSSL");
                    tmrCheckMailOdd.Interval = (double)dtGlobalSettings.Rows[0]["EmailPollTimerIntervalInSeconds"] * 1000;
                    //Interval is in milliseconds

                    using (SqlConnection scMail = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myDigiStuff"].ConnectionString))
                    {
                        scMail.Open();
                        CSUtilities objCSUtilities = new CSUtilities();

                        RefreshEmailMerchants();

                        objCSUtilities.CheckEmail(scMail, dtGlobalSettings.Rows[0], true, ("WinnovativePrototype"), EmailMerchants);

                        if (scMail.State != ConnectionState.Closed)
                        {
                            scMail.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString(), TraceEventType.Error, "Error Processing Emails: " + GetErrorInfo(ex));
                }
                finally
                {
                    //Restart the timer
                    tmrCheckMailOdd.Start();
                }
            }
            public void tmrCheckMailEven_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                try
                {
                    //Stop the timer while we process..
                    tmrCheckMailEven.Stop();

                    DataTable dtGlobalSettings = GetGlobalVariables("EmailPollTimerIntervalInSeconds, MailHosts, ReplyEmail, SMTPUserName, SMTPPassword, SMTPPort, SMTPUseSSL");
                    tmrCheckMailEven.Interval = (double)dtGlobalSettings.Rows[0]["EmailPollTimerIntervalInSeconds"] * 1000;
                    //Interval is in milliseconds

                    using (SqlConnection scMail = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myDigiStuff"].ConnectionString))
                    {
                        scMail.Open();
                        CSUtilities objCSUtilities = new CSUtilities();

                        RefreshEmailMerchants();
                        string folderz = "WinnovativeTesting";

                        objCSUtilities.CheckEmail(scMail, dtGlobalSettings.Rows[0], false, ("WinnovativePrototype"), EmailMerchants);
                        if (scMail.State != ConnectionState.Closed)
                        {
                            scMail.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString(), TraceEventType.Error, "Error Processing Emails: " + GetErrorInfo(ex));
                }
                finally
                {
                    //Restart the timer
                    tmrCheckMailEven.Start();
                }
            }


            /// <summary>
            /// This function will return a formatted string of information we would like to see in the event log. Since the eventlog message is limited to 32766 bytes, we make sure this function never returns more than 30000 characters
            /// </summary>
            /// <param name="ex">Exception containing info we would like to parse</param>
            /// <returns></returns>
            /// <remarks></remarks>
            private string GetErrorInfo(Exception ex)
            {

                string strReturn = "";
                try
                {
                    strReturn += System.Environment.NewLine + "Error: [" + ex.Message + "]";
                    if ((ex.StackTrace != null))
                    {
                        strReturn += System.Environment.NewLine + "Stack Trace:" + System.Environment.NewLine + ex.StackTrace + "]";
                    }

                    foreach (string objItem in ex.Data.Keys)
                    {
                        strReturn += System.Environment.NewLine + objItem + ": [" + ex.Data[objItem].ToString() + "]";
                    }

                    //if (Strings.Len(strReturn) >= 30000)
                    if (strReturn.Length >= 30000)
                    {
                        strReturn = "The additional info needed to be truncated!" + System.Environment.NewLine + System.Environment.NewLine + strReturn.Substring(0, 30000);
                    }

                }
                catch (Exception ex2)
                {
                    Console.Write(ex2.ToString(), TraceEventType.Error, "There was an unhandled exception when building the ErrorInfo string. GetErrorInfo(); " + System.Environment.NewLine + ex2.Message);
                }

                return strReturn;
            }

            /// <summary>
            /// Function will return a datatable of the selected variables from the global config table
            /// Pass variables in as comma delimited list
            /// </summary>
            /// <param name="strVariableList"></param>
            /// <returns></returns>
            /// <remarks></remarks>
            public DataTable GetGlobalVariables(string strVariableList)
            {
                DataTable functionReturnValue = default(DataTable);
                try
                {
                    using (SqlConnection scMail = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myDigiStuff"].ConnectionString))
                    {
                        scMail.Open();
                        string strSQL = "";
                        SqlDataAdapter sda = new SqlDataAdapter(strSQL, scMail);
                        DataTable dtReturnValues = new DataTable();
                        strSQL = "SELECT " + strVariableList + " FROM GlobalConfig";
                        sda.SelectCommand.CommandText = strSQL;

                        sda.Fill(dtReturnValues);
                        functionReturnValue = dtReturnValues;
                    }

                }
                catch (Exception ex)
                {
                    functionReturnValue = null;
                    throw ex;

                }
                finally
                {
                }
                return functionReturnValue;
            }
            private void RefreshEmailMerchants()
            {
                EmailMerchantRefreshIndex = EmailMerchantRefreshIndex + 1;
                if (EmailMerchantRefreshIndex > EmailMerchantRefreshMaxIndex)
                {
                    EmailMerchants = GetEmailMerchantDomains();
                    EmailMerchantRefreshIndex = 0;
                }
            }
            private Dictionary<string, string> GetEmailMerchantDomains()
            {
                Dictionary<string, string> retVal = new Dictionary<string, string>();

                try
                {
                    using (SqlConnection scMail = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myDigiStuff"].ConnectionString))
                    {
                        scMail.Open();
                        string strSQL = "";
                        SqlDataAdapter sda = new SqlDataAdapter(strSQL, scMail);
                        DataTable dtReturnValues = new DataTable();
                        strSQL = "SELECT MerchantDomain, MerchantName FROM lkupReturnPathMerchantDomains WITH(NOLOCK) WHERE IsActive = 1;";
                        sda.SelectCommand.CommandText = strSQL;
                        sda.Fill(dtReturnValues);
                        dtReturnValues.AsEnumerable().ToList().ForEach(obj => { retVal.Add(obj[0].ToString(), obj[1].ToString()); });
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                return retVal;
            }

        }

    }

}

}


What I have tried:

I've check multiple time to make sure its in the correct placement.
Rebuilt project
Clean Build
Pulled hair out :) lol
Posted
Updated 19-Dec-16 5:15am
Comments
[no name] 19-Dec-16 11:11am    
OMG, without having to read through your entire codebase, you can't define functions inside your main method.
hari19113 20-Dec-16 2:11am    
Class inside Main function???

1 solution

Um, you tried to define an entire class inside your Main method in the Program class. You can't do that.

If you really think that's the "correct placement" of this code, then you know nothing at all about C# and copied this code from somewhere and have absolutely no idea how it works.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900