Exemplo n.º 1
0
        /// <summary>
        /// Processes an entry from the queue.
        /// </summary>
        /// <param name="entry">A file queue entry.</param>
        /// <returns>A boolean value that specifies if the queue entry has been 
        ///			processed successfully.</returns>
        public bool ProcessQueueEntry(
            FileQueueEntry entry)
        {
            string queryString = entry["QueryString"];

            this.message = new Message();
            this.message.FromQueue = true;
            this.message.QueryString = queryString;

            return this.SendToService();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Makes the connection to the email service and sends the request.
        /// </summary>
        private bool SendToService()
        {
            switch (this.message.Attempts) {
                case 0:
                    this.message.Server = ConfigurationSettings.AppSettings[CONFIG_PRIMARY_SERVICE];
                    break;

                case 1:
                    this.message.Server = ConfigurationSettings.AppSettings[CONFIG_SECONDARY_SERVICE];
                    break;

                default:
                    if (!this.message.FromQueue) {
                        FileQueueEntry queueEntry = new FileQueueEntry();
                        queueEntry["QueryString"] = this.message.QueryString;
                        queue.Enqueue(queueEntry);
                    }

                    //  NOTE:  we exit the method here
                    return false;
            }

            //  increament the attempt counter
            this.message.Attempts++;

            string url = this.message.Server; // + "?" + this.message.QueryString;

            try {
                // Create http request
                HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);

                // Set proxy if needed
                NameValueCollection config = (NameValueCollection) ConfigurationSettings.GetConfig("proxySettings/proxyInfo");
                if (config != null) {
                    WebProxy proxy = new WebProxy(config["proxyName"], int.Parse(config["port"]));
                    proxy.BypassProxyOnLocal = true;
                    proxy.Credentials = CredentialCache.DefaultCredentials;
                    request.Proxy = proxy;
                }

                // ---------  write the email information out via "post"  ----------
                request.Method = "POST";

                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] bytes = encoding.GetBytes(this.message.QueryString);

                // set the content type of the data being posted.
                request.ContentType = "application/x-www-form-urlencoded";

                // set the content length of the string being posted.
                request.ContentLength = bytes.Length;

                Stream reqStream = request.GetRequestStream();

                reqStream.Write(bytes, 0, bytes.Length);

                // close the Stream object.
                reqStream.Close();
                // ---------------------------------------------

                WebResponse response = request.GetResponse();
            //				StreamReader reader = new StreamReader(response.GetResponseStream());
                response.Close();
            } catch (Exception e) {
                //  log an error message
                string msg;
                if (this.message.Attempts == 1) {
                    msg = "Primary server unreachable: ";
                } else if (this.message.Attempts == 2) {
                    msg = "Secondary server failed: ";
                } else {
                    msg = "SendToService2: attempts= " + this.message.Attempts + ": ";
                }
                msg += ((this.message.FromQueue) ? "(from queue) " : "") + url;

                LogManager.GetCurrentClassLogger().Error(
                    errorMessage => errorMessage(msg), e);

                //  if it's the first or second attempt, retry
                if ((this.message.Attempts == 1) || (this.message.Attempts == 2)) {
                    return this.SendToService();
                }
            }

            return true;
        }
Exemplo n.º 3
0
 /// <summary>
 /// Implements the <c>MaxAttemptsProcessor</c> delegate for the
 /// <c>FileQueue</c>.  This is called by the <c>FileQueue</c> when
 /// a queued message is retried the max number of times.
 /// This method just moves the queue entry to another directory.
 /// </summary>
 /// <param name="entry">The queue entry that has been attempted
 ///			the max # of times.</param>
 public void MaxedOutQueueEntry(
     FileQueueEntry entry)
 {
     try {
         File.Move(queueDir + entry.FileName, failedDir + entry.FileName);
     } catch (Exception e) {
         LogManager.GetCurrentClassLogger().Error(
             errorMessage => errorMessage("ServiceMailer.MaxedOutQueueEntry "), e);
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Writes an entry to the queue.  If the entry already exists the info in the
        /// file is updated.  If it does not exist it is created.
        /// </summary>
        /// <param name="entry">The <c>FileQueueEntry</c> to write to the queue.</param>
        private void WriteQueueEntry(
            FileQueueEntry entry)
        {
            //  get the output to be written to the queue file
            String output = entry.ToString();

            //  open and truncate the file if it already exists, otherwise
            //  create it
            FileStream file;
            String path = this.queueInfo.queueLocation + entry.FileName;
            if (File.Exists(path)) {
                file = File.Open(path, FileMode.Truncate, FileAccess.Write);
            } else {
                file = File.Create(path);
            }

            //  write the output to the file
            Byte[] content = new UTF8Encoding(true).GetBytes(output);
            file.Write(content, 0, content.Length);
            file.Close();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Checks the queue directory for any entries and if there are entries attempts
        /// to process them.  This is the method called by the <c>Timer</c> to
        /// periodically process the queue.
        /// </summary>
        /// <param name="stateInfo">The <c>QueueInfo</c> containing the state
        ///			information of the <c>FileQueue</c> from which the Timer that
        ///			is calling this method originated.</param>
        private static void CheckQueue(
            Object stateInfo)
        {
            QueueInfo queueInfo = (QueueInfo)stateInfo;
            FileQueue fileQueue = new FileQueue(queueInfo);
            bool hadError = false;

            LogManager.GetCurrentClassLogger().Info(
                infoMessage => infoMessage("===== Checking Queue ====="));

            DirectoryInfo dirInfo = new DirectoryInfo(queueInfo.queueLocation);

            //  get the list of files in the queue directory
            FileInfo[] files = dirInfo.GetFiles("*.txt");

            //  for each queued file...
            foreach (FileInfo info in files) {
                try {
                    StreamReader reader = info.OpenText();
                    FileQueueEntry entry = new FileQueueEntry();
                    entry.SetFileName(info.Name);

                    int keyLineCnt = 0;
                    //  continue while there is more stuff in the file
                    while (reader.Peek() >= 0) {
                        try {
                            //  read the next line of the file
                            String line = reader.ReadLine();
                            //  find the position of the key/value delimiter
                            int delimPos = line.IndexOf(FileQueueEntry.QUEUE_FILE_DELIMITER);
                            String key = line.Substring(0, delimPos);
                            String val = line.Substring(delimPos + FileQueueEntry.QUEUE_FILE_DELIMITER.Length);

                            //  set the attributes of the queue entry from the
                            //  queued file
                            if (key == FileQueueEntry.Q_LABEL_QUEUE_TIME) {
                                entry.SetQueuedTime(DateTime.Parse(val));
                                keyLineCnt++;
                            } else if (key == FileQueueEntry.Q_LABEL_ATTEMPT_CNT) {
                                entry.SetAttempts(int.Parse(val));
                                keyLineCnt++;
                            } else if (key == FileQueueEntry.Q_LABEL_LAST_TIME) {
                                entry.SetLastAttemptTime(DateTime.Parse(val));
                                keyLineCnt++;
                            } else {
                                entry[key] = val;
                            }
                        } catch (Exception e) {
                            hadError = true;
                            LogManager.GetCurrentClassLogger().Error(
                                errorMessage => errorMessage("FileQueue.CheckQueue 1: "), e);
                        }
                    }
                    reader.Close();

                    bool processed = false;
                    //  if the entry was successfully processed, removed it
                    //  from the queue
                    try {
                        if (!hadError && queueInfo.processingMethod(entry)) {
                            fileQueue.Dequeue(entry);
                            processed = true;
                        }
                    } catch (Exception e) {
                        LogManager.GetCurrentClassLogger().Error(
                            errorMessage => errorMessage("Error processing queue entry: "), e);
                    }

                    //  if the entry was not successfully processed, first
                    //  see if we have reached the max # of attempts and it
                    //  so, call the MaxAttemptsHandler, otherwise update
                    //  the entry info
                    //  also, make sure we at least read the key
                    //  lines required to maintain the queue entry (beyond 3
                    //  is application data)
                    if (!processed && (keyLineCnt >= 3)) {
                        entry.SetAttempts(entry.Attempts + 1);
                        entry.SetLastAttemptTime(DateTime.Now);
                        fileQueue.WriteQueueEntry(entry);
                        //  if there is a max attempts set and we've reached it
                        //  call the handler method (if one is defined) for max attempts
                        //  and remove the entry from the queue
                        if ((queueInfo.maxAttempts > 0) && (entry.Attempts >= queueInfo.maxAttempts)) {
                            if (queueInfo.maxAttemptsMethod != null) {
                                queueInfo.maxAttemptsMethod(entry);
                            }
                            fileQueue.Dequeue(entry);
                        }
                    }
                } catch (Exception e) {
                    LogManager.GetCurrentClassLogger().Error(
                        errorMessage => errorMessage("FileQueue.CheckQueue 2: "), e);
                }
            }

            LogManager.GetCurrentClassLogger().Info(
                infoMessage => infoMessage("===== End Queue Check ====="));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Adds the given entry to the queue.
 /// </summary>
 /// <param name="entry">The entry to add to the queue.</param>
 public void Enqueue(
     FileQueueEntry entry)
 {
     this.WriteQueueEntry(entry);
 }
Exemplo n.º 7
0
 /// <summary>
 /// Removes the given entry from the queue.
 /// </summary>
 /// <param name="entry">The entry to remove from the queue.</param>
 public void Dequeue(
     FileQueueEntry entry)
 {
     File.Delete(this.queueInfo.queueLocation + entry.FileName);
 }