Exemplo n.º 1
0
 protected override void OnEnded(ServiceOutcome outcome)
 {
     // TODO: you can perform different operations here based on the 'outcome' variable.
     // Avoid doing complicated operations here that can take a long time or can cause exceptions
     // to be thrown.
     // If you don't need to do anything here, just delete this entire method.
 }
Exemplo n.º 2
0
 protected override void OnEnded(ServiceOutcome serviceOutcome)
 {
     if (serviceOutcome == ServiceOutcome.Aborted)
     {
         _builder.AbortAllservices();
     }
 }
        /*=========================*/
        #endregion

        #region Service Override Methods
        /*=========================*/

        /// <summary>
        /// Handle abort event.
        /// </summary>
        protected override void OnEnded(ServiceOutcome serviceOutcome)
        {
            if ((serviceOutcome == ServiceOutcome.Aborted) ||
                (serviceOutcome == ServiceOutcome.Failure))
            {
            }
        }
        void OnOutcomeReported(ServiceOutcome outcome)
        {
            OutcomeProperty.SetValue(this, outcome);
            this.Save();

            if (this.OutcomeReported != null)
            {
                OutcomeReported(this, EventArgs.Empty);
            }

            // Service is done, so unsubscribe to the engine's events
            if (_commChannel != null)
            {
                if (_commChannel.State == CommunicationState.Opened)
                {
                    _commChannel.Engine.Unsubscribe();
                }
                else
                {
                    _commChannel.Abort();
                }
            }

            /*
             * // Remove event handlers from child services
             * foreach (ServiceInstance child in _childServices.Keys)
             * {
             *  StateChanged -= _childStateHandler;
             *  OutcomeReported -= _childOutcomeHandler;
             * }
             */
        }
Exemplo n.º 5
0
 protected override void OnEnded(ServiceOutcome outcome)
 {
     if (_host != null && _host.State == System.ServiceModel.CommunicationState.Opened)
     {
         _host.Close();
     }
 }
        /*=========================*/
        #endregion

        #region Service Override Methods
        /*=========================*/

        /// <summary>
        /// Handle abort event.
        /// </summary>
        protected override void OnEnded(ServiceOutcome serviceOutcome)
        {
            if ((serviceOutcome == ServiceOutcome.Aborted) ||
                (serviceOutcome == ServiceOutcome.Failure))
            {
                // Delete old data from Today.
                DeleteDay(DayCode(_requiredDay), BackOfficeTable);
            }
        }
Exemplo n.º 7
0
        void Stop(ServiceOutcome outcome)
        {
            // Enforce only one stop call
            if (IsStopped)
            {
                return;
            }

            IsStopped = true;

            // Report an outcome, bitch
            if (outcome == ServiceOutcome.Unspecified)
            {
                Error("Service did not report any outcome, treating as failure.");
                outcome = ServiceOutcome.Failure;
            }
            else if (outcome == ServiceOutcome.Success)
            {
                StateInfo.Progress = 1;
            }

            // Start wrapping things up
            StateInfo.State = ServiceState.Ending;
            NotifyState();

            // Run the cleanup code, and time its execution
            Thread onEndedThread = new Thread(() =>
            {
                // Suppress thread abort because these are expected
                try { this.Cleanup(); }
                catch (ThreadAbortException) { }
                catch (Exception ex)
                {
                    Error("Error occured during cleanup.", ex);
                }
            });

            onEndedThread.Start();

            if (!onEndedThread.Join(MaxCleanupTime))
            {
                // Timeout, abort the thread and exit
                onEndedThread.Abort();
                //Log(String.Format("Cleanup timed out. Limit is {0}.", MaxCleanupTime.ToString()), LogMessageType.Error);
            }

            // Change state to ended
            StateInfo.TimeEnded = DateTime.Now;
            StateInfo.State     = ServiceState.Ended;
            StateInfo.Outcome   = outcome;
            NotifyState();

            // Unload app domain if Stop was called directly
            AppDomain.Unload(AppDomain.CurrentDomain);
        }
Exemplo n.º 8
0
        /*=========================*/
        #endregion

        #region Service Override Methods
        /*=========================*/

        /// <summary>
        /// Handle abort event.
        /// </summary>
        protected override void OnEnded(ServiceOutcome serviceOutcome)
        {
            if ((serviceOutcome == ServiceOutcome.Aborted) ||
                (serviceOutcome == ServiceOutcome.Failure))
            {
                if (_easyForexBackOffice != null)
                {
                    _easyForexBackOffice.Abort();
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        void IServiceEngine.ChildServiceOutcomeReported(int stepNumber, ServiceOutcome outcome)
        {
            StepInfo step = GetStepFromHistory(Instance.Configuration.ExecutionSteps[stepNumber]);

            if (step == null)
            {
                return;
            }

            step.ServiceOutcome = outcome;

            // We want to continue execution when a child has completed
            if (this.State == ServiceState.Waiting)
            {
                ((IServiceEngine)this).Run();
            }
        }
Exemplo n.º 10
0
        void DoWorkInternal()
        {
            ServiceOutcome outcome = ServiceOutcome.Unspecified;

            StateInfo.State = ServiceState.Running;
            NotifyState();

            // Run the service code, and time its execution
            _doWork = new Thread(() =>
            {
                // Suppress thread abort because these are expected
                try { outcome = this.DoWork(); }
                catch (ThreadAbortException) { }
                catch (Exception ex)
                {
                    Error("Error occured during execution.", ex);
                    outcome = ServiceOutcome.Failure;
                }
            });
            _doWork.Start();

            if (!_doWork.Join(DefaultMaxExecutionTime))
            {
                // Timeout, abort the thread and exit
                _doWork.Abort();
                outcome = ServiceOutcome.Timeout;
            }

            _doWork = null;

            if (outcome == ServiceOutcome.Unspecified)
            {
                StateInfo.State          = ServiceState.Paused;
                StateInfo.TimeLastPaused = DateTime.Now;
                NotifyState();
            }
            else
            {
                Stop(outcome);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Handle abort event - delete all data we insert.
        /// </summary>
        protected override void OnEnded(ServiceOutcome serviceOutcome)
        {
            if ((serviceOutcome == ServiceOutcome.Aborted) ||
                (serviceOutcome == ServiceOutcome.Failure))
            {
                #region Obsolete - delete data by AggregationType.
                // Delete old data on the same day.
                //if (_aggregationType == AggregationType.Empty)
                //{
                //}
                //else if (_aggregationType == AggregationType.Month) // Monthly report
                //{
                //    DeleteDay(DayCodeSummary(), AdWordsCreativeTable);
                //}
                //else // Daily report
                //{
                //    DeleteDay(DayCode(_requiredDay), AdWordsCreativeTable);
                //}
                #endregion

                DeleteDay(GetDayCode(_requiredDay), _tableName);
            }
        }
Exemplo n.º 12
0
        void Stop(ServiceOutcome outcome)
        {
            lock (_stopLock)
            {
                // Enforce only one stop call
                if (_stopped)
                {
                    throw new InvalidOperationException("Stop can only be called once.");
                }

                _stopped = true;

                // Kill the timer
                if (_executionTimer != null)
                {
                    _executionTimer.Stop();
                }

                // Tell the external process to close
                KillExternalProcess();

                // Indicates that stop was entered during an abort
                bool aborting = State == ServiceState.Aborting;

                // Change state to ended
                State = ServiceState.Ended;

                // Change outcome to whatever was reported
                if (aborting)
                {
                    _outcome = ServiceOutcome.Aborted;
                }
                else if (_exceptionThrown)
                {
                    _outcome = ServiceOutcome.Failure;
                }
                else
                {
                    // Apply outcome
                    _outcome = outcome;
                }

                // Call finalizers
                OnEnded(_outcome);

                // Notify subscribers
                if (_subscribers.ContainsKey(ServiceEventType.OutcomeReported))
                {
                    _subscribers[ServiceEventType.OutcomeReported].ForEach(delegate(IServiceSubscriber subscriber)
                    {
                        try
                        {
                            subscriber.OutcomeReported(_outcome);
                        }
                        catch (Exception ex)
                        {
                            Log.Write("Failed to notify the instance proxy (ServiceInstance object) of an engine event.", ex);
                        }
                    });
                }

                // Close WCF host
                if (_wcfHost != null)
                {
                    if (_wcfHost.State == CommunicationState.Faulted)
                    {
                        _wcfHost.Abort();
                    }
                    else
                    {
                        _wcfHost.Close();
                    }
                }

                // If stop was not called by DomainUnload, unload again
                AppDomain.Unload(AppDomain.CurrentDomain);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        protected virtual ServiceOutcome DoWork()
        {
            if (Outcome != ServiceOutcome.Unspecified || State != ServiceState.Running)
            {
                throw new InvalidOperationException("DoWork() cannot be called because the service has ended.");
            }

            // Simulate processing execution time
            if (Instance.Configuration.DebugDelay > 0)
            {
                Thread.Sleep(Instance.Configuration.DebugDelay);
            }

            // Service with no steps means instant success!
            if (Instance.Configuration.ExecutionSteps.Count < 1)
            {
                return(ServiceOutcome.Success);
            }

            // Add the first step of the history as null - indicator for starting
            if (_stepHistory.Count < 1)
            {
                _stepHistory.Add(null);
            }

            // The return result
            bool stepsInProgress = false;

            ServiceOutcome outcome = ServiceOutcome.Unspecified;

            // Loop over each step in the history
            foreach (StepInfo step in _stepHistory.ToArray())
            {
                bool moveToNextStep = true;

                if (step != null)
                {
                    stepsInProgress = stepsInProgress || step.ServiceState != ServiceState.Ended;

                    // As long as a blocking process is running, halt all processing
                    if (stepsInProgress && step.Config.IsBlocking)
                    {
                        break;
                    }

                    // Indicates whether to process next step
                    moveToNextStep = step.ServiceOutcome == ServiceOutcome.Success;

                    if (!step.FailureWasHandled && (step.ServiceOutcome == ServiceOutcome.Failure || step.ServiceOutcome == ServiceOutcome.CouldNotBeScheduled || step.ServiceOutcome == ServiceOutcome.Aborted))
                    {
                        if (step.FailureRepetitions < step.Config.FailureRepeat - 1 && step.ServiceOutcome != ServiceOutcome.Aborted)
                        {
                            step.ServiceState = ServiceState.Uninitialized;
                            step.FailureRepetitions++;
                        }
                        else
                        {
                            if (step.Config.FailureOutcome == FailureOutcome.Continue)
                            {
                                // Process same as Success
                                moveToNextStep = true;
                            }

                            // This here is due to base[] getter bug
                            else if
                            (
                                !step.Config.IsFailureHandler &&
                                step.Config.FailureHandler.Element != null &&
                                step.Config.FailureHandler.Element.ServiceToUse.Element.Name != null &&
                                !IsInStepHistory(step.Config.FailureHandler.Element) &&
                                IsStepConditionValid(step.Config.FailureHandler.Element.ConditionOptions, step.Config.FailureHandler.Element.Condition)
                            )
                            {
                                // Get the correct step element
                                AccountServiceSettingsElement stepSettings = Instance.Configuration.StepSettings != null ? Instance.Configuration.StepSettings[step.Config.FailureHandler.Element] : null;

                                // Add a new step, the failure handler
                                if (stepSettings != null)
                                {
                                    _stepHistory.Add(new StepInfo(stepSettings));
                                }
                                else
                                {
                                    _stepHistory.Add(new StepInfo(step.Config.FailureHandler.Element));
                                }

                                // Done handling this step's failure
                                step.FailureWasHandled = true;
                            }
                            else
                            {
                                // Terminate because there is no failure handling - abort and stop processing
                                outcome = ServiceOutcome.Failure;
                                break;
                            }
                        }
                    }
                }

                if (moveToNextStep)
                {
                    // Get rid of the first null used to jump start the processing loop
                    if (step == null)
                    {
                        _stepHistory.Remove(step);
                    }

                    // Get the next step of a failure handler
                    ExecutionStepElement nextStepConfig = GetNextStep(step == null ? null : step.StepConfig);

                    if (nextStepConfig == null)
                    {
                        // No steps left to process
                        if (_stepHistory.TrueForAll(new Predicate <StepInfo>(delegate(StepInfo s) { return(s.ServiceState == ServiceState.Ended); })))
                        {
                            // All steps ended - outcome successful
                            outcome = ServiceOutcome.Success;
                            break;
                        }
                        else
                        {
                            // There are still steps being run so wait for them to complete before reporting that we are done
                            continue;
                        }
                    }
                    else if (nextStepConfig.WaitForPrevious && stepsInProgress)
                    {
                        // The next step needs to wait for all previous steps to end - stop processing
                        break;
                    }
                    else
                    {
                        bool adding = true;
                        while (adding)
                        {
                            if (!IsInStepHistory(nextStepConfig))
                            {
                                // Get the correct step element
                                AccountServiceSettingsElement stepSettings = Instance.Configuration.StepSettings != null ? Instance.Configuration.StepSettings[nextStepConfig] : null;

                                // Schedule the next step as long as it hasn't been added already
                                if (stepSettings != null)
                                {
                                    _stepHistory.Add(new StepInfo(stepSettings));
                                }
                                else
                                {
                                    _stepHistory.Add(new StepInfo(nextStepConfig));
                                }
                            }

                            // If the step is blocking or if it's a failure handler, stop adding steps, otherwise add the next
                            if (nextStepConfig.IsBlocking || nextStepConfig == Instance.Configuration.ExecutionSteps[Instance.Configuration.ExecutionSteps.Count - 1])
                            {
                                adding = false;
                            }
                            else
                            {
                                nextStepConfig = GetNextStep(nextStepConfig);

                                // Only add the next if it doesn't require previous steps to end first
                                if (nextStepConfig == null || nextStepConfig.WaitForPrevious)
                                {
                                    adding = false;
                                }
                            }
                        }
                    }
                }
            }

            if (outcome == ServiceOutcome.Unspecified)
            {
                // Request any pending child steps to be run
                foreach (StepInfo step in _stepHistory)
                {
                    if (step.ServiceState == ServiceState.Uninitialized)
                    {
                        RequestChildService(Instance.Configuration.ExecutionSteps.IndexOf(step.StepConfig), step.FailureRepetitions + 1);
                    }
                }
            }

            return(outcome);
        }
Exemplo n.º 14
0
        /*=========================*/
        #endregion

        #region Execution
        /*=========================*/

        /// <summary>
        ///
        /// </summary>
        public void Run()
        {
            // Ignore any run commands when the state is not ready
            if (State != ServiceState.Ready && State != ServiceState.Waiting)
            {
                return;
            }

            // Init the execution timer
            if
            (
                _executionTimer == null &&
                (
                    Instance.ActiveSchedulingRule == null ||
                    (
                        Instance.ActiveSchedulingRule != null &&
                        Instance.ActiveSchedulingRule.CalendarUnit != CalendarUnit.AlwaysOn
                    )
                )
            )
            {
                _executionTimer          = new System.Timers.Timer(Instance.Configuration.MaxExecutionTime.TotalMilliseconds);
                _executionTimer.Elapsed += new System.Timers.ElapsedEventHandler(MaxExecutionTimeElapsed);
                _executionTimer.Start();
            }

            ServiceOutcome outcome = ServiceOutcome.Unspecified;

            // Differnet processecing depending on type
            if (Instance.Configuration.ServiceType == ServiceType.Executable)
            {
                // Delegate for reporting success outcome
                _processEndHandler = new EventHandler(delegate(object sender, EventArgs e)
                {
                    // This is run outside of this method
                    Stop(ServiceOutcome.Success);
                });

                _process = new Process();
                _process.StartInfo.FileName        = Instance.Configuration.Path;
                _process.StartInfo.Arguments       = Instance.Configuration.Arguments;
                _process.StartInfo.UseShellExecute = false;
                _process.EnableRaisingEvents       = true;
                _process.Exited += _processEndHandler;

                // Start the process - exceptions will be handled by service error handling plumbling
                _process.Start();

                //catch (Exception ex)
                //{
                //    // TODO: throw exception instead for infrastructure to catch
                //    throw new Exception("Failed to start external Win32 process.", ex);
                //}

                State = ServiceState.Running;
            }
            else
            {
                // Add other conditions for settings as run
                State   = ServiceState.Running;
                outcome = DoWork();
            }

            // Apply returned outcome
            if (outcome != ServiceOutcome.Unspecified)
            {
                // Stop and report outcome
                Stop(outcome);
            }
            else
            {
                // Change state to waiting till next Run() is called
                State = ServiceState.Waiting;
            }
        }
Exemplo n.º 15
0
 protected override void OnEnded(ServiceOutcome outcome)
 {
     // TODO: update delivery history automatically?
 }
Exemplo n.º 16
0
        // ==============================

        protected sealed override ServiceOutcome DoWork()
        {
            ServiceOutcome outcome = DoPipelineWork();

            return(outcome);
        }
 void IServiceSubscriber.OutcomeReported(ServiceOutcome outcome)
 {
     OnOutcomeReported(outcome);
 }
        protected override ServiceOutcome DoWork()
        {
            //Get the hour of the Day
            ServiceOutcome outcome   = ServiceOutcome.Success;
            int            hourOfDay = DateTime.Now.Hour;
            int            today     = Convert.ToInt32(DateTime.Now.DayOfWeek);

            if (today == 0)
            {
                today = 7;
            }


            StringBuilder campaign_specs = new StringBuilder();



            //prepere sqlstatment by time of day get all campaings by time and status != null and 1

            using (DataManager.Current.OpenConnection())
            {
                SqlCommand sqlCommand = DataManager.CreateCommand(string.Format(@"SELECT T2.campaignid,T0.Hour{0} 
																				FROM Campaigns_Scheduling T0
																				INNER JOIN User_GUI_Account T1 ON T0.Account_ID=T1.Account_ID
																				INNER JOIN UserProcess_GUI_PaidCampaign T2 ON T0.Campaign_GK=T2.Campaign_GK
																				WHERE T0.Day=@Day:Int AND T0.Account_ID=@Account_ID:Int 
																				AND (T0.Hour{0} =1 OR T0.Hour{0}=2) AND
																				T2.Channel_ID=@Channel_ID:Int AND T1.Status!=0 AND T2.campStatus<>3 AND T2.ScheduleEnabled=1"                                                                                , hourOfDay.ToString().PadLeft(2, '0')));
                sqlCommand.Parameters["@Day"].Value        = today;
                sqlCommand.Parameters["@Account_ID"].Value = this.Instance.AccountID;
                sqlCommand.Parameters["@Channel_ID"].Value = _channelID;


                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        long campaign_ID     = Convert.ToInt64(sqlDataReader[0]);
                        int  campaign_status = Convert.ToInt32(sqlDataReader[1]);
                        campaign_specs.Append("{\"campaign_id\":" + campaign_ID.ToString() + ",\"campaign_status\":" + campaign_status.ToString() + "},");
                    }
                }
            }


            /* For test only - capaign with deleted status
             * campaign_specs.Append("{\"campaign_id\":" + "60028003668686853" + ",\"campaign_status\":" + "2" + "},");
             * List<string> campaigns = GetCampaigns();*/
            if (!string.IsNullOrEmpty(campaign_specs.ToString()))
            {
                //Remove the last ","
                campaign_specs = campaign_specs.Remove(campaign_specs.Length - 1, 1);
                //add '[' ']' for json array
                campaign_specs = campaign_specs.Insert(0, '[');
                campaign_specs = campaign_specs.Insert(campaign_specs.Length, ']');

                string Errors = UpdateStatus(campaign_specs.ToString());
                if (!string.IsNullOrEmpty(Errors))
                {
                    Easynet.Edge.Core.Utilities.Log.Write(Errors, Easynet.Edge.Core.Utilities.LogMessageType.Error);
                    outcome = ServiceOutcome.Failure;
                }
            }
            return(outcome);
        }
Exemplo n.º 19
0
 /// <summary>
 /// When overriden in a derived class, handles last minute actions after the normal
 /// service execution has ended but before the outcome is reported.
 /// </summary>
 /// <param name="outcome"></param>
 protected virtual void OnEnded(ServiceOutcome outcome)
 {
 }
 protected override void OnEnded(ServiceOutcome outcome)
 {
     GC.Collect();
     base.OnEnded(outcome);
 }
Exemplo n.º 21
0
        protected override ServiceOutcome DoWork()
        {
            HttpWebRequest request;
            WebResponse    response;

            #region Init

            Dictionary <int, FacbookAccountParams> facbookAccountParams = new Dictionary <int, FacbookAccountParams>();
            StringBuilder strAccounts = new StringBuilder();

            foreach (AccountElement account in EdgeServicesConfiguration.Current.Accounts)
            {
                foreach (AccountServiceElement service in account.Services)
                {
                    if (service.Uses.Element.Name == "Facebook.GraphApi")
                    {
                        ActiveServiceElement activeService = new ActiveServiceElement(service);
                        facbookAccountParams.Add(account.ID, new FacbookAccountParams()
                        {
                            FacebookAccountID = activeService.Options[FacebookConfigurationOptions.Account_ID],
                            AccessToken       = activeService.Options[FacebookConfigurationOptions.Auth_AccessToken]
                        });
                        strAccounts.AppendFormat("{0},", account.ID);
                    }
                }
            }
            if (strAccounts.Length == 0)
            {
                Log.Write("No account runing facebook found", LogMessageType.Information);
                return(ServiceOutcome.Success);
            }
            else             //remove last ','
            {
                strAccounts.Remove(strAccounts.Length - 1, 1);



                this.ReportProgress(0.2);

                #endregion



                #region UpdateCampaignStatus

                ServiceOutcome outcome   = ServiceOutcome.Success;
                int            hourOfDay = DateTime.Now.Hour;
                int            today     = Convert.ToInt32(DateTime.Now.DayOfWeek);
                if (today == 0)
                {
                    today = 7;
                }


                Dictionary <int, Dictionary <long, int> > statusByCampaignID = new Dictionary <int, Dictionary <long, int> >();



                //prepere sqlstatment by time of day get all campaings by time and status != null and 1

                using (SqlConnection connection = new SqlConnection(AppSettings.GetConnectionString(this, "DB")))
                {
                    connection.Open();

                    SqlCommand sqlCommand = DataManager.CreateCommand(string.Format(@"SELECT distinct T0.Account_ID, T2.campaignid,T0.Hour{1} 
																				FROM Campaigns_Scheduling T0
																				INNER JOIN User_GUI_Account T1 ON T0.Account_ID=T1.Account_ID
																				INNER JOIN UserProcess_GUI_PaidCampaign T2 ON T0.Campaign_GK=T2.Campaign_GK
																				WHERE T0.Day=@Day:Int AND T0.Account_ID IN ({0}) 
																				AND (T0.Hour{1} =1 OR T0.Hour{1}=2) AND
																				T2.Channel_ID=6 AND T1.Status!=0 AND T2.campStatus<>3 AND T2.ScheduleEnabled=1 
																				ORDER BY T0.Account_ID"                                                                                , strAccounts.ToString(), hourOfDay.ToString().PadLeft(2, '0')));
                    sqlCommand.Parameters["@Day"].Value = today;
                    sqlCommand.Connection = connection;


                    using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                    {
                        while (sqlDataReader.Read())
                        {
                            int  account_id      = Convert.ToInt32(sqlDataReader["Account_ID"]);
                            long campaign_ID     = Convert.ToInt64(sqlDataReader["campaignid"]);
                            int  campaign_status = Convert.ToInt32(sqlDataReader[string.Format("Hour{0}", hourOfDay.ToString().PadLeft(2, '0'))]);
                            if (!statusByCampaignID.ContainsKey(account_id))
                            {
                                statusByCampaignID.Add(account_id, new Dictionary <long, int>());
                            }
                            statusByCampaignID[account_id][campaign_ID] = campaign_status;
                        }
                    }
                }



                foreach (KeyValuePair <int, Dictionary <long, int> > byAccount in statusByCampaignID)
                {
                    FacbookAccountParams param = facbookAccountParams[byAccount.Key];
                    string accessToken         = param.AccessToken;

                    foreach (var byCampaign in statusByCampaignID[byAccount.Key])
                    {
                        request        = (HttpWebRequest)HttpWebRequest.Create(string.Format(@"https://graph.facebook.com/{0}?campaign_status={1}&access_token={2}", byCampaign.Key, byCampaign.Value, accessToken));
                        request.Method = "POST";
                        string strResponse;
                        try
                        {
                            response = request.GetResponse();

                            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                            {
                                strResponse = stream.ReadToEnd();
                            }
                            if (strResponse != "true")
                            {
                                outcome = ServiceOutcome.Failure;
                                Edge.Core.Utilities.Log.Write(string.Format("Account {0} failed:{1}", byAccount.Key, strResponse), null, LogMessageType.Error, byAccount.Key);
                            }
                            else
                            {
                                Edge.Core.Utilities.Log.Write(string.Format("Account- {0} with campaign-{1} updated successfuly with value {2} for day num{3}", byAccount.Key, byCampaign.Key, byCampaign.Value, today), null, LogMessageType.Error, byAccount.Key);
                            }
                        }
                        catch (WebException ex)
                        {
                            using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
                            {
                                outcome     = ServiceOutcome.Failure;
                                strResponse = reader.ReadToEnd();
                                Edge.Core.Utilities.Log.Write(string.Format("Account {0} -{1}", byAccount.Key, strResponse), ex, LogMessageType.Error, byAccount.Key);
                            }
                        }
                    }
                }


                #endregion
                return(outcome);
            }
        }
        protected override Core.Services.ServiceOutcome DoPipelineWork()
        {
            #region Init
            this.Delivery = this.NewDelivery();

            this.Delivery.Account = new Data.Objects.Account()
            {
                ID         = this.Instance.AccountID,
                OriginalID = this.Instance.Configuration.Options[FacebookConfigurationOptions.Account_ID].ToString()
            };

            Delivery.Channel = new Data.Objects.Channel()
            {
                ID = 6
            };

            Delivery.Signature = "UpdateCampaignStatus";
            Delivery.TargetLocationDirectory = "Not Relevant";
            var configOptionsToCopyToDelivery = new string[] {
                FacebookConfigurationOptions.Account_ID,
                FacebookConfigurationOptions.Account_Name,
                FacebookConfigurationOptions.Auth_ApiKey,
                FacebookConfigurationOptions.Auth_AppSecret,
                FacebookConfigurationOptions.Auth_SessionKey,
                FacebookConfigurationOptions.Auth_SessionSecret,
                FacebookConfigurationOptions.Auth_RedirectUri,
                FacebookConfigurationOptions.Auth_AuthenticationUrl
            };
            foreach (string option in configOptionsToCopyToDelivery)
            {
                this.Delivery.Parameters[option] = this.Instance.Configuration.Options[option];
            }
            if (string.IsNullOrEmpty(this.Instance.Configuration.Options[FacebookConfigurationOptions.BaseServiceAddress]))
            {
                throw new Exception("facebook base url must be configured!");
            }



            this.ReportProgress(0.2);
            Delivery.Save();
            #endregion

            #region Authentication
            _urlAuth = string.Format(string.Format(Delivery.Parameters[FacebookConfigurationOptions.Auth_AuthenticationUrl].ToString(), Delivery.Parameters[FacebookConfigurationOptions.Auth_ApiKey],
                                                   Delivery.Parameters[FacebookConfigurationOptions.Auth_RedirectUri],
                                                   Delivery.Parameters[FacebookConfigurationOptions.Auth_AppSecret],
                                                   Delivery.Parameters[FacebookConfigurationOptions.Auth_SessionSecret]));

            HttpWebRequest request  = (HttpWebRequest)HttpWebRequest.Create(_urlAuth);
            WebResponse    response = request.GetResponse();

            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                this.Delivery.Parameters["AccessToken"] = stream.ReadToEnd();
            }



            #endregion


            #region UpdateCampaignStatus

            ServiceOutcome outcome   = ServiceOutcome.Success;
            int            hourOfDay = DateTime.Now.Hour;
            int            today     = Convert.ToInt32(DateTime.Now.DayOfWeek);
            if (today == 0)
            {
                today = 7;
            }


            Dictionary <long, int> statusByCampaignID = new Dictionary <long, int>();



            //prepere sqlstatment by time of day get all campaings by time and status != null and 1

            using (SqlConnection connection = new SqlConnection(AppSettings.GetConnectionString(this, "DB")))
            {
                connection.Open();

                SqlCommand sqlCommand = DataManager.CreateCommand(string.Format(@"SELECT distinct T2.campaignid,T0.Hour{0} 
																				FROM Campaigns_Scheduling T0
																				INNER JOIN User_GUI_Account T1 ON T0.Account_ID=T1.Account_ID
																				INNER JOIN UserProcess_GUI_PaidCampaign T2 ON T0.Campaign_GK=T2.Campaign_GK
																				WHERE T0.Day=@Day:Int AND T0.Account_ID=@Account_ID:Int 
																				AND (T0.Hour{0} =1 OR T0.Hour{0}=2) AND
																				T2.Channel_ID=@Channel_ID:Int AND T1.Status!=0 AND T2.campStatus<>3 AND T2.ScheduleEnabled=1"                                                                                , hourOfDay.ToString().PadLeft(2, '0')));
                sqlCommand.Parameters["@Day"].Value        = today;
                sqlCommand.Parameters["@Account_ID"].Value = this.Instance.AccountID;
                sqlCommand.Parameters["@Channel_ID"].Value = Delivery.Channel.ID;
                sqlCommand.Connection = connection;


                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        long campaign_ID     = Convert.ToInt64(sqlDataReader[0]);
                        int  campaign_status = Convert.ToInt32(sqlDataReader[1]);
                        statusByCampaignID.Add(campaign_ID, campaign_status);
                    }
                }
            }


            StringBuilder errorBuilder = new StringBuilder();
            foreach (KeyValuePair <long, int> item in statusByCampaignID)
            {
                request        = (HttpWebRequest)HttpWebRequest.Create(string.Format(@"https://graph.facebook.com/{0}?campaign_status={1}&{2}", item.Key, item.Value, Delivery.Parameters["AccessToken"].ToString()));
                request.Method = "POST";
                string strResponse;
                try
                {
                    response = request.GetResponse();

                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        strResponse = stream.ReadToEnd();
                    }
                    if (strResponse != "true")
                    {
                        outcome = ServiceOutcome.Failure;
                        errorBuilder.Append(strResponse);
                    }
                }
                catch (WebException ex)
                {
                    using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        strResponse = reader.ReadToEnd();
                        errorBuilder.Append(strResponse);
                    }
                }
            }
            if (errorBuilder.Length > 0)
            {
                Edge.Core.Utilities.Log.Write(errorBuilder.ToString(), Core.Utilities.LogMessageType.Error);
            }


            #endregion
            return(outcome);
        }