Пример #1
0
        public (State stepStep, NationalElfService serviceState, IList <char> stepsDone) ProcessOneSecond(
            State stepState)
        {
            (State updatedStepState, IImmutableList <WorkInProgress> workerState, ImmutableList <char> completed) =
                Enumerable.Range(0, WorkerState.Count).Aggregate(
                    (stepState, workerState: WorkerState, completed: ImmutableList <char> .Empty),
                    (acc, workerIndex) =>
            {
                WorkInProgress ws = acc.workerState[workerIndex];
                return(ws == null
                        ? (acc.stepState, acc.workerState, acc.completed)
                        : ws.MinutesRemaining == 1
                            ? (stepState.ExecuteStep(ws.Step),
                               acc.workerState.SetItem(workerIndex, null),
                               acc.completed.Add(ws.Step))
                            : (acc.stepState,
                               acc.workerState.SetItem(workerIndex, new WorkInProgress(ws.Step, ws.MinutesRemaining - 1)),
                               acc.completed));
            });

            IEnumerable <(char step, int workerIndex)> workToStart = updatedStepState
                                                                     .NextAvailable
                                                                     .Where(step => !workerState.Any(ws => ws?.Step == step))
                                                                     .Zip(workerState.Select((w, i) => (w, i)).Where(x => x.w == null).Select(x => x.i));

            var updatedWorkerState = workToStart.Aggregate(
                workerState,
                (s, x) => s.SetItem(x.workerIndex, new WorkInProgress(x.step, GetStepExecutionTime(x.step))));

            return(updatedStepState, new NationalElfService(updatedWorkerState, baseStepTime), completed);
        }
Пример #2
0
 public SqlConnectionEditor(WorkInProgress animation = null)
 {
     InitializeComponent();
     _animation = animation;
     cbxSQLServerName.DataSource = Settings.Default.SQLServerNames;
     cbxSQLServerName.Text       = Settings.Default.SQLServerName;
 }
Пример #3
0
 public ConfigPuller(SNGDataSet ds, int ConfigurationSetID)
 {
     InitializeComponent();
     this.SNGDataSet = ds;
     _workInProgress = new WorkInProgress(_workInProgressCaption, _workInProgressText);
     SetControlBackGround(this);
     _configurationSetID = ConfigurationSetID;
 }
Пример #4
0
		public override void Reset ()
		{
			base.Reset ();
			
			Animated = true;
			MinValue = 0;
			MaxValue = 1;
			WorkInProgress = null;
		}		
Пример #5
0
 public PGTInterface()
 {
     _workInProgress         = new WorkInProgress();
     _workInProgress.Caption = "Please wait";
     _workInProgress.Text    = "Loading module...";
     if (!Properties.Settings.Default.HasSettingsUpgraded)
     {
         Properties.Settings.Default.Upgrade();
         Properties.Settings.Default.HasSettingsUpgraded = true;
         Properties.Settings.Default.Save();
     }
 }
Пример #6
0
		/// <summary>
		/// Copies the state from another instance
		/// </summary>
		/// <param name="other">The GUIItem to copy from</param>
		public override void CopyFrom (GUIItem other)
		{
			base.CopyFrom (other);
			
			WorkItemProgressBar bar = other as WorkItemProgressBar;
			if (bar == null)
			{
				return;
			}
			
			WorkInProgress = bar.WorkInProgress; 
		}
Пример #7
0
        public ActivityStateMachine(Activity activity)
        {
            _activity = activity;
            _machine  = new StateMachine <ActivityState, Trigger>(() => _activity._state, s => _activity._state = s);

            _machine.OnTransitioned(
                (StateMachine <ActivityState, Trigger> .Transition transition)
                => Print($" New Status: {_activity._state}"));

            Created.SetupState(this);
            Todo.SetupState(this);
            WorkInProgress.SetupState(this);
            CodeReview.SetupState(this);
            Revision.SetupState(this);
            DeployStaging.SetupState(this);
            BusinessValidation.SetupState(this);
            DeployProduction.SetupState(this);
        }
        private void InitializeWorkInProgress(WorkInProgress progress)
        {
            originalAutoDetectString = bnDetectCoworkers.Text;

            folder.Enabled           = false;
            btnBrowse.Enabled        = false;
            bnCreateTeamRule.Enabled = false;

            if (progress == WorkInProgress.AutoDetectCoworkers)
            {
                tbCoworkers.Text       = string.Empty;
                bnDetectCoworkers.Text = "Cancel";

                pictureBoxLoading.Visible = true;
                pictureBoxLoading.Enabled = true;
                labelProgress.Visible     = true;
                labelProgress.Text        = string.Empty;
            }
        }
        protected override void DoAction(HttpResponseBase response, HttpContextBase context)
        {
            string sContentId = context.Request.Params["content_id"];
            string sJson;
            List <WorkInProgress> listWorkInProgress = new List <WorkInProgress>();

            foreach (Tuple <DateTime, string> workInProgress in
                     _creekController.GetWorkInProgressList(sContentId))
            {
                WorkInProgress oWIP = new WorkInProgress()
                {
                    Time       = workInProgress.Item1.ToLocalTime().ToString(),
                    Percentage = workInProgress.Item2
                };
                listWorkInProgress.Add(oWIP);
            }
            sJson = JsonConvert.SerializeObject(listWorkInProgress);
            response.ContentType = "application/json";
            response.Write(sJson);
        }
Пример #10
0
        /// <summary>
        ///     Show a modal window with a progress bar that simulates doing some work.
        /// </summary>
        /// <param name="work">The delegate to run as a background operation</param>
        public static void ShowModal(Action work)
        {
            var splash = new WorkInProgress
            {
                Owner = System.Windows.Application.Current.Windows.OfType <MetroWindow>()
                        .SingleOrDefault(x => x.IsActive),
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            splash.Loaded += (_, args) =>
            {
                var worker = new BackgroundWorker();

                worker.DoWork += (s, workerArgs) => work();

                worker.RunWorkerCompleted +=
                    (s, workerArgs) => splash.Close();

                worker.RunWorkerAsync();
            };

            splash.ShowDialog();
        }
Пример #11
0
 /// <summary>
 /// Gets the percentage of work complete for a given work item
 /// at the current time
 /// </summary>
 /// <param name="workItem"></param>
 /// <returns></returns>
 public double GetPercentageCompleteForWorkItem(WorkInProgress workItem)
 {
     BuildableItem buildableItem = BuildableItems[workItem.Quantity.ItemCode];
     BuildableItemStat stat = buildableItem.Stats[workItem.Quantity.Level];
     double secondsToGo = workItem.FinishTime.Subtract(DateTime.UtcNow).TotalSeconds;
     double ratio = 1 - (secondsToGo / (double)stat.BuildSeconds);
     return Math.Min(1, Math.Max(ratio, 0));
 }
Пример #12
0
 /// <summary>
 /// Adds or removes an item to or from a player when work is completed
 /// </summary>
 /// <param name="player"></param>
 /// <param name="item"></param>
 public void AdjustInventory(GamePlayer player, WorkInProgress item)
 {
     WorkItem workItem = BuildableItems[item.Quantity.ItemCode] as WorkItem;
     if (workItem != null)
     {
         RemoveItem(player, item.Location, item.Quantity);
     }
     else
     {
         AddItem(player, item.Location, item.Quantity);
     }            
 }
Пример #13
0
        /// <summary>
        /// Starts a player doing delayed work if all conditions pass.
        /// </summary>
        /// <param name="player"></param>
        /// <param name="code"></param>
        public WorkInProgress StartWork(GamePlayer player, int location, int level, BuildableItemEnum itemCode)
        {
            bool canDoWork = TryBuildItem(player, location, level, itemCode);

            if (!canDoWork)
            {
                return null;
            }

            DeductResources(player, location, level, itemCode);

            BuildableItem buildableItem = BuildableItems[itemCode];
            BuildableItemStat stat = buildableItem.Stats[level];

            WorkInProgress wip = new WorkInProgress
            {
                Quantity = new ItemQuantity
                {
                    ItemCode = itemCode,
                    UnStoredQuantity = GetProductionQuantityForItem(player, location, level, itemCode)
                },
                FinishTime = DateTime.UtcNow.AddSeconds(stat.BuildSeconds)
            };

            player.WorkInProgress.Add(wip);

            if (WorkStarted != null)
            {
                OnWorkStarted(new GamePlayerLogicEventArgs(player, wip));
            }

            WorkItem workItem = buildableItem as WorkItem;
            if (workItem != null)
            {
                FinishWork(player, DateTime.UtcNow);
            }

            player.StateChanged = true;

            return wip;
        }
 /// <summary>
 /// Creates a new instance of the GamePlayerLogicEventArgs class
 /// </summary>
 public GamePlayerLogicEventArgs(GamePlayer player, WorkInProgress item)
 {
     Player = player;
     WorkItem = item;
 }
        /// <summary>
        /// Checks database and creates it if missing and also creates required DB objects
        /// </summary>
        /// <param name="ServerName">The SQL Server name to connect to</param>
        /// <param name="DatabaseName">The name of the database to check or create</param>
        /// <param name="intSecurity">If integrated security to be used for connection</param>
        /// <param name="sqlUserName">SQL Username for connection</param>
        /// <param name="sqlPassword">SQL Password for connection</param>
        /// <param name="animation">A Backgoundworker to stop before displaying any dialog boxes. Optional</param>
        /// <returns></returns>
        public static bool RegisterDatabase(string ServerName, string DatabaseName, bool intSecurity, string sqlUserName, string sqlPassword, WorkInProgress animation = null)
        {
            bool runResult        = true;
            bool DBExists         = false;
            bool DBCreated        = false;
            bool DBObjectsCreated = false;

            try
            {
                #region Create Database if not exists
                string MasterConnectionString = intSecurity ? string.Format("Data Source={0};Initial Catalog=master;Integrated Security=True", ServerName) :
                                                string.Format("Data Source={0};Initial Catalog=master;Persist Security Info=True;User ID={1};Password={2}", ServerName, sqlUserName, sqlPassword);
                DebugEx.WriteLine(string.Format("Connecting to master db using : {0}", MasterConnectionString), DebugLevel.Informational);
                using (SqlConnection conn = new SqlConnection(MasterConnectionString))
                {
                    try
                    {
                        conn.Open();
                        #region Test database existence
                        try
                        {
                            DebugEx.WriteLine(string.Format("Checking database : {0}", DatabaseName), DebugLevel.Informational);
                            SqlCommand scmd = conn.CreateCommand();
                            scmd.CommandText = string.Format("SELECT name FROM master.sys.databases WHERE name = N'{0}'", DatabaseName);
                            object o = new object();
                            o        = scmd.ExecuteScalar();
                            DBExists = o != null;
                            if (!DBExists)
                            {
                                DebugEx.WriteLine("database doesn't exist", DebugLevel.Informational);
                                animation?.Cancel();
                                runResult = MessageBox.Show(string.Format("Database {0} does not exists. Do you want to create it now?", DatabaseName), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes;
                                if (runResult)
                                {
                                    animation?.Run();
                                }
                            }
                            else
                            {
                                DebugEx.WriteLine("database exists", DebugLevel.Informational);
                            }
                        }
                        catch (SqlException Ex)
                        {
                            DebugEx.WriteLine("Unexpected error 1");
                            animation?.Cancel();
                            MessageBox.Show(string.Format("Unexpected error while checking database {0} : {1} ", DatabaseName, Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            runResult = false;
                        }
                        #endregion
                        if (runResult & !DBExists)
                        {
                            #region Create database
                            try
                            {
                                DebugEx.WriteLine(string.Format("Creating database : {0}", DatabaseName), DebugLevel.Informational);
                                SqlCommand scmd = conn.CreateCommand();
                                scmd.CommandText = "CREATE DATABASE " + DatabaseName;
                                scmd.ExecuteNonQuery();
                                scmd.CommandText = string.Format("ALTER DATABASE {0} SET AUTO_SHRINK ON", DatabaseName);
                                scmd.ExecuteNonQuery();
                                DBCreated = true;
                                DebugEx.WriteLine("database created successfully", DebugLevel.Informational);
                            }
                            catch (SqlException Ex)
                            {
                                if (((SqlException)Ex).Number == 1801)
                                {
                                    DebugEx.WriteLine("database already exists", DebugLevel.Informational);
                                }
                                else
                                {
                                    DebugEx.WriteLine("Unexpected error 2");
                                    animation?.Cancel();
                                    MessageBox.Show(string.Format("Unexpected error while creating database {0} : {1} ", DatabaseName, Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    runResult = false;
                                }
                            }
                            #endregion
                        }
                    }
                    catch (SqlException Ex)
                    {
                        DebugEx.WriteLine("Unexpected error 3");
                        animation?.Cancel();
                        MessageBox.Show(string.Format("Unexpected error while opening connection : {0} ", Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        runResult = false;
                    }
                }
                #endregion

                if (runResult)
                {
                    #region Connect to database and create database objects if missing

                    string InstallerConnectionString = intSecurity ? string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True", ServerName, DatabaseName) :
                                                       string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={1};Password={2}", ServerName, DatabaseName, sqlUserName, sqlPassword);
                    DebugEx.WriteLine(string.Format("Connecting using : {0}", InstallerConnectionString), DebugLevel.Informational);
                    using (SqlConnection conn = new SqlConnection(InstallerConnectionString))
                    {
                        conn.Open();
                        SqlCommand scmd;
                        try
                        {
                            try
                            {
                                #region Check if require objects exist
                                DebugEx.WriteLine("Checking database objects", DebugLevel.Informational);
                                bool RequiredObjectsExist = false;
                                // This is to try whether required database objects exist or not
                                scmd = new SqlCommand("SELECT COUNT (*) FROM CONFIGTARGETS", conn);
                                try
                                {
                                    object o = new object();
                                    o = scmd.ExecuteScalar();
                                    RequiredObjectsExist = true;
                                }
                                catch (SqlException Ex)
                                {
                                    // Error number 208 is normal, meaning that there is no Params table yet
                                    if (((SqlException)Ex).Number == 208)
                                    {
                                        DebugEx.WriteLine("Error 208 : there is no CONFIGTARGETS table yet");
                                    }
                                    else
                                    {
                                        // other exceptions are unexpected and unhandled errors
                                        animation?.Cancel();
                                        MessageBox.Show(string.Format("Unexpected error while creating database {0} : {1} ", DatabaseName, Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        runResult = false;
                                        throw Ex;
                                    }
                                }
                                #endregion

                                #region Run DDL script if required objects do not exist
                                if (!RequiredObjectsExist)
                                {
                                    // this is a new empty database
                                    DebugEx.WriteLine("this is a new empty database, running DDL script", DebugLevel.Informational);
                                    try
                                    {
                                        string SqlScript = Resource1.CreateConfigManagerObjects_20151007_v1;
                                        SqlScript = SqlScript.Replace("GO", "^");
                                        string[] SqlCommands = SqlScript.Split("^".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                        foreach (string command in SqlCommands)
                                        {
                                            DebugEx.WriteLine(scmd.CommandText);
                                            scmd = new SqlCommand(command, conn);
                                            scmd.ExecuteNonQuery();
                                        }
                                        DBObjectsCreated = true;
                                        DebugEx.WriteLine("DB objects created sucessfully", DebugLevel.Informational);
                                    }
                                    catch (Exception Ex)
                                    {
                                        animation?.Cancel();
                                        MessageBox.Show(string.Format("Unexpected error while creating database objects : {0} ", Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        runResult = false;
                                    }
                                }
                                #endregion
                            }
                            finally
                            {
                                conn.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Sorry, I am unable to register database. Please view debug logs for more details.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            runResult = false;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                animation?.Cancel();
                MessageBox.Show("Sorry, I am unable to register database. Please view debug logs for more details. Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                runResult = false;
            }
            if (DBCreated | DBObjectsCreated)
            {
                animation?.Cancel();
                string s = DBCreated ? "Database created sucessfully." : "";
                if (DBObjectsCreated)
                {
                    s += " Required database objects created sucessfully.";
                }
                MessageBox.Show(s, "SQL Operation success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return(runResult);
        }