Question

i'm created my web site in asp.net 2.0 with c# technology.and i included one kind of news letter application in my admin control part. when there will be one of my JobRunner.cs class in Add_Code directory.

actually my problem was to Start Job in news letter application. for detail i also include my file cs.code and full code of JobRunner.cs class.

  • this is my manage_jobs.aspx.cs coding for set Job Id to Start Job.

    protected void lbut_startjob_Click(object sender, EventArgs e)
    {
        int count = 0;
        SetData();
        GV_ViewJobs.AllowPaging = false;
        this.FillGrid();
        ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
        count = arr.Count;
        for (int i = 0; i < GV_ViewJobs.Rows.Count; i++)
        {
            if (arr.Contains(GV_ViewJobs.DataKeys[i].Value))
            {
                StartJob(GV_ViewJobs.DataKeys[i].Value.ToString());
                arr.Remove(GV_ViewJobs.DataKeys[i].Value);
            }
        }
        ViewState["SelectedRecords"] = arr;
        hfCount.Value = "0";
        GV_ViewJobs.AllowPaging = true;
        this.FillGrid();
        ShowMessageRun(count);
    }
    private void StartJob(string JobID)
    {
        int jobId = Convert.ToInt32(JobID);
        if (!JobRunner.IsJobQueuedOrRunning(jobId))
        {
            JobRunner.RunJob(jobId);
        }
    }
    
  • and my JobRunner.cs class (all coding)

JobRunner.cs ---------------------------------------------------

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Text;
    using System.IO;
    using System.Net.Mail;
    using System.Threading;
    /// <summary>
    /// Summary description for JobRunner
    /// </summary>
    public static class JobRunner
    {
        private static List<JobInfo> ActiveJobs = new List<JobInfo>();
        //public static JobRunner()
        //{
        //    //
        //    // TODO: Add constructor logic here
        //    //
        //}
        public static void RunJob(int jobId)
        {
            lock (ActiveJobs)
            {
                JobInfo jobInfo = FindQueuedOrRunningJob(jobId);

                if (jobInfo != null)
                    return;

                jobInfo = FindExitedJob(jobId);

                if (jobInfo == null)
                {
                    jobInfo = new JobInfo(jobId);
                    ActiveJobs.Add(jobInfo); // Default status is Queued
                }
                else
                {
                    jobInfo.State = JobInfo.JobState.Queued;
                }

                ThreadPool.QueueUserWorkItem(new WaitCallback(StartJob), jobInfo);
            }
        }
        public static bool IsJobQueuedOrRunning(int jobId)
        {
            return FindQueuedOrRunningJob(jobId) != null;
        }
        public static JobInfo FindJob(int jobId)
        {
            JobInfo ji = FindQueuedOrRunningJob(jobId);

            if (ji != null)
                return ji;

            return FindExitedJob(jobId);
        }
        public static JobInfo FindQueuedOrRunningJob(int jobId)
        {
            lock (ActiveJobs)
            {
                for (int i = 0; i < ActiveJobs.Count; i++)
                {
                    JobInfo ji = ActiveJobs[i];
                    if (ji.JobId == jobId && (ji.State == JobInfo.JobState.Queued | ji.State == JobInfo.JobState.Running))
                        return ji;
                }

                return null;
            }
        }
        public static JobInfo FindExitedJob(int jobId)
        {
            lock (ActiveJobs)
            {
                for (int i = 0; i < ActiveJobs.Count; i++)
                {
                    JobInfo ji = ActiveJobs[i];

                    if (ji.JobId == jobId && ji.State == JobInfo.JobState.Exited)
                        return ji;
                }

                return null;
            }
        }
        public static void StartJob(object stateInfo)
        {
            JobInfo jobInfo = (JobInfo)stateInfo;
            int jobId = jobInfo.JobId;
            jobInfo.State = JobInfo.JobState.Running;
            // Email settings
            string fromName = ConfigurationManager.AppSettings["Newsletter_FromName"];
            string fromEmailAddress = ConfigurationManager.AppSettings["Newsletter_FromEmailAddress"];
            SmtpClient client = Util.GetSmtpClient();
            // For logging
            int emailsSentInThisAttempt = 0;
            try
            {
                using (SqlConnection con = Util.GetConnection())
                {
                    con.Open();
                    jobInfo.Log(con, "Connected to database...");
                    // Step 1: Retrieving job information
                    string subject, plainText;
                    DatabaseHelper.GetJobInfo(con, jobInfo.JobId, out subject, out plainText);
                    jobInfo.Log(con, String.Format("Retrieved job #{0} information...", jobId));
                    // Creating a loop to send all emails one-by-one
                    while (true)
                    {
                        // Step 2: Retrieving one email from the list
                        // to whom this email will be sent
                        //int subscriberId;
                        string email;
                        //int validationCode;

                        //DatabaseHelper.PopAllotedEmail(con, jobId, out subscriberId,out email, out validationCode);
                        DatabaseHelper.PopAllotedEmail(con, jobId, out email);
                        if (email == null)
                            break;

                        // Step 3: Sending email
                        try
                        {
                            //SendEmail(fromName, fromEmailAddress, email, subject, plainText, client, subscriberId,validationCode);
                            SendEmail(fromName, fromEmailAddress, email, subject, plainText, client);
                        }
                        catch (Exception ex)
                        {
                            DatabaseHelper.PushAllotedEmail(jobId, email);
                            jobInfo.Log(con,
                        String.Format("Could not send email to: {0}",
                            email));

                            throw ex;
                        }

                        emailsSentInThisAttempt++;
                    }

                    DatabaseHelper.SetJobCompleted(con, jobId, DateTime.Now);
                    jobInfo.Log(con, "Successfully delivered " +
                emailsSentInThisAttempt + " email(s).");
                    jobInfo.Log(con, "Exiting with success!");
                }
            }
            catch (Exception ex)
            {
                jobInfo.Log("Exception: " + ex.Message);
                jobInfo.Log("Exiting with disgrace!");
            }
            finally
            {
                jobInfo.State = JobInfo.JobState.Exited;
            }
        }
        private static void SendEmail(string fromName, string fromEmailAddress, string toEmailAddress, string subject, string plainText, SmtpClient client)
        {
            MailMessage msg = new MailMessage();
            msg.IsBodyHtml = true;
            client.EnableSsl = true;
            if (fromName != null)
                msg.From = new MailAddress(fromName + " <" + fromEmailAddress + ">");
            else
                msg.From = new MailAddress(fromEmailAddress);
            msg.To.Add(new MailAddress(toEmailAddress));
            msg.Subject = subject;
            string pathToApp = ConfigurationManager.AppSettings["Newsletter_PathToApplication"];
            string unsubscribeText = "<br/>\r\n\r\n---------------------------\r\n" +
                                     "To unsubscribe, please click the following link:\r\n" +
                                     pathToApp + "Unsubscribe.aspx";
            msg.Body = plainText + unsubscribeText;
            client.Send(msg);
        }
        public class JobInfo
        {
            public enum JobState { Queued, Running, Exited }
            public int JobId
            {
                get
                {
                    return JobId;
                }
                set
                {
                    JobId = value; // <- Exception occurred here.
                }
            }
            public JobState State
            {
                get
                {
                    return State;
                }
                set
                {
                    State = value;
                }
            }
            public JobInfo(int jobId)
            {
                JobId = jobId;
                State = JobState.Queued;
            }
            public void Log(string message)
            {
                DatabaseHelper.AddLogMessage(JobId, DateTime.Now, message);
            }
            public void Log(SqlConnection con, string message)
            {
                DatabaseHelper.AddLogMessage(con, JobId, DateTime.Now, message);
            }
            public override bool Equals(object obj)
            {
                if (obj is JobInfo)
                {
                    JobInfo otherJobInfo = (JobInfo)obj;
                    if (JobId == otherJobInfo.JobId && State == otherJobInfo.State)
                        return true;
                }
                return false;
            }
        }
    }

The exception:

"System.StackOverflowException was unhandled An unhandled exception of type 'System.StackOverflowException' occurred in App_Code.okrls50x.dll"

  • whether i'm also getting one warning message at compile time like "'JobRunner.JobInfo' overrides Object.Equals(object o) but does not override Object.GetHashCode()"

please help i there problem with Get Set Properties in JobInfo method ?....

Was it helpful?

Solution

One of these properties caused the StackOverflowException:

public int JobId
            {
                get
                {
                    return JobId;
                }
                set
                {
                    JobId = value; 
                }
            }
            public JobState State
            {
                get
                {
                    return State;
                }
                set
                {
                    State = value;
                }
            }

You can implement a Property as (autoimplemented):

public int JobId { get; set; }

Or you can implement it manually with a backing field:

private int _jobId;
public int JobId
{
    get { return _jobId; }
    set { _jobId = value; }
}

OTHER TIPS

The problem is that somewhere in the code you have a property

JobState State 
{ 
   get { return State; } 
   set { State = value; } //THIS LINE RUNS in STACKOVERFLOW 
}

to fix this declare variable JobState, like this:

private JobState state;
public JobState State 
{ 
     get { return state; } 
     set { state= value; } 
 }
public JobState State
            {
                get
                {
                    return State;
                }
                set
                {
                    if(value != State)
                    {
                       State = value;
                    }
                }
            }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top