Beispiel #1
0
        public bool Matches(MethodInfo Method, Step Step)
        {
            this.Method = Method;
            this.Step = Step;

            return MatchesName && MatchesArgs;
        }
 private static void AssertStep(Step step, string stepTitle, ExecutionOrder order, bool asserts = false, bool shouldReport = true)
 {
     Assert.That(step.Title.Trim(), Is.EqualTo(stepTitle));
     Assert.That(step.Asserts, Is.EqualTo(asserts));
     Assert.That(step.ExecutionOrder, Is.EqualTo(order));
     Assert.That(step.ShouldReport, Is.EqualTo(shouldReport));
 }
        public StepMatch GetMatch(Step step, ActionStepMethod stepMethod)
        {
            if (step.StepType != stepMethod.StepType) return StepMatch.NoMatch(step);

            var stepTokens = Tokenize(step.Text);
            var methodTokens = Tokenize(stepMethod.Text);

            if (stepTokens.Length != methodTokens.Length) return StepMatch.NoMatch(step);

            var tokens = new List<Token>();

            for (var index = 0; index < stepTokens.Length; index++)
            {
                var tok1 = stepTokens[index];
                var tok2 = methodTokens[index];

                if (tok2 is VariableToken)
                {
                    ((VariableToken) tok2).Value = tok1.Text;
                    tokens.Add(tok2);
                    continue;
                }

                if (tok1.Text != tok2.Text)
                {
                    return StepMatch.NoMatch(step);
                }

                tokens.Add(tok1);
            }

            return new StepMatch(step) {IsMatch = true, Tokens = tokens};
        }
        public void ThenSingleScenarioWithStepsAddedSuccessfully()
        {
            var excelScenarioFormatter = Container.Resolve<ExcelScenarioFormatter>();
            var scenario = new Scenario
                               {
                                   Name = "Test Feature",
                                   Description =
                                       "In order to test this feature,\nAs a developer\nI want to test this feature"
                               };
            var given = new Step {NativeKeyword = "Given", Name = "a precondition"};
            var when = new Step {NativeKeyword = "When", Name = "an event occurs"};
            var then = new Step {NativeKeyword = "Then", Name = "a postcondition"};
            scenario.Steps = new List<Step>(new[] {given, when, then});

            using (var workbook = new XLWorkbook())
            {
                IXLWorksheet worksheet = workbook.AddWorksheet("SHEET1");
                int row = 3;
                excelScenarioFormatter.Format(worksheet, scenario, ref row);

                worksheet.Cell("B3").Value.ShouldEqual(scenario.Name);
                worksheet.Cell("C4").Value.ShouldEqual(scenario.Description);
                row.ShouldEqual(8);
            }
        }
    void Start()
    {
        toggles = GameObject.Find("TowerChoice").GetComponentsInChildren<Toggle>();
        choiceTowers = new Dictionary<TglTower, Tower>();
        retrieveChoiceTowers();
        DisableChoices();

        title = GameObject.Find("txtTitle");
		title.SetActive(false);
        smallTitle = GameObject.Find("txtSmallTitle");
        tiltShift = GameObject.Find("Main Camera").GetComponent<UnityStandardAssets.ImageEffects.TiltShift>();
        spawnLaps = 2;
        spawner = GameObject.Find("Spawn").GetComponentInChildren<Spawn>();
		step = Step.STARTING;
        shakeAmount = 0.1F;
        shakeTimer = 1F;

        HideTowerDetails();
        
        btnNextWave.onClick.AddListener(EndConstructionTime);
        nextWave = GameObject.Find("btnNextWave");
        nextWave.SetActive(false);

		animator = ((Animator)GetComponent<Animator>());
		topCam = (Camera) topCamObject.GetComponent<Camera> ();

		animator.Play("CameraStartAnim", -1, 0F);
		startTimer = Time.time;
    }
Beispiel #6
0
        public void EnsureComplete_should_throw_if_minimum_count_not_met()
        {
            var step = new Step(Times.Once());

            Assert.Throws<SequenceException>(() => step.EnsureComplete(""));
            Assert.That(step.Complete, Is.False);
        }
Beispiel #7
0
        public void Multiline_strings_are_formatted_as_list_items_with_pre_elements_formatted_as_code_internal()
        {
            var step = new Step
                           {
                               Keyword = Keyword.Given,
                               NativeKeyword = "Given ",
                               Name = "a simple step",
                               TableArgument = null,
                               DocStringArgument = "this is a\nmultiline table\nargument",
                           };

            var formatter = Container.Resolve<HtmlStepFormatter>();
            XElement actual = formatter.Format(step);

            XNamespace xmlns = XNamespace.Get("http://www.w3.org/1999/xhtml");
            var expected = new XElement(xmlns + "li",
                                        new XAttribute("class", "step"),
                                        new XElement(xmlns + "span", new XAttribute("class", "keyword"),
                                                     EXPECTED_GIVEN_HTML),
                                        new XText("a simple step"),
                                        new XElement(xmlns + "div",
                                                     new XAttribute("class", "pre"),
                                                     new XElement(xmlns + "pre",
                                                                  new XElement(xmlns + "code",
                                                                               new XAttribute("class", "no-highlight"),
                                                                               new XText(
                                                                                   "this is a\nmultiline table\nargument")
                                                                      )
                                                         )
                                            )
                );

            expected.ShouldDeepEquals(actual);
        }
        protected override void ExecuteAction(Context context, Step step)
        {
            string first = step.GetParameterValue<string>("String", 1);
            string second = step.GetParameterValue<string>("String", 2);

            ServiceAgent.Currency from = (ServiceAgent.Currency)Enum.Parse(typeof(ServiceAgent.Currency), first, true);
            ServiceAgent.Currency to = (ServiceAgent.Currency)Enum.Parse(typeof(ServiceAgent.Currency), second, true);

            ConfigurationChannelFactory<ServiceAgent.CurrencyConvertorSoap> channelFactory = null;
            double rate;
            try
            {
                channelFactory = new ConfigurationChannelFactory<ServiceAgent.CurrencyConvertorSoap>("CurrencyConvertorSoap", conf.Configuration, null);
                var client = channelFactory.CreateChannel();
                rate = client.ConversionRate(from, to);
            }
            catch (Exception)
            {
                rate = double.NaN;
            }
            finally
            {
                if (channelFactory != null)
                    channelFactory.Close();
            }

            context.AddPublishedItem("Number", step.Id, rate);
        }
Beispiel #9
0
        public IReaderMode Read(int indention, string text)
        {
            if (!text.IsTableLine()) return null;

            var values = text.ToTableValues();
            if (_cells == null)
            {
                _cells = values;
            }
            else
            {
                if (values.Length != _cells.Length)
                    throw new InvalidOperationException(
                        $"Wrong number of cells. Expected {_cells.Join(", ")}, but got {values.Length} data values in \n\"{text}\"");

                var step = new Step("row");
                for (var i = 0; i < _cells.Length; i++)
                {
                    var key = _cells[i];
                    step.Values.Add(key, values[i]);

                    // This makes the integration tests happier
                    if (key == "id")
                    {
                        step.id = values[i];
                    }
                }

                _section.Children.Add(step);
            }

            return this;
        }
 protected override void ExecuteAction(Context context, Step step)
 {
     Action<IDataReader> action = DisplayRow;
     context.AddPublishedItem("Row Action", step.Id, action);
     context.AddPublishedItem("String", step.Id, queryName);
     context.AddPublishedItem("Configuration Info", step.Id, this);
 }
        void ReportOnStep(Scenario scenario, Step step)
        {
            var message =
                string.Format
                    ("\t{0}  [{1}] ",
                    PrefixWithSpaceIfRequired(step).PadRight(_longestStepSentence + 5),
                    Configurator.Scanners.Humanize(step.Result.ToString()));

            // if all the steps have passed, there is no reason to make noise
            if (scenario.Result == Result.Passed)
                message = "\t" + PrefixWithSpaceIfRequired(step);

            if (step.Exception != null)
            {
                _exceptions.Add(step.Exception);

                var exceptionReference = string.Format("[Details at {0} below]", _exceptions.Count);
                if (!string.IsNullOrEmpty(step.Exception.Message))
                    message += string.Format("[{0}] {1}", FlattenExceptionMessage(step.Exception.Message), exceptionReference);
                else
                    message += string.Format("{0}", exceptionReference);
            }

            if (step.Result == Result.Inconclusive || step.Result == Result.NotImplemented)
                Console.ForegroundColor = ConsoleColor.Yellow;
            else if (step.Result == Result.Failed)
                Console.ForegroundColor = ConsoleColor.Red;
            else if (step.Result == Result.NotExecuted)
                Console.ForegroundColor = ConsoleColor.Gray;

            Console.WriteLine(message);
            Console.ForegroundColor = ConsoleColor.White;
        }
 /// <summary>
 /// Sets next model's step
 /// </summary>
 /// <param name="step"></param>
 protected void SetNextStep(Step step)
 {
     if (_initialStep == null)
         _initialStep = step;
     Steps.Clear();
     Steps.Add(0, step);
 }
        public override void Apply(Step step)
        {
            var databaseExists = DatabaseExists();

            foreach (var script in step.Scripts)
            {
                if (!script.HasContent()) continue;

                try
                {
                    if (databaseExists)
                    {
                        var executeScriptResult = ExecuteScript(script);
                        ExamineForScriptError(executeScriptResult);
                    }
                    else
                    {
                        var executeScriptOnMasterResult = ExecuteScriptOnMaster(script);
                        ExamineForScriptError(executeScriptOnMasterResult);
                    }
                }
                catch (Exception scriptException)
                {
                    RaiseOnScriptFailure(script, scriptException);
                }

                RaiseOnScriptSuccess(script);
            }
        }
Beispiel #14
0
        void Start()
        {
            mDownloader = new AssetDownloader();
            mPreStep = Step.None;
            mStep = Step.HashmapHash;

            // 读取本地的配置列表
            string localFiles = UrlUtil.Combine(Settings.UNITY_RAW_FOLDER, "files");
            if (File.Exists(localFiles))
            {
                string[] array = File.ReadAllLines(localFiles);
                mLocalCfgMap = new Dictionary<string, AssetCfg>(array.Length);
                for (int i = 0; i < array.Length; i++)
                {
                    string line = array[i];
                    if (string.IsNullOrEmpty(line))
                        continue;
                    string[] cells = line.Split('|');
                    if (cells == null || cells.Length == 0)
                        continue;
                    AssetCfg cfg = new AssetCfg(cells);
                    mLocalCfgMap.Add(cfg.key, cfg);
                }
            }
            else
            {
                mLocalCfgMap = new Dictionary<string, AssetCfg>();
            }
        }
        public Result ExecuteStep(Step step)
        {
            try
            {
                step.Execute(_scenario.TestObject);
                step.Result = Result.Passed;
            }
            catch (Exception ex)
            {
                // ToDo: more thought should be put into this. Is it safe to get the exception?
                var exception = ex;
                if (exception is TargetInvocationException)
                {
                    exception = ex.InnerException ?? ex;
                }

                if (exception is NotImplementedException)
                {
                    step.Result = Result.NotImplemented;
                    step.Exception = exception;
                }
                else if (IsInconclusive(exception))
                {
                    step.Result = Result.Inconclusive;
                    step.Exception = exception;
                }
                else
                {
                    step.Exception = exception;
                    step.Result = Result.Failed;
                }
            }

            return step.Result;
        }
 private static void AssertStep(Step step, string stepTitle, ExecutionOrder order, bool asserts = false, bool shouldReport = true)
 {
     step.Title.Trim().ShouldBe(stepTitle);
     step.Asserts.ShouldBe(asserts);
     step.ExecutionOrder.ShouldBe(order);
     step.ShouldReport.ShouldBe(shouldReport);
 }
Beispiel #17
0
 public Waiter(Step step, Action completed = null, int timesToComplete = 1)
 {
     _time = new WaiterTime();
     _step = step;
     _timesToComplete = timesToComplete;
     _completed = completed;
 }
        public static void WriteStep(this XmlElement parent, Step step)
        {
            var element = parent.AddElement(step.Key);
            step.Values.Each(pair => element.SetAttribute(pair.Key, pair.Value));

            step.Collections.Each(element.WriteSection);
        }
Beispiel #19
0
 /// <summary>
 /// Creates instance of the <see cref="Action"></see> class with properties initialized with specified parameters.
 /// </summary>
 /// <param name="returnType">The return type of the action.</param>
 /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param>
 /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param>
 /// <param name="condition">The launch condition for the <see cref="Action"/>.</param>
 protected Action(Return returnType, When when, Step step, Condition condition)
 {
     Return = returnType;
     Step = step;
     When = when;
     Condition = condition;
 }
Beispiel #20
0
 public Move(Step step, Board board)
 {
     _board = board;
     Step = new Step(step);
     oldFrom = _board[(step.FromX << 3) + step.FromY];
     oldTo = _board[(step.ToX << 3) + step.ToY];
 }
Beispiel #21
0
 static CodeFunction CodeFunctionForUnimplemented(this Project project, Step Step)
 {
     return project.Classes()
         .Where(x => x.Name == Step.Feature.Name)
         .SelectMany(x => x.Functions())
         .FirstOrDefault(x => x.EqualsTo(Step));
 }
Beispiel #22
0
 public static StepMatch NoMatch(Step step)
 {
     return new StepMatch(step)
                {
                    IsMatch = false,
                };
 }
        private void CorrectCorrection_Button_Click(object sender, RoutedEventArgs e)
        {
            lastStep = Step.CorrectCorrection;
            correctCorrection += 1;
            this.CorrectCorrectionTextBlock.Text = correctCorrection.ToString();

            this.ShowNext();
        }
Beispiel #24
0
        public override IStep CreateNewStep()
        {
            var step = new Step(Name);
            step.Description = Description;
            LeafFor(step);

            return step;
        }
 public override void Apply(Step step)
 {
     foreach (var script in step.Scripts)
     {
         if (!script.HasContent()) continue;
         ExecuteScript(script);
     }
 }
Beispiel #26
0
        public void EnsureComplete_should_not_throw_if_minimum_and_maximum_count_met()
        {
            var step = new Step(Times.Once());
            step.CountCall();

            step.EnsureComplete("");
            Assert.That(step.Complete, Is.True);
        }
 protected override void ExecuteAction(Context context, Step step)
 {
     string name = step.GetParameterValue<string>("String");
     Logger.DebugFormat("connection string name = {0}", name);
     string returnValue = conf.ConnectionString(name);
     Logger.DebugFormat("connection string retrieved = {0}", returnValue);
     context.AddPublishedItem(new Public("Connection String"), step.Id, returnValue);
 }
Beispiel #28
0
 protected void AllOpcodes(Step assert) {
   foreach (byte opcode in opcodes) {
     Instruction instruction = cpu.Apply(opcode);
     Operand[] operands = instruction.Operands;
     instruction.Do();
     assert(operands);
   }
 }
 private NodeV1(NodeV1 parentNode, Step previousStep, BoardState state, int distanceFromInitialNode, int estimatedDistanceToGoal)
 {
     this.ParentNode = parentNode;
     this.PreviousStep = previousStep;
     this.State = state;
     this.distanceFromInitialNode = distanceFromInitialNode;
     this.Cost = distanceFromInitialNode + estimatedDistanceToGoal;
 }
Beispiel #30
0
        public Pitch(Step step, string octave)
        {
            if (octave == null)
                throw new ArgumentNullException("octave");

            this.Step = step;
            this.Octave = octave;
        }
Beispiel #31
0
        private IEnumerator Checking()
        {
            if (!Directory.Exists(_savePath))
            {
                Directory.CreateDirectory(_savePath);
            }

            if (_step == Step.Wait)
            {
                enableVFS = true;
#if UNITY_IPHONE
                enableVFS = false;
#endif
                _step = Step.Copy;
            }

            if (_step == Step.Copy)
            {
                yield return(RequestCopy());
            }

            if (_step == Step.Coping)
            {
                var path     = _savePath + Versions.Filename + ".tmp";
                var versions = Versions.LoadVersions(path);
                var basePath = GetBasePath();
                yield return(UpdateCopy(versions, basePath));

                _step = Step.Versions;
            }

            if (_step == Step.Versions)
            {
                yield return(RequestVersions());
            }

            if (_step == Step.Prepared)
            {
                OnMessage("正在检查版本信息...");
                var totalSize = _downloader.size;
                if (totalSize > 0)
                {
                    var tips = string.Format("发现内容更新,总计需要下载 {0} 内容", Downloader.GetDisplaySize(totalSize));
                    var mb   = MessageBox.Show("提示", tips, "下载", "退出");
                    yield return(mb);

                    if (mb.isOk)
                    {
                        _downloader.StartDownload();
                        _step = Step.Download;
                    }
                    else
                    {
                        Quit();
                    }
                }
                else
                {
                    OnComplete();
                }
            }
        }
Beispiel #32
0
 /// <summary>
 /// Foir creating a PopupWindowViewModel we need to pass the step to be used
 /// </summary>
 /// <param name="popupType">Step is a abstract class then the parameter can be any of the child clases like Welcome, Tooltip, Survey....</param>
 public PopupWindowViewModel(Step popupType)
 {
     Step = popupType;
 }
Beispiel #33
0
        public IHttpActionResult PostTrip(TripModel trip)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));

                    throw new WebFaultException <string>("ModelState not valid", HttpStatusCode.BadRequest);
                }
                //Validate
                //Ensure traveler exists
                if (Uow.Repository <Traveler>().Find(trip.TravelerId) == null)
                {
                    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.NotFound, "No traveler found with id " + trip.TravelerId);
                    throw new HttpResponseException(responseMessage);
                }
                //if (trip.TripStartDate < DateTime.UtcNow)
                //{
                //    //Cant add trips in the past
                //    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Trips cannot be created in the past");
                //    throw new HttpResponseException(responseMessage);
                //}
                if (trip.TripEndDate < trip.TripStartDate)
                {
                    //Cant add trips that finish before they start
                    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid trip stop time");
                    throw new HttpResponseException(responseMessage);
                }


                Trip tripEntity = new Trip();
                tripEntity.TravelerId    = trip.TravelerId;
                tripEntity.Origination   = trip.Origination;
                tripEntity.Destination   = trip.Destination;
                tripEntity.TripStartDate = (DateTime)trip.TripStartDate;
                tripEntity.TripEndDate   = (DateTime)trip.TripEndDate;
                tripEntity.MobilityFlag  = (bool)trip.MobilityFlag;
                tripEntity.BicycleFlag   = (bool)trip.BicycleFlag;
                tripEntity.PriorityCode  = trip.PriorityCode;
                //Set creation and modified date to now.
                tripEntity.CreatedDate = tripEntity.ModifiedDate = DateTime.UtcNow;
                List <Step> steps      = new List <Step>();
                int         stepnumber = 1;
                foreach (StepModel sm in trip.Steps)
                {
                    Step stepEntity = new Step();
                    stepEntity.Distance = (decimal)sm.Distance;
                    stepEntity.EndDate  = (DateTime)sm.EndDate;
                    stepEntity.FromName = sm.FromName;
                    if (sm.FromProviderId == 0)
                    {
                        sm.FromProviderId = null;
                    }
                    stepEntity.FromProviderId   = sm.FromProviderId;
                    stepEntity.FromStopCode     = sm.FromStopCode;
                    stepEntity.ModeId           = (int)sm.ModeId;
                    stepEntity.RouteNumber      = sm.RouteNumber;
                    stepEntity.BlockIdentifier  = sm.BlockIdentifier;
                    stepEntity.StartDate        = (DateTime)sm.StartDate;
                    stepEntity.StepNumber       = stepnumber++;
                    stepEntity.ToName           = sm.ToName;
                    stepEntity.EncodedMapString = sm.EncodedMapString;
                    if (sm.ToProviderId == 0)
                    {
                        sm.ToProviderId = null;
                    }
                    stepEntity.ToProviderId = sm.ToProviderId;
                    stepEntity.ToStopCode   = sm.ToStopCode;
                    steps.Add(stepEntity);
                }

                string       tConnectWindow = ConfigurationManager.AppSettings["TConnectWindowInMinutes"];
                int          tConnWindowMin = 0;
                ITripService tripService    = int.TryParse(tConnectWindow, out tConnWindowMin) ? new TripService(tConnWindowMin) : new TripService();
                int          id             = tripService.SaveTrip(tripEntity, steps, Uow);

                Trip        savedtrip  = Uow.Repository <Trip>().Find(id);
                List <Step> savedSteps = Uow.Repository <Step>().Query().Get().Include(s => s.Block).Where(ss => ss.TripId.Equals(id)).ToList();
                TripModel   m          = new TripModel(savedtrip);
                m.Steps = savedSteps.Select(s => new StepModel(s)).ToList();

                return(CreatedAtRoute("DefaultApi", new { id = m.Id }, m)); //same as
            }
            catch (HttpResponseException hrex)                              //rethrow failed validation errors so we don't obliterate the httpstatuscode
            {
                string msg = RecordException(hrex, "TripController.PostTrip");
                throw hrex;
            }
            catch (Exception ex)
            {
                string msg = RecordException(ex, "TripController.PostTrip");
                HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(responseMessage);
            }
        }
Beispiel #34
0
        public void Run()
        {
            var data     = FeedData.FromSeq(new[] { 1, 2, 3, 4, 5 });
            var dataFeed = Feed.CreateRandom("random_feed", data);

            var webSocketConnectionPool =
                ConnectionPoolArgs.Create(
                    name: "web_socket_pool",
                    getConnectionCount: () => 10,
                    openConnection: async(number, token) =>
            {
                await Task.Delay(1_000);
                return(new FakeSocketClient {
                    Id = number
                });
            },
                    closeConnection: (connection, token) =>
            {
                Task.Delay(1_000).Wait();
                return(Task.CompletedTask);
            });

            var step1 = Step.Create("step_1", webSocketConnectionPool, dataFeed, async context =>
            {
                // you can do any logic here: go to http, websocket etc

                // context.CorrelationId - every copy of scenario has correlation id
                // context.Connection    - fake websocket connection taken from pool
                // context.FeedItem      - item taken from data feed
                // context.Logger
                // context.StopScenario("hello_world_scenario", reason = "")
                // context.StopTest(reason = "")

                await Task.Delay(TimeSpan.FromMilliseconds(200));
                return(Response.Ok(42));    // this value will be passed as response for the next step

                // return Response.Ok(42, sizeBytes: 100, latencyMs: 100); - you can specify response size and custom latency
                // return Response.Fail();                                 - in case of fail, the next step will be skipped
            });

            var step2 = Step.Create("step_2", async context =>
            {
                // you can do any logic here: go to http, websocket etc

                await Task.Delay(TimeSpan.FromMilliseconds(200));
                var value = context.GetPreviousStepResponse <int>(); // 42
                return(Response.Ok());
            });

            var scenario = ScenarioBuilder
                           .CreateScenario("hello_world_scenario", new[] { step1, step2 })
                           .WithTestInit(TestInit)
                           .WithTestClean(TestClean)
                           .WithWarmUpDuration(TimeSpan.FromSeconds(10))
                           // .WithOutWarmUp() - disable warm up
                           .WithLoadSimulations(new []
            {
                Simulation.RampConcurrentScenarios(copiesCount: 20, during: TimeSpan.FromSeconds(20)),
                Simulation.KeepConcurrentScenarios(copiesCount: 20, during: TimeSpan.FromMinutes(1)),
                // Simulation.RampScenariosPerSec(copiesCount: 10, during: TimeSpan.FromSeconds(20)),
                // Simulation.InjectScenariosPerSec(copiesCount: 10, during: TimeSpan.FromMinutes(1))
            });

            NBomberRunner
            .RegisterScenarios(new[] { scenario })
            // .LoadTestConfig("test_config.json")   // test config for test settings only
            // .LoadInfraConfig("infra_config.json") // infra config for infra settings only
            .RunInConsole();
        }
Beispiel #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomActionRef" /> class.
 /// </summary>
 /// <param name="id">The id.</param>
 /// <param name="when">The When.</param>
 /// <param name="step">The Step.</param>
 public CustomActionRef(string id, When when, Step step)
     : base(new Id(id))
 {
     When = when;
     Step = step;
 }
Beispiel #36
0
 public async void confirmAmount()
 {
     this.currentStep = Step.CONFIRM_WITHDRAWAL;
     await switchPanel(this.amountPanel, this.confirmPanel);
 }
Beispiel #37
0
 public async void insertCard()
 {
     this.currentStep = Step.INSERT_PIN;
     await switchPanel(this.insertCardPanel, this.pinPanel);
 }
Beispiel #38
0
        public void NextStepEvent(Game game, Step step)
        {
            _game.Log(LogLevel.DEBUG, BlockType.TRIGGER, "Event", $"NextStepEvent - {step}");
            switch (step)
            {
            case Step.BEGIN_FIRST:
                game.Step = step;
                game.BeginFirst();
                break;

            case Step.BEGIN_SHUFFLE:
                game.Step = step;
                game.BeginShuffle();
                break;

            case Step.BEGIN_DRAW:
                game.Step = step;
                game.BeginDraw();
                break;

            case Step.BEGIN_MULLIGAN:
                game.Step = step;
                game.BeginMulligan();
                break;

            case Step.MAIN_BEGIN:
                game.Step = step;
                game.MainBegin();
                break;

            case Step.MAIN_DRAW:
                game.Step = step;
                game.MainDraw();
                break;

            case Step.MAIN_READY:
                game.Step = step;
                game.MainReady();
                break;

            case Step.MAIN_RESOURCE:
                game.Step = step;
                game.MainRessources();
                break;

            case Step.MAIN_START:
                game.Step = step;
                game.MainStart();
                break;

            case Step.MAIN_START_TRIGGERS:
                game.Step = step;
                game.MainStartTriggers();
                break;

            case Step.MAIN_ACTION:
                game.Step = step;
                break;

            case Step.MAIN_COMBAT:
                break;

            case Step.MAIN_CLEANUP:
                game.Step = step;
                game.MainCleanUp();
                break;

            case Step.MAIN_END:
                game.Step = step;
                game.MainEnd();
                break;

            case Step.MAIN_NEXT:
                game.Step = step;
                game.MainNext();
                break;

            case Step.FINAL_WRAPUP:
                game.FinalWrapUp();
                break;

            case Step.FINAL_GAMEOVER:
                game.FinalGameOver();
                break;

            case Step.INVALID:
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(step), step, null);
            }
        }
 public virtual Task DoStep(Step step, ICall call)
 {
     call.Logger.Debug("Next step " + step.GetStepFromConnector(NextStep));
     call.CallState.AddStepToIncomingQueue(step.GetStepFromConnector(NextStep));
     return(Task.CompletedTask);
 }
 public Command(Step currentphase, IMonitoringManager monitoringManager)
 {
     this.CurrentStep       = currentphase;
     this.MonitoringManager = monitoringManager;
 }
Beispiel #41
0
        internal static PackagingResult ExecuteCurrentPhase(Manifest manifest, ExecutionContext executionContext)
        {
            var sysInstall   = manifest.SystemInstall;
            var currentPhase = executionContext.CurrentPhase;

            if (0 == currentPhase - (sysInstall ? 1 : 0))
            {
                SaveInitialPackage(manifest);
            }

            var stepElements = manifest.GetPhase(executionContext.CurrentPhase);

            var stopper = Stopwatch.StartNew();

            Logger.LogMessage("Executing steps");

            Exception phaseException = null;
            var       successful     = false;

            try
            {
                var maxStepId = stepElements.Count;
                for (int i = 0; i < maxStepId; i++)
                {
                    var stepElement = stepElements[i];
                    var step        = Step.Parse(stepElement, i, executionContext);

                    var stepStopper = Stopwatch.StartNew();
                    Logger.LogStep(step, maxStepId);
                    step.Execute(executionContext);
                    stepStopper.Stop();
                    Logger.LogMessage("-------------------------------------------------------------");
                    Logger.LogMessage("Time: " + stepStopper.Elapsed);
                    if (executionContext.Terminated)
                    {
                        LogTermination(executionContext);
                        break;
                    }
                }
                stopper.Stop();
                Logger.LogMessage("=============================================================");
                Logger.LogMessage("All steps were executed.");
                Logger.LogMessage("Aggregated time: " + stopper.Elapsed);
                Logger.LogMessage("Errors: " + Logger.Errors);
                successful = true;
            }
            catch (Exception e)
            {
                phaseException = e;
            }

            var finished = executionContext.Terminated || (executionContext.CurrentPhase == manifest.CountOfPhases - 1);

            if (successful && !finished)
            {
                return new PackagingResult {
                           NeedRestart = true, Successful = true, Errors = Logger.Errors
                }
            }
            ;

            if (executionContext.Terminated && executionContext.TerminationReason == TerminationReason.Warning)
            {
                successful = false;

                phaseException = new PackageTerminatedException(executionContext.TerminationMessage);
            }

            try
            {
                SavePackage(manifest, executionContext, successful, phaseException);
            }
            catch (Exception e)
            {
                if (phaseException != null)
                {
                    Logger.LogException(phaseException);
                }
                throw new PackagingException("Cannot save the package.", e);
            }
            finally
            {
                RepositoryVersionInfo.Reset();

                // we need to shut down messaging, because the line above uses it
                if (!executionContext.Test)
                {
                    DistributedApplication.ClusterChannel.ShutDown();
                }
                else
                {
                    Diagnostics.SnTrace.Test.Write("DistributedApplication.ClusterChannel.ShutDown SKIPPED because it is a test context.");
                }
            }
            if (!successful && !executionContext.Terminated)
            {
                throw new ApplicationException(String.Format(SR.Errors.PhaseFinishedWithError_1, phaseException.Message), phaseException);
            }

            return(new PackagingResult {
                NeedRestart = false, Successful = successful, Terminated = executionContext.Terminated && !successful, Errors = Logger.Errors
            });
        }
 public void SetCurrentStep(Step s)
 {
     FirstCallCurrentStep = true;
     CurrentStep          = s;
 }
Beispiel #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomActionRef" /> class.
 /// </summary>
 /// <param name="id">The id.</param>
 /// <param name="when">The When.</param>
 /// <param name="step">The Step.</param>
 public CustomActionRef(Id id, When when, Step step)
     : base(id)
 {
     When = when;
     Step = step;
 }
Beispiel #44
0
 private bool Equals(ForLoop other)
 {
     return(Body.Equals(other.Body) && Step.Equals(other.Step) && Init.Equals(other.Init) &&
            Equals(Condition, other.Condition));
 }
Beispiel #45
0
        public ActionResult editStep(int id)
        {
            Step step = stepDAO.getStepsInfo(id);

            return(View(step));
        }
Beispiel #46
0
 public void step(Step step)
 {
     throw new NotImplementedException();
 }
Beispiel #47
0
 public IExecutionStep CreatePlan(Step step, FixtureLibrary library)
 {
     return(new FactPlan(new StepValues(step.id), this));
 }
 public OpenDoorAction(Being performer, Step direction) : base(performer)
 {
     this.direction = direction;
 }
        public static void Run()
        {
            var userFeed = Feed.CreateRandom(
                "userFeed",
                FeedData.FromJson <User>("./JsonConfig/Configs/user-feed.json")
                );

            var httpFactory = ClientFactory.Create("http_factory",
                                                   initClient: (number, context) => Task.FromResult(new HttpClient {
                BaseAddress = new Uri(_customSettings.BaseUri)
            }));

            var getUser = Step.Create("get_user", httpFactory, userFeed, async context =>
            {
                var userId = context.FeedItem;
                var url    = $"users?id={userId}";

                var response = await context.Client.GetAsync(url, context.CancellationToken);
                var json     = await response.Content.ReadAsStringAsync();

                // parse JSON
                var users = JsonConvert.DeserializeObject <UserResponse[]>(json);

                return(users?.Length == 1
                    ? Response.Ok(users.First()) // we pass user object response to the next step
                    : Response.Fail("not found user"));
            });

            // this 'getPosts' will be executed only if 'getUser' finished OK.
            var getPosts = Step.Create("get_posts", httpFactory, async context =>
            {
                var user = context.GetPreviousStepResponse <UserResponse>();
                var url  = $"posts?userId={user.Id}";

                var response = await context.Client.GetAsync(url, context.CancellationToken);
                var json     = await response.Content.ReadAsStringAsync();

                // parse JSON
                var posts = JsonConvert.DeserializeObject <PostResponse[]>(json);

                return(posts?.Length > 0
                    ? Response.Ok()
                    : Response.Fail());
            });

            var scenario1 = ScenarioBuilder
                            .CreateScenario("rest_api", getUser, getPosts)
                            .WithInit(ScenarioInit);

            // the following scenario will be ignored since it is not included in target scenarios list of config.json
            var scenario2 = ScenarioBuilder
                            .CreateScenario("ignored", getUser, getPosts);

            // settings for worker plugins and reporting sinks are overriden in infra-config.json
            var pingPlugin = new PingPlugin();

            var customPlugin = new CustomPlugin(new CustomPluginSettings
            {
                Message = "Plugin is configured via constructor"
            });

            var influxDbReportingSink = new InfluxDBSink();

            var customReportingSink = new CustomReportingSink(new CustomReportingSinkSettings
            {
                Message = "Reporting sink is configured via constructor"
            });

            NBomberRunner
            .RegisterScenarios(scenario1, scenario2)
            .WithWorkerPlugins(pingPlugin, customPlugin)
            .WithReportingSinks(influxDbReportingSink, customReportingSink)
            .LoadConfig("./JsonConfig/Configs/config.json")
            .LoadInfraConfig("./JsonConfig/Configs/infra-config.json")
            .Run();
        }
Beispiel #50
0
        private void ProcessLines(string[] lines)
        {
            string               capabilityName              = null;
            string               featureName                 = null;
            string               scenarioName                = null;
            string               asAStatement                = null;
            string               soThatStatement             = null;
            string               youCanStatement             = null;
            StringBuilder        stepInput                   = new StringBuilder();
            StringBuilder        stepExplanation             = new StringBuilder();
            StringBuilder        scenarioExplanation         = new StringBuilder();
            StringBuilder        featureExplanation          = new StringBuilder();
            StringBuilder        capabilityExplanation       = new StringBuilder();
            ScenarioBuilder      scenarioBuilder             = null;
            Step                 currentStep                 = null;
            StepType             currentStepType             = new StepType();
            FeatureStatementType currentFeatureStatementType = new FeatureStatementType();
            LineType             previousLineType            = new LineType();
            LineType             currentLineType             = new LineType();
            int capabilityFeatureCount = 0;
            int featureScenarioCount   = 0;

            for (int x = 0; x < lines.Length; x++)            //First 2 lines are test run name and blank.
            {
                try {
                    previousLineType = currentLineType;
                    var    currentLine  = lines[x];
                    string previousLine = null;
                    if (x > 0)
                    {
                        previousLine = lines[x - 1];
                    }
                    currentLineType = this.GetLineType(currentLine, previousLineType, x + 1);
                    var currentLineContent = this.GetLineContent(currentLine, currentLineType, x + 1);
                    switch (currentLineType)
                    {
                    case LineType.Capability:
                        if (scenarioName != null)
                        {
                            scenarioBuilder = this.AddScenario(
                                capabilityName,
                                featureName,
                                scenarioName,
                                asAStatement,
                                soThatStatement,
                                youCanStatement,
                                scenarioExplanation.ToString(),
                                TextFormat.markdown,
                                featureExplanation.ToString(),
                                TextFormat.markdown);
                            scenarioName = null;
                            scenarioExplanation.Clear();
                            featureExplanation.Clear();
                        }
                        if (currentStep != null)
                        {
                            this.AddStep(scenarioBuilder, currentStepType, currentStep, stepInput, stepExplanation);
                            currentStep = null;
                        }
                        if (capabilityName != null && capabilityFeatureCount == 0)
                        {
                            throw new TextImportException($"Line {x+1}: Capability defined with no features.");
                        }
                        capabilityFeatureCount = 0;
                        capabilityName         = currentLineContent;
                        break;

                    case LineType.CapabilityExplanation:
                        capabilityExplanation.AppendLine(currentLineContent);
                        break;

                    case LineType.FeatureExplanation:
                        featureExplanation.AppendLine(currentLineContent);
                        break;

                    case LineType.ScenarioExplanation:
                        scenarioExplanation.AppendLine(currentLineContent);
                        break;

                    case LineType.StepExplanation:
                        stepExplanation.AppendLine(currentLineContent);
                        break;

                    case LineType.FeatureStatement:
                        currentFeatureStatementType = this.GetFeatureStatementType(currentLineContent);
                        var featureStatement = this.GetFeatureStatement(currentLineContent, currentFeatureStatementType);
                        switch (currentFeatureStatementType)
                        {
                        case FeatureStatementType.AsA:
                            asAStatement = this.GetFeatureStatement(currentLineContent, currentFeatureStatementType);
                            break;

                        case FeatureStatementType.SoThat:
                            soThatStatement = this.GetFeatureStatement(currentLineContent, currentFeatureStatementType);
                            break;

                        case FeatureStatementType.YouCan:
                            youCanStatement = this.GetFeatureStatement(currentLineContent, currentFeatureStatementType);
                            break;
                        }
                        break;

                    case LineType.Feature:
                        capabilityFeatureCount++;
                        if (scenarioName != null)
                        {
                            if (featureScenarioCount == 0)
                            {
                                throw new TextImportException($"Line {x}: Feature defined with no scenarios.");
                            }
                            scenarioBuilder = this.AddScenario(
                                capabilityName,
                                featureName,
                                scenarioName,
                                asAStatement,
                                soThatStatement,
                                youCanStatement,
                                scenarioExplanation.ToString(),
                                TextFormat.markdown,
                                featureExplanation.ToString(),
                                TextFormat.markdown);
                            scenarioName = null;
                            scenarioExplanation.Clear();
                            featureExplanation.Clear();
                        }
                        if (currentStep != null)
                        {
                            this.AddStep(scenarioBuilder, currentStepType, currentStep, stepInput, stepExplanation);
                            currentStep = null;
                        }
                        this.scenarioCount   = 0;
                        featureScenarioCount = 0;
                        featureName          = currentLineContent;
                        this.featureNames.Add($"{rootNamespace}.{capabilityName.ConvertCapabilityNameToNamespace()}.{featureName.ConvertFeatureNameToClassName()}");
                        break;

                    case LineType.Scenario:
                        featureScenarioCount++;
                        if (scenarioName != null)
                        {
                            scenarioBuilder = this.AddScenario(
                                capabilityName,
                                featureName,
                                scenarioName,
                                asAStatement,
                                soThatStatement,
                                youCanStatement,
                                scenarioExplanation.ToString(),
                                TextFormat.markdown,
                                featureExplanation.ToString(),
                                TextFormat.markdown);
                            scenarioName = null;
                            scenarioExplanation.Clear();
                            featureExplanation.Clear();
                        }
                        if (currentStep != null)
                        {
                            this.AddStep(scenarioBuilder, currentStepType, currentStep, stepInput, stepExplanation);
                            currentStep = null;
                        }
                        scenarioName = currentLineContent;
                        break;

                    case LineType.Step:
                        if (scenarioName != null)
                        {
                            scenarioBuilder = this.AddScenario(
                                capabilityName,
                                featureName,
                                scenarioName,
                                asAStatement,
                                soThatStatement,
                                youCanStatement,
                                scenarioExplanation.ToString(),
                                TextFormat.markdown,
                                featureExplanation.ToString(),
                                TextFormat.markdown);
                            scenarioName = null;
                            scenarioExplanation.Clear();
                            featureExplanation.Clear();
                        }
                        if (currentStep != null)
                        {
                            this.AddStep(scenarioBuilder, currentStepType, currentStep, stepInput, stepExplanation);
                            currentStep = null;
                        }
                        currentStepType = this.GetStepType(currentLineContent, x + 1);
                        var           stepName   = this.GetStepName(currentLineContent, currentStepType);
                        var           stepReason = currentLineContent.ExtractReason();
                        Action <Step> action     = (s) => {};
                        if (stepReason == "Failed")
                        {
                            action = (s) => {
                                throw new Exception("Generated Failure");
                            };
                        }
                        currentStep = xB.CreateStep(stepName, action);
                        if (stepReason == "Failed")
                        {
                            currentStep.Outcome = Outcome.Failed;
                        }
                        break;

                    case LineType.StepInput:
                        stepInput.AppendLine(currentLineContent);
                        break;
                    }
                } catch (TextImportException) {
                    throw;
                } catch (Exception) {
                    throw new TextImportException(x + 1, lines[x], Enum.GetName(typeof(LineType), previousLineType));
                }
            }
            this.ValidateFollowingLine(LineType.LastLine, currentLineType, lines.Length, "");
            if (scenarioName != null)
            {
                scenarioBuilder = this.AddScenario(
                    capabilityName,
                    featureName,
                    scenarioName,
                    asAStatement,
                    soThatStatement,
                    youCanStatement,
                    scenarioExplanation.ToString(),
                    TextFormat.markdown,
                    featureExplanation.ToString(),
                    TextFormat.markdown);
                scenarioName = null;
                scenarioExplanation.Clear();
                featureExplanation.Clear();
            }
            if (currentStep != null)
            {
                this.AddStep(scenarioBuilder, currentStepType, currentStep, stepInput, stepExplanation);
                currentStep = null;
            }
        }
Beispiel #51
0
        private static SdkMessageProcessingStepImage GetImageToRegister(IOrganizationService service, Guid stepId, Step step, bool isPreImage)
        {
            var isAllColumns = isPreImage ? step.PreImageAllAttributes : step.PostImageAllAttributes;
            var columns      = isPreImage ? step.PreImageAttributes : step.PostImageAttributes;
            var name         = isPreImage ? "PreImage" : "PostImage";

            var messagePropertyName = "Target";

            if (step.Message == Messages.Create.ToString() && !isPreImage)
            {
                messagePropertyName = "Id";
            }
            else if (step.Message == Messages.SetState.ToString() || step.Message == Messages.SetStateDynamicEntity.ToString())
            {
                messagePropertyName = "EntityMoniker";
            }

            var t = new SdkMessageProcessingStepImage()
            {
                Attributes1         = isAllColumns ? null : columns,
                EntityAlias         = name,
                ImageType           = new OptionSetValue(isPreImage ? (int)sdkmessageprocessingstepimage_imagetype.PreImage : (int)sdkmessageprocessingstepimage_imagetype.PostImage),
                IsCustomizable      = new BooleanManagedProperty(true),
                MessagePropertyName = messagePropertyName,
                Name = name,
                SdkMessageProcessingStepId = new EntityReference(SdkMessageProcessingStep.EntityLogicalName, stepId)
            };

            return(t);
        }
Beispiel #52
0
 public Sequence AddStep(Step step)
 {
     _steps.Add(step);
     return(this);
 }
Beispiel #53
0
        private IEnumerator RequestVersions()
        {
            OnMessage("正在获取版本信息...");
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                var mb = MessageBox.Show("提示", "请检查网络连接状态", "重试", "退出");
                yield return(mb);

                if (mb.isOk)
                {
                    StartUpdate();
                }
                else
                {
                    Quit();
                }

                yield break;
            }

            var request = UnityWebRequest.Get(GetDownloadURL(Versions.Filename));

            request.downloadHandler = new DownloadHandlerFile(_savePath + Versions.Filename);
            yield return(request.SendWebRequest());

            var error = request.error;

            request.Dispose();
            if (!string.IsNullOrEmpty(error))
            {
                var mb = MessageBox.Show("提示", string.Format("获取服务器版本失败:{0}", error), "重试", "退出");
                yield return(mb);

                if (mb.isOk)
                {
                    StartUpdate();
                }
                else
                {
                    Quit();
                }

                yield break;
            }

            try
            {
                _versions = Versions.LoadVersions(_savePath + Versions.Filename, true);
                if (_versions.Count > 0)
                {
                    PrepareDownloads();
                    _step = Step.Prepared;
                }
                else
                {
                    OnComplete();
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                MessageBox.Show("提示", "版本文件加载失败", "重试", "退出").onComplete +=
                    delegate(MessageBox.EventId id)
                {
                    if (id == MessageBox.EventId.Ok)
                    {
                        StartUpdate();
                    }
                    else
                    {
                        Quit();
                    }
                };
            }
        }
Beispiel #54
0
 /// <summary>Invokes a delegate for each entry in the data structure.</summary>
 /// <param name="step_function">The delegate to invoke on each item in the structure.</param>
 public void Stepper(Step <T> step_function)
 {
     this._tree.Keys(step_function);
 }
Beispiel #55
0
 private async Task SelectStepAsync(Step step) => await BaseMainViewModel.BaseInstance.SetStepAsync(step.Index);
Beispiel #56
0
    void Update()
    {
        if (ESC_Step == Step.mian)
        {
            //鍵盤選擇
            if ((Input.GetKeyDown(KeyCode.UpArrow) || Input.GetAxis("XBOX_Vertical") > 0.5f) && !inputHold)
            {
                inputHold = true;
                do
                {
                    selectedIndex -= 1;
                    if (selectedIndex < 0)
                    {
                        selectedIndex = mian_buttons.Length - 1;
                    }
                }while (mian_buttons[selectedIndex].GetComponent <Button>().interactable == false);
            }
            else if ((Input.GetKeyDown(KeyCode.DownArrow) || Input.GetAxis("XBOX_Vertical") < -0.5f) && !inputHold)
            {
                inputHold = true;
                do
                {
                    selectedIndex += 1;
                    if (selectedIndex >= mian_buttons.Length)
                    {
                        selectedIndex = 0;
                    }
                }while (mian_buttons[selectedIndex].GetComponent <Button>().interactable == false);
            }
            else if (Mathf.Abs(Input.GetAxis("XBOX_Vertical")) < 0.5f && inputHold)
            {
                inputHold = false;
            }

            //設定選擇的項目
            EventSystem.current.SetSelectedGameObject(mian_buttons[selectedIndex]);


            //進入
            if (Input.GetButtonDown("Submit"))
            {
                // EventSystem.current.currentSelectedGameObject.
                switch (selectedIndex)
                {
                case 0:
                    gameManager.SetEscMenu(false);
                    break;

                case 1:
                    ESC_folder[0].SetActive(false); ESC_folder[1].SetActive(true);
                    ESC_Step = Step.control;
                    break;

                case 2:
                    ESC_folder[0].SetActive(false); ESC_folder[2].SetActive(true);
                    ESC_Step = Step.energy;
                    break;

                case 3:
                    ESC_folder[3].SetActive(true);
                    ESC_Step = Step.exit;
                    break;
                }
            }

            if (Input.GetButtonDown("Cancel"))
            {
                gameManager.SetEscMenu(false);
            }
        }
        else if (ESC_Step == Step.control || ESC_Step == Step.energy)
        {
            if (Input.GetButtonDown("Cancel"))
            {
                ResetEscMain();
                ESC_Step = Step.mian;
            }
        }
        else if (ESC_Step == Step.exit)
        {
            if (Input.GetButtonDown("Submit"))
            {
                PlayerStatus.canControl = true;
                Time.timeScale          = 1f;

                if (SceneManager.GetActiveScene().buildIndex == SceneManager.GetSceneByName("Level_Room").buildIndex)
                {
                    gameManager.GoToScene(0);
                }
                else if (SceneManager.GetActiveScene().buildIndex >= SceneManager.GetSceneByName("Level_Room").buildIndex)
                {
                    gameManager.GoToScene("Level_Room");
                }

                this.gameObject.SetActive(false);
            }
            else if (Input.GetButtonDown("Cancel"))
            {
                ESC_folder[3].SetActive(false);
                ESC_Step = Step.mian;
            }
        }
    }
Beispiel #57
0
 public void Set(Step step, int value)
 {
     alterationsWithinOneBar[StepToIndex(step)] = value;
 }
Beispiel #58
0
        bool FindPath(MeshElement start, Point3d startPos, Point3d endPos, LinkedList <Point3d> path)
        {
            Point3d currentPos = start.triangle.Centroid.Copy();
            float   distance   = Distance(startPos, endPos);
            Step    step       = new Step(start);

            step.costS2C = 0;
            step.costS2E = distance;
            m_open.Add(start.meshId, step);
            m_openSorted.Add(step);
            while (m_openSorted.Count != 0)
            {
                IEnumerator <Step> e = m_openSorted.GetEnumerator();
                if (!e.MoveNext())
                {
                    return(false);
                }
                Step currentStep = e.Current;
                int  id          = currentStep.element.meshId;
                m_openSorted.Remove(currentStep);
                m_open.Remove(id);
                MeshElement element = currentStep.element;
                if (TriangleContainPoint(element.triangle, endPos))
                {
                    // Success ...
                    ConstructPath(currentStep, endPos, path);
                    return(true);
                }
                m_close.Add(id);
                foreach (MeshElement neighbor in element.neighbor)
                {
                    if (neighbor == null)
                    {
                        continue;
                    }
                    if (m_close.Contains(neighbor.meshId))
                    {
                        continue;
                    }

                    // start position to this neighbor piece cost
                    float costS2C = currentStep.costS2C + Distance(neighbor.triangle.Centroid, endPos);
                    if (m_open.ContainsKey(neighbor.meshId))
                    {
                        Step s = m_open.GetValueOrDefault(neighbor.meshId);

                        if (s != null && costS2C < s.costS2C)
                        {
                            m_openSorted.Remove(s);
                            s.costS2C = costS2C;
                            s.prev    = currentStep;
                            m_openSorted.Add(s);
                        }
                    }
                    else
                    {
                        Step nextStep = new Step(neighbor);
                        nextStep.costS2C = costS2C;
                        nextStep.costS2E = costS2C + CostEstimate(startPos, neighbor.triangle.Centroid, endPos);
                        m_open.Add(neighbor.meshId, nextStep);
                        m_openSorted.Add(nextStep);
                        nextStep.prev = currentStep;
                    }
                }
            }
            return(false);
        }
Beispiel #59
0
        private static PackagingResult ExecuteCurrentPhase(Manifest manifest, ExecutionContext executionContext)
        {
            if (manifest.Type == PackageType.Product && manifest.Level == PackageLevel.Install)
            {
                // In case of product install create initial entry at the beginning of the
                // second phase, after the new db was created in the first phase.
                if (executionContext.CurrentPhase == 1)
                {
                    SaveInitialPackage(manifest);
                }
            }
            else
            {
                if (executionContext.CurrentPhase == 0)
                {
                    SaveInitialPackage(manifest);
                }
            }

            var stepElements = manifest.GetPhase(executionContext.CurrentPhase);

            var stopper = Stopwatch.StartNew();

            Logger.LogMessage("Executing steps");

            Exception phaseException = null;
            var       successful     = false;

            try
            {
                var maxStepId = stepElements.Count();
                for (int i = 0; i < maxStepId; i++)
                {
                    var stepElement = stepElements[i];
                    var step        = Step.Parse(stepElement, i);
                    executionContext.SubstituteParameters(step);

                    var stepStopper = Stopwatch.StartNew();
                    Logger.LogStep(step, maxStepId);
                    step.Execute(executionContext);
                    stepStopper.Stop();
                    Logger.LogMessage("-------------------------------------------------------------");
                    Logger.LogMessage("Time: " + stepStopper.Elapsed);
                    if (executionContext.Terminated)
                    {
                        LogTermination(executionContext);
                        break;
                    }
                }
                stopper.Stop();
                Logger.LogMessage("=============================================================");
                Logger.LogMessage("All steps were executed.");
                Logger.LogMessage("Aggregated time: " + stopper.Elapsed);
                Logger.LogMessage("Errors: " + Logger.Errors);
                successful = true;
            }
            catch (Exception e)
            {
                phaseException = e;
            }

            var finished = executionContext.Terminated || (executionContext.CurrentPhase == manifest.CountOfPhases - 1);

            if (successful && !finished)
            {
                return new PackagingResult {
                           NeedRestart = true, Successful = true, Errors = Logger.Errors
                }
            }
            ;

            if (executionContext.Terminated && executionContext.TerminationReason == TerminationReason.Warning)
            {
                successful = false;

                phaseException = new PackageTerminatedException(executionContext.TerminationMessage);
            }

            try
            {
                SavePackage(manifest, executionContext, successful, phaseException);
            }
            finally
            {
                RepositoryVersionInfo.Reset();

                //we need to shut down messaging, because the line above uses it
                DistributedApplication.ClusterChannel.ShutDown();
            }
            if (!successful && !executionContext.Terminated)
            {
                throw new ApplicationException(String.Format(SR.Errors.PhaseFinishedWithError_1, phaseException.Message), phaseException);
            }

            return(new PackagingResult {
                NeedRestart = false, Successful = successful, Terminated = executionContext.Terminated && !successful, Errors = Logger.Errors
            });
        }
Beispiel #60
0
 public int Get(Step step)
 {
     return(alterationsWithinOneBar[StepToIndex(step)]);
 }