Ejemplo n.º 1
0
        private void AddServices(TreeNode currentNode, AccountServiceElementCollection accountServiceElementCollection = null, WorkflowStepElementCollection workflowStepElementCollection = null)
        {
            TreeNode current;

            if (accountServiceElementCollection != null)
            {
                foreach (AccountServiceElement accountServiceElement in accountServiceElementCollection)
                {
                    ActiveServiceElement activeServiceElement = new ActiveServiceElement(accountServiceElement);
                    current     = currentNode.Nodes.Add(activeServiceElement.Name);
                    current.Tag = activeServiceElement;
                    AddServices(current, workflowStepElementCollection: activeServiceElement.Workflow);
                }
            }
            else if (workflowStepElementCollection != null)
            {
                foreach (WorkflowStepElement stepElement in workflowStepElementCollection)
                {
                    current         = currentNode.Nodes.Add(stepElement.ActualName);
                    current.Checked = stepElement.IsEnabled;
                    current.Tag     = stepElement;
                    AddServices(current, workflowStepElementCollection: stepElement.BaseConfiguration.Element.Workflow);
                }
            }
            return;
        }
Ejemplo n.º 2
0
        public void Start(int?accountID = null, Dictionary <string, string> options = null)
        {
            ActiveServiceElement configuration;

            if (accountID == null)
            {
                configuration = new ActiveServiceElement(this.Configuration);
                if (options != null)
                {
                    configuration.Options.Merge(options);
                }

                Start(Service.CreateInstance(configuration));
            }
            else
            {
                configuration = new ActiveServiceElement(this.Accounts[accountID.Value]);
                if (options != null)
                {
                    configuration.Options.Merge(options);
                }

                Start(Service.CreateInstance(configuration, accountID.Value));
            }
        }
Ejemplo n.º 3
0
        public bool AddToSchedule(string serviceName, int accountID, DateTime targetTime, Edge.Core.SettingsCollection options)
        {
            AccountElement account = EdgeServicesConfiguration.Current.Accounts.GetAccount(accountID);

            if (account == null)
            {
                Log.Write(Program.LS, String.Format("Ignoring AddToSchedule request for account {0} which does not exist.", accountID), LogMessageType.Warning);
                return(false);
            }

            AccountServiceElement service = account.Services[serviceName];

            if (service == null)
            {
                Log.Write(Program.LS, String.Format("Ignoring AddToSchedule request for service {0} which does not exist in account {1}.", serviceName, accountID), LogMessageType.Warning);
                return(false);
            }

            var             activeServiceElement = new ActiveServiceElement(service);
            ServicePriority priority             = activeServiceElement.Options.ContainsKey("ServicePriority") ?
                                                   (ServicePriority)Enum.Parse(typeof(ServicePriority), activeServiceElement.Options["ServicePriority"]) :
                                                   ServicePriority.Normal;

            AddToSchedule(activeServiceElement, account, targetTime, options, priority);
            return(true);
        }
        /*=========================*/
        #endregion

        #region Generate
        /*=========================*/

        /// <summary>
        ///
        /// </summary>
        internal static ServiceInstance Generate(EnabledConfigurationElement config, ServiceInstance parentInstance, int accountID)
        {
            ActiveServiceElement activeConfig;

            // Get the right constructor
            if (config is ServiceElement)
            {
                activeConfig = new ActiveServiceElement((ServiceElement)config);
            }
            else if (config is ExecutionStepElement)
            {
                activeConfig = new ActiveServiceElement((ExecutionStepElement)config);
            }
            else if (config is AccountServiceElement)
            {
                activeConfig = new ActiveServiceElement((AccountServiceElement)config);
            }
            else if (config is AccountServiceSettingsElement)
            {
                activeConfig = new ActiveServiceElement((AccountServiceSettingsElement)config);
            }
            else
            {
                throw new ArgumentException("Configuration is an unrecognized class.", "config");
            }

            // Don't allow non-enabled services
            if (!activeConfig.IsEnabled)
            {
                throw new InvalidOperationException(String.Format("Cannot create an instance of a disabled service. Set IsEnabled to true in the configuration file in order to run. Service name: {0}", activeConfig.Name));
            }

            return(new ServiceInstance(activeConfig, parentInstance, accountID));
        }
        /// <summary>
        /// Check the service rule and add it if needed.
        /// </summary>
        /// <param name="serviceElement"></param>
        /// <remarks>
        /// We schedule the table for next day.
        /// For example on sunday 23:00 we schedule the table for monday.
        /// </remarks>
        /// <param name="childService">if we add a service request this service is the requested child service to schedule.</param>
        public void AddServicesByRules(AccountServiceElement accountServiceElement, int accountID, ServiceInstance childService)
        {
            ActiveServiceElement element = new ActiveServiceElement(accountServiceElement);

            //TODO: check if there is parent to the service

            foreach (SchedulingRuleElement rule in element.SchedulingRules)
            {
                // TODO: to check if there are same scheduling rules to account and service.
                HandleRule(accountServiceElement, accountID, childService, rule);
            }
        }
Ejemplo n.º 6
0
        public void AddToSchedule(ActiveServiceElement activeServiceElement, AccountElement account, DateTime targetTime, Edge.Core.SettingsCollection options, ServicePriority servicePriority)
        {
            if (options != null)
            {
                foreach (string option in options.Keys)
                {
                    activeServiceElement.Options[option] = options[option];
                }
            }

            //base configuration
            var baseConfiguration = new ServiceConfiguration()
            {
                Name                    = activeServiceElement.Name,
                MaxConcurrent           = activeServiceElement.MaxInstances,
                MaxConcurrentPerProfile = activeServiceElement.MaxInstancesPerAccount
            };

            //configuration per profile
            var instanceConfiguration = new ServiceConfiguration()
            {
                BaseConfiguration = baseConfiguration,
                Name                    = activeServiceElement.Name,
                MaxConcurrent           = (activeServiceElement.MaxInstances == 0) ? 9999 : activeServiceElement.MaxInstances,
                MaxConcurrentPerProfile = (activeServiceElement.MaxInstancesPerAccount == 0) ? 9999 : activeServiceElement.MaxInstancesPerAccount,
                LegacyConfiguration     = activeServiceElement
            };

            //scheduling rules
            instanceConfiguration.SchedulingRules.Add(new SchedulingRule()
            {
                Scope             = SchedulingScope.UnPlanned,
                SpecificDateTime  = targetTime,
                MaxDeviationAfter = TimeSpan.FromMinutes(30),
                Hours             = new List <TimeSpan>(),
                GuidForUnplaned   = Guid.NewGuid(),
            });

            instanceConfiguration.SchedulingRules[0].Hours.Add(new TimeSpan(0, 0, 0, 0));

            Profile profile = new Profile()
            {
                ID       = account.ID,
                Name     = account.ID.ToString(),
                Settings = new Dictionary <string, object>()
            };

            profile.Settings.Add("AccountID", account.ID);
            instanceConfiguration.SchedulingProfile = profile;

            _scheduler.AddNewServiceToSchedule(instanceConfiguration);
        }
        /// <summary>
        /// Initializing service from current configuration
        /// </summary>
        /// <param name="timePeriod">Service time period</param>
        /// <param name="serviceName">Service Name , See Const</param>
        /// <param name="channels">Channels List in string format seperated by comma</param>
        /// <param name="accounts">Accounts List in string format seperated by comma</param>
        internal void InitServices(DateTimeRange timePeriod, string serviceName, string channels, string accounts, Dictionary <string, Object> eventsHandlers)
        {
            try
            {
                ActiveServiceElement serviceElements = new ActiveServiceElement(EdgeServicesConfiguration.Current.Accounts.GetAccount(-1).Services[serviceName]);



                //Removing overide options
                serviceElements.Options.Remove("fromDate");
                serviceElements.Options.Remove("toDate");
                serviceElements.Options.Remove("ChannelList");
                serviceElements.Options.Remove("AccountsList");

                // TimePeriod
                serviceElements.Options.Add("fromDate", timePeriod.Start.ToDateTime().ToString());
                serviceElements.Options.Add("toDate", timePeriod.End.ToDateTime().ToString());

                serviceElements.Options.Add("ChannelList", channels);
                serviceElements.Options.Add("AccountsList", accounts);
                serviceElements.Options.Add("PmsServiceName", serviceName);


                //Update WorkFlow
                foreach (WorkflowStepElement step in serviceElements.Workflow)
                {
                    //CHECK IF CHILD SERVICE OPTION IS -> PMS = ENABLED
                    if (step.Options.ContainsKey("PMS") && !step.Options["PMS"].ToString().ToUpper().Equals("ENABLED"))
                    {
                        step.IsEnabled = false;
                    }
                    else
                    {
                        step.IsEnabled = true;
                    }
                }

                ServiceInstance = Edge.Core.Services.Service.CreateInstance(serviceElements);

                ServiceInstance.OutcomeReported       += (EventHandler)eventsHandlers[Const.EventsTypes.ParentOutcomeReportedEvent];
                ServiceInstance.StateChanged          += (EventHandler <ServiceStateChangedEventArgs>)eventsHandlers[Const.EventsTypes.ParentStateChangedEvent];
                ServiceInstance.ChildServiceRequested += (EventHandler <ServiceRequestedEventArgs>)eventsHandlers[Const.EventsTypes.ChildServiceRequested];

                //instance.ProgressReported += new EventHandler(instance_ProgressReported);
                ServiceInstance.Initialize();
            }
            catch (Exception ex)
            {
                throw new Exception("Could not init validation service, Check configuration", ex);
            }
        }
Ejemplo n.º 8
0
        void OnChildServiceRequested(int stepNumber, int attemptNumber, SettingsCollection options)
        {
            // Get the step configuration elements
            WorkflowStepElement           stepConfig   = this.Configuration.Workflow[stepNumber];
            AccountServiceSettingsElement stepSettings =
                this.Configuration.StepSettings != null ?
                this.Configuration.StepSettings[stepConfig] :
                null;

            // Take the step configuration
            ActiveServiceElement configuration = stepSettings != null ?
                                                 new ActiveServiceElement(stepSettings) :
                                                 new ActiveServiceElement(stepConfig);

            // Add child-specific options
            if (options != null)
            {
                configuration.Options.Merge(options);
            }

            // Add parent options, without overriding child options with the same name
            foreach (var parentOption in this.Configuration.Options)
            {
                if (!configuration.Options.ContainsKey(parentOption.Key))
                {
                    configuration.Options.Add(parentOption.Key, parentOption.Value);
                }
            }

            // Add parent extensions, without overriding child options with the same name
            foreach (var parentExtension in this.Configuration.Extensions)
            {
                if (!configuration.Extensions.ContainsKey(parentExtension.Key))
                {
                    configuration.Extensions.Add(parentExtension.Key, parentExtension.Value);
                }
            }

            // Generate a child instance
            ServiceInstance child = Service.CreateInstance(configuration, this, this.AccountID);

            child.StateChanged     += _childStateHandler;
            child.OutcomeReported  += _childOutcomeHandler;
            child.ProgressReported += _childProgressHandler;
            _childServices.Add(child, stepNumber);

            if (ChildServiceRequested != null)
            {
                ChildServiceRequested(this, new ServiceRequestedEventArgs(child, attemptNumber));
            }
        }
        /*=========================*/
        #endregion

        #region Constructor
        /*=========================*/

        /// <summary>
        ///
        /// </summary>
        internal ServiceInstance(ActiveServiceElement activeConfiguration, ServiceInstance parentInstance, int accountID)
        {
            ActiveConfigurationProperty.SetValue(this, activeConfiguration);
            ParentInstanceProperty.SetValue(this, parentInstance);

            if (accountID > -1)
            {
                AccountIDProperty.SetValue(this, accountID);
            }

            _childStateHandler   = new EventHandler <ServiceStateChangedEventArgs>(ChildStateChanged);
            _childOutcomeHandler = new EventHandler(ChildOutcomeReported);

            Log = new Log(this);
        }
        public ServiceInstanceInfo(ServiceInstance instance)
        {
            _accountID     = instance.AccountID;
            _instanceID    = instance.InstanceID;
            _priority      = instance.Priority;
            _config        = instance.Configuration;
            _rule          = instance.ActiveSchedulingRule;
            _timeStarted   = instance.TimeStarted;
            _timeScheduled = instance.TimeScheduled;
            _serviceUrl    = instance.ServiceUrl;

            if (instance.ParentInstance != null)
            {
                _parentInstanceData = new ServiceInstanceInfo(instance.ParentInstance);
            }
        }
Ejemplo n.º 11
0
        /*=========================*/
        #endregion

        #region Constructor
        /*=========================*/

        /// <summary>
        ///
        /// </summary>
        internal ServiceInstance(ActiveServiceElement activeConfiguration, ServiceInstance parentInstance, int accountID)
        {
            this.Guid = Guid.NewGuid();
            ActiveConfigurationProperty.SetValue(this, activeConfiguration);
            ParentInstanceProperty.SetValue(this, parentInstance);
            _logSource = activeConfiguration.Name;

            if (accountID > -1)
            {
                AccountIDProperty.SetValue(this, accountID);
            }

            _childStateHandler    = new EventHandler <ServiceStateChangedEventArgs>(ChildStateChanged);
            _childOutcomeHandler  = new EventHandler(ChildOutcomeReported);
            _childProgressHandler = new EventHandler(ChildProgressReported);
        }
Ejemplo n.º 12
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);
            }
        }
Ejemplo n.º 13
0
        protected static T FromLegacyConfiguration <T>(NamedConfigurationElement legacyConfiguration, ServiceConfiguration baseConfiguration = null, Profile profile = null, Dictionary <string, string> options = null) where T : ServiceConfiguration, new()
        {
            if (legacyConfiguration is AccountServiceElement || legacyConfiguration is WorkflowStepElement || legacyConfiguration is ActiveServiceElement)
            {
                if (baseConfiguration == null)
                {
                    throw new ArgumentNullException("baseConfiguration", "When creating a configuration from a Legacy.AccountServiceElement or Legacy.ActiveServiceElement, baseConfiguration must be supplied.");
                }
                if (profile == null)
                {
                    throw new ArgumentNullException("profile", "When creating a configuration from a Legacy.AccountServiceElement or Legacy.ActiveServiceElement, profile must be supplied.");
                }
            }
            if (legacyConfiguration is ServiceElement && !(legacyConfiguration is ActiveServiceElement))
            {
                if (baseConfiguration != null)
                {
                    throw new ArgumentException("baseConfiguration", "When creating a configuration from a Legacy.ServiceInstance, baseConfiguration must be null.");
                }
                if (profile != null)
                {
                    throw new ArgumentException("profile", "When creating a configuration from a Legacy.ServiceInstance, profile must be null.");
                }
            }

            ServiceElement legacy;

            if (legacyConfiguration is AccountServiceElement)
            {
                legacy = new ActiveServiceElement(legacyConfiguration as AccountServiceElement);
            }
            else if (legacyConfiguration is WorkflowStepElement)
            {
                legacy = new ActiveServiceElement(legacyConfiguration as WorkflowStepElement);
            }
            else
            {
                if (options != null)
                {
                    legacy = new ActiveServiceElement((ServiceElement)legacyConfiguration);
                }
                else
                {
                    legacy = (ServiceElement)legacyConfiguration;
                }
            }
            if (options != null)
            {
                legacy.Options.Merge(options);
            }

            T serviceConfiguration = new T()
            {
                _name                   = legacy.Name,
                MaxConcurrent           = (legacy.MaxInstances == 0) ? 9999 : legacy.MaxInstances,
                MaxConcurrentPerProfile = (legacy.MaxInstancesPerAccount == 0) ? 9999 : legacy.MaxInstancesPerAccount,
                _legacyConfiguration    = legacy,
                _baseConfiguration      = baseConfiguration,
                _schedulingProfile      = profile
            };

            if (legacy.Options.ContainsKey("ServicePriority"))
            {
                serviceConfiguration._priority = int.Parse(legacy.Options["ServicePriority"]);
            }

            //scheduling rules
            foreach (SchedulingRuleElement schedulingRuleElement in legacy.SchedulingRules)
            {
                SchedulingRule rule = SchedulingRule.FromLegacyRule(schedulingRuleElement);
                if (serviceConfiguration.SchedulingRules == null)
                {
                    serviceConfiguration.SchedulingRules = new List <SchedulingRule>();
                }
                serviceConfiguration.SchedulingRules.Add(rule);
            }

            return(serviceConfiguration);
        }
Ejemplo n.º 14
0
        public bool AddToSchedule(string serviceName, int accountID, DateTime targetTime, Edge.Core.SettingsCollection options)
        {
            bool respond = true;

            try
            {
                ServiceConfiguration myServiceConfiguration = new ServiceConfiguration();
                ServiceConfiguration baseConfiguration      = new ServiceConfiguration();
                ActiveServiceElement activeServiceElement   = new ActiveServiceElement(EdgeServicesConfiguration.Current.Accounts.GetAccount(accountID).Services[serviceName]);
                if (options != null)
                {
                    foreach (string option in options.Keys)
                    {
                        activeServiceElement.Options[option] = options[option];
                    }
                }
                ServiceElement serviceElement = EdgeServicesConfiguration.Current.Services[serviceName];

                //base configuration;
                baseConfiguration.Name                    = serviceElement.Name;
                baseConfiguration.MaxConcurrent           = serviceElement.MaxInstances;
                baseConfiguration.MaxCuncurrentPerProfile = serviceElement.MaxInstancesPerAccount;


                //configuration per profile

                myServiceConfiguration = new ServiceConfiguration();

                myServiceConfiguration.Name = activeServiceElement.Name;
                if (activeServiceElement.Options.ContainsKey("ServicePriority"))
                {
                    myServiceConfiguration.priority = int.Parse(activeServiceElement.Options["ServicePriority"]);
                }
                myServiceConfiguration.MaxConcurrent           = (activeServiceElement.MaxInstances == 0) ? 9999 : activeServiceElement.MaxInstances;
                myServiceConfiguration.MaxCuncurrentPerProfile = (activeServiceElement.MaxInstancesPerAccount == 0) ? 9999 : activeServiceElement.MaxInstancesPerAccount;
                myServiceConfiguration.LegacyConfiguration     = activeServiceElement;
                //        //scheduling rules
                myServiceConfiguration.SchedulingRules.Add(new SchedulingRule()
                {
                    Scope             = SchedulingScope.UnPlanned,
                    SpecificDateTime  = DateTime.Now,
                    MaxDeviationAfter = new TimeSpan(0, 0, 45, 0, 0),
                    Hours             = new List <TimeSpan>(),
                    GuidForUnplaned   = Guid.NewGuid()
                });
                myServiceConfiguration.SchedulingRules[0].Hours.Add(new TimeSpan(0, 0, 0, 0));
                myServiceConfiguration.BaseConfiguration = baseConfiguration;
                Edge.Core.Scheduling.Objects.Profile profile = new Edge.Core.Scheduling.Objects.Profile()
                {
                    ID       = accountID,
                    Name     = accountID.ToString(),
                    Settings = new Dictionary <string, object>()
                };
                profile.Settings.Add("AccountID", accountID);
                myServiceConfiguration.SchedulingProfile = profile;
                _scheduler.AddNewServiceToSchedule(myServiceConfiguration);
            }
            catch (Exception ex)
            {
                respond = false;
                Edge.Core.Utilities.Log.Write("AddManualServiceListner", ex.Message, ex, Edge.Core.Utilities.LogMessageType.Error);
            }

            return(respond);
        }
Ejemplo n.º 15
0
        private void addBtn_Click(object sender, EventArgs e)
        {
            ServicePriority servicePriority = ServicePriority.Low;
            var             options         = new Edge.Core.SettingsCollection();
            DateTime        targetDateTime  = new DateTime(dateToRunPicker.Value.Year, dateToRunPicker.Value.Month, dateToRunPicker.Value.Day, timeToRunPicker.Value.Hour, timeToRunPicker.Value.Minute, 0);

            if (priorityCmb.SelectedItem != null)
            {
                switch (priorityCmb.SelectedItem.ToString())
                {
                case "Low":
                {
                    servicePriority = ServicePriority.Low;
                    break;
                }

                case "Normal":
                {
                    servicePriority = ServicePriority.Normal;
                    break;
                }

                case "High":
                {
                    servicePriority = ServicePriority.High;
                    break;
                }

                case "Immediate":
                {
                    servicePriority = ServicePriority.Immediate;
                    break;
                }
                }
            }
            int countedSelectedServices = 0;

            foreach (TreeNode accountNode in servicesTreeView.Nodes)
            {
                foreach (TreeNode serviceNode in accountNode.Nodes)
                {
                    if (!serviceNode.Checked)
                    {
                        continue;
                    }

                    countedSelectedServices++;
                    AccountElement       account = (AccountElement)accountNode.Tag;
                    ActiveServiceElement service = (ActiveServiceElement)serviceNode.Tag;
                    if (useOptionsCheckBox.Checked)
                    {
                        foreach (ListViewItem item in optionsListView.Items)
                        {
                            options.Add(item.SubItems[0].Text.Trim(), item.SubItems[1].Text.Trim());
                        }

                        DateTime from = FromPicker.Value;
                        DateTime to   = toPicker.Value;
                        if (to.Date < from.Date || to.Date > DateTime.Now.Date)
                        {
                            MessageBox.Show(String.Format("Account {0} service {1}: To date must be equal or greater than from date, and both should be less then today's date",
                                                          account.ID,
                                                          service.Name
                                                          ));
                            continue;
                        }

                        DateTimeRange daterange = new DateTimeRange()
                        {
                            Start = new DateTimeSpecification()
                            {
                                BaseDateTime = from,
                                Hour         = new DateTimeTransformation()
                                {
                                    Type = DateTimeTransformationType.Exact, Value = 0
                                },
                            },
                            End = new DateTimeSpecification()
                            {
                                BaseDateTime = to,
                                Hour         = new DateTimeTransformation()
                                {
                                    Type = DateTimeTransformationType.Max
                                },
                            }
                        };
                        options.Add(PipelineService.ConfigurationOptionNames.TimePeriod, daterange.ToAbsolute().ToString());
                    }

                    _listener.AddToSchedule(service, account, targetDateTime, options, servicePriority);
                    options.Clear();
                }
            }

            MessageBox.Show(String.Format("{0} unplanned services were added.", countedSelectedServices));
        }
Ejemplo n.º 16
0
        public bool AddToSchedule(string serviceName, int accountID, DateTime targetTime, SettingsCollection options)
        {
            // YANIV:
            // if cannot perform at requested time, or can only perform after max deviation expires -
            // throw exception with a message

            ActiveServiceElement startupElement = null;

            if (accountID < 0)
            {
                AccountServiceElement elem = ServicesConfiguration.SystemAccount.Services[serviceName];
                if (elem != null)
                {
                    startupElement = new ActiveServiceElement(elem);
                }
                else
                {
                    startupElement = new ActiveServiceElement(ServicesConfiguration.Services[serviceName]);
                }
            }
            else
            {
                AccountElement account = ServicesConfiguration.Accounts.GetAccount(accountID);
                if (account == null)
                {
                    // EXCEPTION:
                    return(false);
                    //throw new ArgumentException(
                    //    String.Format("Account with ID {0} does not exist.", accountID),
                    //    "accountID");
                }

                AccountServiceElement accountService = account.Services[serviceName];
                if (accountService == null)
                {
                    // EXCEPTION
                    // throw new ArgumentException(String.Format("Service {0} is not defined for account {1}", serviceName, account.Name), "serviceName");
                    return(false);
                    // Log.Write(String.Format("Service {0} is not defined for account {1}", serviceName, account.Name), LogMessageType.Warning);
                }
                else
                {
                    startupElement = new ActiveServiceElement(accountService);
                }
            }


            // Couldn't find exception
            if (startupElement == null)
            {
                // EXCEPTION:
                return(false);
                //throw new ArgumentException(
                //    String.Format("The requested service \"{0}\" could not be found.", serviceName),
                //    "serviceName");
            }

            // Merge the options
            if (options != null)
            {
                foreach (KeyValuePair <string, string> pair in options)
                {
                    startupElement.Options[pair.Key] = pair.Value;
                }
            }

            // Add the manual request.
            if (targetTime < DateTime.Now)
            {
                _builder.AddManualRequest(startupElement, accountID);
            }
            else
            {
                _builder.AddManualRequest(startupElement, targetTime, accountID);
            }

            return(true);
        }
Ejemplo n.º 17
0
        private void addBtn_Click(object sender, EventArgs e)
        {
            bool allSucceed = true;

            try
            {
                ServicePriority servicePriority      = ServicePriority.Low;
                Edge.Core.SettingsCollection options = new Edge.Core.SettingsCollection();
                DateTime targetDateTime = new DateTime(dateToRunPicker.Value.Year, dateToRunPicker.Value.Month, dateToRunPicker.Value.Day, timeToRunPicker.Value.Hour, timeToRunPicker.Value.Minute, 0);
                bool     result         = false;

                if (priorityCmb.SelectedItem != null)
                {
                    switch (priorityCmb.SelectedItem.ToString())
                    {
                    case "Low":
                    {
                        servicePriority = ServicePriority.Low;
                        break;
                    }

                    case "Normal":
                    {
                        servicePriority = ServicePriority.Normal;
                        break;
                    }

                    case "High":
                    {
                        servicePriority = ServicePriority.High;
                        break;
                    }

                    case "Immediate":
                    {
                        servicePriority = ServicePriority.Immediate;
                        break;
                    }
                    }
                }
                int countedSelectedServices = 0;
                foreach (TreeNode accountNode in servicesTreeView.Nodes)
                {
                    foreach (TreeNode serviceNode in accountNode.Nodes)
                    {
                        if (serviceNode.Checked)
                        {
                            countedSelectedServices++;
                            AccountElement       account = (AccountElement)accountNode.Tag;
                            ActiveServiceElement service = (ActiveServiceElement)serviceNode.Tag;
                            if (useOptionsCheckBox.Checked)
                            {
                                foreach (ListViewItem item in optionsListView.Items)
                                {
                                    options.Add(item.SubItems[0].Text.Trim(), item.SubItems[1].Text.Trim());
                                }

                                DateTime from = FromPicker.Value;
                                DateTime to   = toPicker.Value;
                                if (to.Date < from.Date || to.Date > DateTime.Now.Date)
                                {
                                    throw new Exception("to date must be equal or greater then from date, and both should be less then today's date");
                                }

                                if (chkBackward.Checked)
                                {
                                    while (from.Date <= to.Date)
                                    {
                                        //For backward compatbility
                                        options["Date"] = from.ToString("yyyyMMdd");
                                        result          = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                        options.Clear();
                                        if (!result)
                                        {
                                            allSucceed = result;
                                            MessageBox.Show(string.Format("Service {0} for account {1} did not run", service.Name, accountNode.Text));
                                        }
                                        from = from.AddDays(1);
                                    }
                                }
                                else
                                {
                                    DateTimeRange daterange = new DateTimeRange()
                                    {
                                        Start = new DateTimeSpecification()
                                        {
                                            BaseDateTime = from,
                                            Hour         = new DateTimeTransformation()
                                            {
                                                Type = DateTimeTransformationType.Exact, Value = 0
                                            },
                                        },
                                        End = new DateTimeSpecification()
                                        {
                                            BaseDateTime = to,
                                            Hour         = new DateTimeTransformation()
                                            {
                                                Type = DateTimeTransformationType.Max
                                            },
                                        }
                                    };
                                    options.Add(PipelineService.ConfigurationOptionNames.TimePeriod, daterange.ToAbsolute().ToString());
                                    result = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                    options.Clear();
                                    if (!result)
                                    {
                                        allSucceed = result;
                                        MessageBox.Show(string.Format("Service {0} for account {1} did not run", service.Name, accountNode.Text));
                                    }
                                }
                            }
                            else
                            {
                                result = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                if (!result)
                                {
                                    allSucceed = result;
                                }
                            }
                        }
                    }
                }
                if (!allSucceed)
                {
                    throw new Exception("Some services did not run");
                }
                else
                {
                    if (countedSelectedServices > 0)
                    {
                        MessageBox.Show(@"Unplaned service\services added successfully");
                    }
                    else
                    {
                        MessageBox.Show(@"No services selected");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public WizardSession Start(string WizardName)
        {
            //Debugger.Launch();

            //load the service from configuration file
            //CHANGED 1 (Service is taken from app.config- what to do if service not found?)
            int            wizardID;
            ServiceElement requestedWizardConfiguration = ServicesConfiguration.Services[WizardName];

            if (requestedWizardConfiguration == null)
            {
                throw new Exception("Wizard cannot be found");
            }



            //Get service data
            wizardID = int.Parse(requestedWizardConfiguration.Options["WizardID"]); //to insert in database it's int future
            //first step name
            ExecutionStepElement FirstStepCollector = GetFirstCollectorStep(requestedWizardConfiguration.ExecutionSteps);

            if (FirstStepCollector == null)
            {
                throw new Exception("No step collector found");
            }



            ActiveServiceElement configurationToRun = new ActiveServiceElement(requestedWizardConfiguration);


            //Initalize the main wizard service (account service...etc)

            ServiceInstance instance = Service.CreateInstance(configurationToRun);


            instance.ChildServiceRequested += new EventHandler <ServiceRequestedEventArgs>(instance_ChildServiceRequested);
            instance.ProgressReported      += new EventHandler(instance_ProgressReported);
            instance.StateChanged          += new EventHandler <ServiceStateChangedEventArgs>(instance_StateChanged);
            instance.OutcomeReported       += new EventHandler(instance_OutcomeReported);


            instance.Initialize();
            object sessionID = null;

            //Open new session by insert values in to the wizards_sessions_data table
            using (DataManager.Current.OpenConnection())
            {
                using (SqlCommand sqlCommand = DataManager.CreateCommand(@"INSERT INTO Wizards_Sessions_Data 
																		    (WizardID,CurrentStepName,ServiceInstanceID,WizardStatus)
																			Values (@WizardID:Int,@CurrentStepName:NvarChar,@ServiceInstanceID:BigInt,@WizardStatus:Int);SELECT @@IDENTITY"                                                                            ))
                {
                    sqlCommand.Parameters["@WizardID"].Value          = wizardID;
                    sqlCommand.Parameters["@CurrentStepName"].Value   = FirstStepCollector.Name;
                    sqlCommand.Parameters["@ServiceInstanceID"].Value = instance.InstanceID;
                    sqlCommand.Parameters["@WizardStatus"].Value      = WizardStatus.Collect;

                    sessionID = sqlCommand.ExecuteScalar();
                    if (sessionID == null)
                    {
                        throw new Exception("Error: Session not created");
                    }
                }
            }

            instance.Configuration.Options["SessionID"] = sessionID.ToString();

            //Create WizardSession object to return

            WizardSession wizardSession = new WizardSession();

            wizardSession.SessionID   = System.Convert.ToInt32(sessionID); //@@IDENTITY IS DECIMAL
            wizardSession.WizardID    = wizardID;
            wizardSession.CurrentStep = new StepConfiguration()
            {
                StepName = FirstStepCollector.Name
            };


            return(wizardSession);
        }