Example #1
0
        public void CoordinatorWorksOnFileSystemStorage()
        {
            var storage = new FileSystemStorage(@"c:\temp\netreduce", eraseContents: true) as IStorage;

            storage.Store(Base64.Encode("f1"), "ala ma kota");
            storage.Store(Base64.Encode("f2"), "kota alama");
            storage.Store(Base64.Encode("f3"), "dolan ma");
            var filesToRead = storage.ListFiles();
            var mapperCodeFile = new Uri("file:///SampleMapper.cs");
            var reducerCodeFile = new Uri("file:///SampleReducer.cs");
            TestHelpers.LoadToStorage(@"..\..\SampleMapper.cs", mapperCodeFile, storage);
            TestHelpers.LoadToStorage(@"..\..\SampleReducer.cs", reducerCodeFile, storage);
            var coordinator = new Coordinator<ThreadWorker>(storage);

            coordinator.Start(2, 2, mapperCodeFile, reducerCodeFile, filesToRead);

            string result = string.Empty;
            foreach (var uri in storage.ListFiles())
            {
                var file = this.storage.GetFileName(uri);
                if (file.Contains("REDUCE") && file.Contains(Base64.Encode("kota")))
                {
                    result = storage.Read(file);
                }
            }

            result.ShouldBe("2");
        }
        public static async void Coroutine(int[,] destination, Coordinator<int[]> coordinator) {

            Console.WriteLine("consumer started");
            int i = 0, j = 0;
            while(true) {

                Console.WriteLine("awaiting producer");
                await coordinator;
                if(coordinator.State == null) {
                    continue;
                }
                if(coordinator.State.Length == 0) {

                    Console.WriteLine("consumer finished, end of input");
                    return;
                }
                foreach(var item in coordinator.State) {
                    destination[i, j] = item;

                    Console.WriteLine("wrote {0} to [{1},{2}]", item, i, j);
                    j++;
                    if(j != destination.GetLength(1)) {
                        continue;
                    }
                    j = 0;
                    i++;
                    if(i == destination.GetLength(0)) {

                        Console.WriteLine("consumer finished, output full");
                        return;
                    }
                }
            }
        }
        public void MapToTrickleOverTimePeriod()
        {
            var model = new Coordinator
                {
                    Numbers = new List<string> { "04040404040", "11111111111" },
                    Message = "Message",
                    StartTimeUtc = DateTime.UtcNow.AddHours(2),
                    SendAllByUtc = DateTime.UtcNow.AddHours(3),
                    Tags = new List<string> { "tag1", "tag2" },
                    Topic = "Dance Dance Revolution!",
                    OlsenTimeZone = string.Empty,
                    ConfirmationEmails = new List<string> { "email1", "email2" }
                };

            var requestId = Guid.NewGuid();
            var mapper = new CoordinatorApiModelToMessageMapping();
            var message = mapper.MapToTrickleOverPeriod(model, requestId);

            var coordinationDuration = model.SendAllByUtc.Value.Subtract(model.StartTimeUtc);
            Assert.That(message.Messages.Count, Is.EqualTo(2));
            Assert.That(message.Messages[0].Mobile, Is.EqualTo(model.Numbers[0]));
            Assert.That(message.Messages[0].Message, Is.EqualTo(model.Message));
            Assert.That(message.Messages[1].Mobile, Is.EqualTo(model.Numbers[1]));
            Assert.That(message.Messages[1].Message, Is.EqualTo(model.Message));
            Assert.That(message.MetaData.Tags, Is.EqualTo(model.Tags));
            Assert.That(message.MetaData.Topic, Is.EqualTo(model.Topic));
            Assert.That(message.StartTimeUtc, Is.EqualTo(model.StartTimeUtc));
            Assert.That(message.Duration, Is.EqualTo(coordinationDuration));
            Assert.That(message.UserOlsenTimeZone, Is.EqualTo("UTC"));
            Assert.That(message.ConfirmationEmails, Is.EqualTo(model.ConfirmationEmails));
        }
 public CoordinatorService()
 {
     this.storage = new FileSystemStorage(@"c:\temp\netreduce\coordinator", true);
     this.coordinator = new Coordinator<RemoteWorker<ServiceClientWrapper>>(this.storage);
     this.uriProvider = new UriProvider();
     ServiceClientWrapper.UriProvider = this.uriProvider;
 }
Example #5
0
 public void AddActionTest()
 {
     Coordinator coord=new Coordinator();
     repository.ReplayAll();
     coord.AddAction(act);
     repository.VerifyAll();
     Assert.AreEqual(1,coord.runningActions.Count);
 }
        public void PostInvalidBothTimeSeparatorAndSendAllAtOnceSet()
        {
            var request = new Coordinator { Message = "msg", Numbers = new List<string> { "1" }, StartTimeUtc = DateTime.Now.AddMinutes(3), SendAllAtOnce = true, TimeSeparator = new TimeSpan(300)};
            var service = new CoordinatorService();
            var response = service.OnPost(request) as CoordinatorResponse;

            Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("InvalidMessage"));
            Assert.That(response.ResponseStatus.Errors[0].Message, Is.EqualTo("Message must contain either Time Separator OR DateTime to send all messages by."));
        }
        public void PostInvalidMessageExceedsLength()
        {
            var request = new Coordinator { Numbers = new List<string> { "1" }, StartTimeUtc = DateTime.Now.AddMinutes(1), SendAllByUtc = DateTime.Now.AddDays(1), Message = "sdf;lkj asd;vlkja sdvklja v;lka jsdvlka jsdvalsjk sdf;lkj asd;vlkja sdvklja v;lka jsdvlka jsdvalsjk sdf;lkj asd;vlkja sdvklja v;lka jsdvlka jsdvalsjk sdf;lkj asd;vlkja sdvklja v;lka jsdvlka jsdvalsjk sdf;lkj asd;vlkja sdvklja v;lka jsdvlka jsdvalsjk" };
            var service = new CoordinatorService();
            var response = service.OnPost(request) as CoordinatorResponse;

            Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("InvalidMessage"));
            Assert.That(response.ResponseStatus.Errors[0].Message, Is.EqualTo("Sms exceeds 160 character length"));
        }
Example #8
0
 public void RunTest()
 {
     Coordinator coord = new Coordinator();
     act.Run();
     repository.ReplayAll();
     coord.AddAction(act);
     coord.Run();
     repository.VerifyAll();
     //Assert.AreEqual(false, coord.Canceled);
 }
 /// <summary>Create a BooleanScorer2.</summary>
 /// <param name="similarity">The similarity to be used.
 /// </param>
 /// <param name="minNrShouldMatch">The minimum number of optional added scorers
 /// that should match during the search.
 /// In case no required scorers are added,
 /// at least one of the optional scorers will have to
 /// match during the search.
 /// </param>
 public BooleanScorer2(Similarity similarity, int minNrShouldMatch)
     : base(similarity)
 {
     if (minNrShouldMatch < 0)
     {
         throw new System.ArgumentException("Minimum number of optional scorers should not be negative");
     }
     coordinator = new Coordinator(this);
     this.minNrShouldMatch = minNrShouldMatch;
 }
Example #10
0
 public void CancelTest()
 {
     Coordinator coord = new Coordinator();
     act.Cancel();
     repository.ReplayAll();
     coord.currAction = act;
     coord.Cancel();
     repository.VerifyAll();
     //Assert.AreEqual(true,coord.Canceled);
 }
Example #11
0
 public void GetActionsTest()
 {
     Coordinator coord = new Coordinator();
     Expect.Call(act.Name()).Return("Тест");
     repository.ReplayAll();
     coord.AddAction(act);
     string[] str = coord.GetActions();
     repository.VerifyAll();
     Assert.AreEqual("Тест", str[0]);
 }
 public TrickleSmsWithDefinedTimeBetweenEachMessage MapToTrickleSpacedByPeriod(Coordinator model, Guid requestId)
 {
     return new TrickleSmsWithDefinedTimeBetweenEachMessage
     {
         Messages =
             model.Numbers.Select(n => new SmsData(n, model.Message)).
             ToList(),
         StartTimeUtc = model.StartTimeUtc.ToUniversalTime(),
         TimeSpacing = model.TimeSeparator.Value,
         MetaData = new SmsMetaData { Tags = model.Tags, Topic = model.Topic },
         CoordinatorId = requestId
     };
 }
        public void GetNotFound()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            ravenDocStore.Expect(r => r.GetStore()).Return(base.DocumentStore);
            var service = new CoordinatorService { RavenDocStore = ravenDocStore };

            var notFoundRequestId = Guid.NewGuid();
            var request = new Coordinator { RequestId = notFoundRequestId };
            var response = service.OnGet(request) as CoordinatorResponse;

            Assert.That(response.RequestId, Is.EqualTo(notFoundRequestId));
            Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("NotFound"));
        }
 public TrickleSmsOverCalculatedIntervalsBetweenSetDates MapToTrickleOverPeriod(Coordinator model, Guid requestId)
 {
     return new TrickleSmsOverCalculatedIntervalsBetweenSetDates
     {
         Duration = model.SendAllByUtc.Value.Subtract(model.StartTimeUtc),
         Messages =
             model.Numbers.Select(n => new SmsData(n, model.Message)).
             ToList(),
         StartTimeUtc = model.StartTimeUtc.ToUniversalTime(),
         MetaData = new SmsMetaData { Tags = model.Tags, Topic = model.Topic },
         CoordinatorId = requestId
     };
 }
Example #15
0
 public void Transpose_and_exponentiate2() {
     var source = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
     var destination = new int[6, 2];
     var coordinator = new Coordinator<int[]>(
         new Func<Coordinator<int[]>, Action>[] {
             c => () => Consumer.Coroutine(destination, c),
             c => () => Producer2.Coroutine(source, c),
         }
     );
     Print("input", source);
     coordinator.Execute();
     Print("output", destination);
 }
Example #16
0
        public Form1(string[] args)
        {
            DebugLogger.SetDebugStyleFile();
            Coordinator threadMe = new Coordinator(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
;
        
                ThreadStart stub = new ThreadStart(threadMe.CoordinateNow);
                Thread stubThread = new Thread(stub);
                stubThread.Start();

            InitializeComponent();
            
        }
Example #17
0
 public static IEnumerator Coroutine(int[,] source, Coordinator<int[]> coordinator) {
     Console.WriteLine("producer started");
     for(var i = 0; i < source.GetLength(0); i++) {
         coordinator.State = new int[source.GetLength(1)];
         for(var j = 0; j < source.GetLength(1); j++) {
             coordinator.State[j] = source[i, j];
             Console.WriteLine("read {0} from [{1},{2}]", source[i, j], i, j);
         }
         Console.WriteLine("yielding to consumer");
         yield return null;
     }
     coordinator.State = new int[0];
     Console.WriteLine("producer finished");
 }
 public SendAllMessagesAtOnce MapToSendAllAtOnce(Coordinator model, Guid requestId)
 {
     return new SendAllMessagesAtOnce
     {
         Messages =
             model.Numbers.Select(n => new SmsData(n, model.Message)).
             ToList(),
         SendTimeUtc = model.StartTimeUtc.ToUniversalTime(),
         MetaData = new SmsMetaData { Tags = model.Tags, Topic = model.Topic },
         CoordinatorId = requestId,
         ConfirmationEmails = model.ConfirmationEmails,
         UserOlsenTimeZone = string.IsNullOrWhiteSpace(model.OlsenTimeZone) ? "UTC" : model.OlsenTimeZone
     };
 }
Example #19
0
        public void Transpose() {
            var source = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
            var destination = new int[6, 2];
            var coordinator = new Coordinator<int[]>(
                new Func<Coordinator<int[]>, IEnumerator>[] {

                    // Curry coroutine into common "shape"
                    c => Consumer.Coroutine(destination, c),
                    c => Producer.Coroutine(source, c),
                }
            );
            Print("input", source);
            coordinator.Execute();
            Print("output", destination);
        }
 public TrickleSmsWithDefinedTimeBetweenEachMessage MapToTrickleSpacedByPeriod(Coordinator model, Guid requestId)
 {
     return new TrickleSmsWithDefinedTimeBetweenEachMessage
     {
         Messages =
             model.Numbers.Select(n => new SmsData(n, model.Message)).
             ToList(),
         StartTimeUtc = model.StartTimeUtc.ToUniversalTime(),
         TimeSpacing = model.TimeSeparator.Value,
         MetaData = new SmsMetaData { Tags = model.Tags, Topic = model.Topic },
         CoordinatorId = requestId,
         ConfirmationEmails = model.ConfirmationEmails,
         UserOlsenTimeZone = string.IsNullOrWhiteSpace(model.OlsenTimeZone) ? "UTC" : model.OlsenTimeZone
     };
 }
 public TrickleSmsOverCalculatedIntervalsBetweenSetDates MapToTrickleOverPeriod(Coordinator model, Guid requestId)
 {
     return new TrickleSmsOverCalculatedIntervalsBetweenSetDates
     {
         Duration = model.SendAllByUtc.Value.Subtract(model.StartTimeUtc),
         Messages =
             model.Numbers.Select(n => new SmsData(n, model.Message)).
             ToList(),
         StartTimeUtc = model.StartTimeUtc.ToUniversalTime(),
         MetaData = new SmsMetaData { Tags = model.Tags, Topic = model.Topic },
         CoordinatorId = requestId,
         ConfirmationEmails = model.ConfirmationEmails,
         UserOlsenTimeZone = string.IsNullOrWhiteSpace(model.OlsenTimeZone) ? "UTC" : model.OlsenTimeZone
     };
 }
 public static async void Coroutine(Coordinator<int[]> coordinator) {
     while(true) {
         if(coordinator.State == null) {
             continue;
         }
         if(coordinator.State.Length == 0) {
             Console.WriteLine("consumer finished, end of input");
             return;
         }
         for(int i = 0; i < coordinator.State.Length; i++) {
             var item = coordinator.State[i];
             coordinator.State[i] = item * item;
         }
         await coordinator;
     }
 }
 public static IEnumerator Coroutine(Coordinator<int[]> coordinator) {
     while(true) {
         if(coordinator.State == null) {
             continue;
         }
         if(coordinator.State.Length == 0) {
             Console.WriteLine("consumer finished, end of input");
             yield break;
         }
         for(int i = 0; i < coordinator.State.Length; i++) {
             var item = coordinator.State[i];
             coordinator.State[i] = item * item;
         }
         yield return coordinator;
     }
 }
        public void GetFound()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            ravenDocStore.Expect(r => r.GetStore()).Return(base.DocumentStore);
            var service = new CoordinatorService {RavenDocStore = ravenDocStore};

            var request = new Coordinator { RequestId = _coordinatorId };
            var response = service.OnGet(request) as CoordinatorResponse;

            Assert.That(response.RequestId, Is.EqualTo(_coordinatorId));
            Assert.That(response.Messages.Count, Is.EqualTo(2));
            Assert.That(response.Messages[0].Number, Is.EqualTo("12313"));
            Assert.That(response.Messages[0].Status, Is.EqualTo(MessageStatusTracking.CompletedSuccess));
            Assert.That(response.Messages[1].Number, Is.EqualTo("434039"));
            Assert.That(response.Messages[1].Status, Is.EqualTo(MessageStatusTracking.Scheduled));

            ravenDocStore.VerifyAllExpectations();
        }
Example #25
0
        public static async void Coroutine(int[,] source, Coordinator<int[]> coordinator) {

            Console.WriteLine("producer started");
            for(var i = 0; i < source.GetLength(0); i++) {

                coordinator.State = new int[source.GetLength(1)];
                for(var j = 0; j < source.GetLength(1); j++) {

                    var item = source[i, j];
                    coordinator.State[j] = item;

                    Console.WriteLine("read {0} from [{1},{2}]", item, i, j);
                }

                Console.WriteLine("awaiting consumer");
                await coordinator;
            }

            coordinator.State = new int[0];
            Console.WriteLine("producer finished");
        }
        /// <summary> Creates a {@link Scorer} with the given similarity and lists of required,
        /// prohibited and optional scorers. In no required scorers are added, at least
        /// one of the optional scorers will have to match during the search.
        /// 
        /// </summary>
        /// <param name="similarity">The similarity to be used.
        /// </param>
        /// <param name="minNrShouldMatch">The minimum number of optional added scorers that should match
        /// during the search. In case no required scorers are added, at least
        /// one of the optional scorers will have to match during the search.
        /// </param>
        /// <param name="required">the list of required scorers.
        /// </param>
        /// <param name="prohibited">the list of prohibited scorers.
        /// </param>
        /// <param name="optional">the list of optional scorers.
        /// </param>
        public BooleanScorer2(Similarity similarity, int minNrShouldMatch, System.Collections.IList required, System.Collections.IList prohibited, System.Collections.IList optional)
            : base(similarity)
        {
            if (minNrShouldMatch < 0)
            {
                throw new System.ArgumentException("Minimum number of optional scorers should not be negative");
            }
            coordinator = new Coordinator(this);
            this.minNrShouldMatch = minNrShouldMatch;

            optionalScorers = optional;
            coordinator.maxCoord += optional.Count;

            requiredScorers = required;
            coordinator.maxCoord += required.Count;

            prohibitedScorers = prohibited;

            coordinator.Init();
            countingSumScorer = MakeCountingSumScorer();
        }
        public static async void Coroutine(int[,] source, Coordinator<int[]> coordinator) {

            Console.WriteLine("producer started");
            for(var i = 0; i < source.GetLength(0); i++) {

                coordinator.State = new int[source.GetLength(1)];
                for(var j = 0; j < source.GetLength(1); j++) {

                    var item = source[i, j];

                    // awaiting a regular async method while in a coordinator controlled coroutine (not possible with Iterator based coroutines)
                    var exponentiated = await Exponentiator2.AsyncMethod(item);
                    coordinator.State[j] = exponentiated;

                    Console.WriteLine("read {0} from [{1},{2}] and processed to {3}", item, i, j, exponentiated);
                }

                Console.WriteLine("awaiting consumer");
                await coordinator;
            }

            coordinator.State = new int[0];
            Console.WriteLine("producer finished");
        }
Example #28
0
 private void textBoxFilterData_TextChanged(object sender, EventArgs e)
 {
     Coordinator.TimedFilter(this.ListView, ((TextBox)sender).Text);
 }
Example #29
0
 private void OnConnectionTerminated(ConnectionTerminated data)
 {
     Coordinator?.Disconnect(data.Connection);
 }
Example #30
0
        private void SaveAssignmentOffice()
        {
            ProfessionalPracticesContext professionalPracticesContext = new ProfessionalPracticesContext();
            UnitOfWork unitOfWork = new UnitOfWork(professionalPracticesContext);

            try
            {
                string      assignmentOfficeFilePath = FileExplorer.Show("Guardar oficio de asignación");
                string      acceptanceOfficeFilePath = FileExplorer.Show("Guardar oficio de aceptación");
                Coordinator coordinator = unitOfWork.Coordinators.FindFirstOccurence(c => c.User.UserStatus == UserStatus.ACTIVE);

                _selectedProject      = unitOfWork.Projects.Get(_selectedProject.IdProject);
                _selectedPracticioner = unitOfWork.Practicioners.Get(_selectedPracticioner.Enrollment);

                OfficeOfAcceptance officeOfAcceptance = new OfficeOfAcceptance
                {
                    DateOfAcceptance = DateTime.Now,
                    RouteSave        = acceptanceOfficeFilePath
                };

                _assignment = new Assignment
                {
                    CompletionTerm     = "",
                    DateAssignment     = DateTime.Now,
                    RouteSave          = assignmentOfficeFilePath,
                    StartTerm          = _selectedProject.Term,
                    Status             = AssignmentStatus.Assigned,
                    OfficeOfAcceptance = officeOfAcceptance,
                    IdProject          = _selectedProject.IdProject,
                    Enrollment         = _selectedPracticioner.Enrollment
                };

                AcceptanceOfficeTemplate acceptanceOfficeTemplate = new AcceptanceOfficeTemplate();
                acceptanceOfficeTemplate.MapData(_selectedProject, _selectedPracticioner, _assignment, coordinator);

                AssignmentOfficeTemplate assignmentOfficeTemplate = new AssignmentOfficeTemplate();
                assignmentOfficeTemplate.MapData(_selectedProject, _selectedPracticioner, _assignment, coordinator);

                DocumentGenerator documentGenerator = new DocumentGenerator();
                documentGenerator.CreateAcceptanceOfficeDocument($"{_assignment.RouteSave}", acceptanceOfficeTemplate);
                documentGenerator.CreateAssignmentOfficeTemplate($"{_assignment.OfficeOfAcceptance.RouteSave}", assignmentOfficeTemplate);
                _selectedProject.QuantityPracticingAssing += 1;
                if (_selectedProject.QuantityPracticingAssing == _selectedProject.QuantityPracticing)
                {
                    _selectedProject.Status = ProjectStatus.FILLED;
                }
                List <RequestProject> requestedProjects = _selectedPracticioner.Requests;
                foreach (RequestProject requestedProject in requestedProjects)
                {
                    if (requestedProject.IdProject == _selectedProject.IdProject)
                    {
                        requestedProject.RequestStatus = RequestStatus.APROVED;
                    }
                    else
                    {
                        requestedProject.RequestStatus = RequestStatus.DENIED;
                    }
                }
                unitOfWork.Assignments.Add(_assignment);
                unitOfWork.Complete();
                MessageBox.Show("Proyecto asignado de forma exitosa");
            }
            catch (EntityException)
            {
                MessageBox.Show("Ha ocurrido un error en la conexión con la base de datos", "Consulta Fallida", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (SqlException)
            {
                MessageBox.Show("Ha ocurrido un error en la conexión con la base de datos", "Consulta Fallida", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Ocurrió un error al intentar generar el oficio de asignación; por favor, intente más tarde", "Guardado Fallido", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (COMException)
            {
                MessageBox.Show("Ocurrió un error al intentar generar el oficio de asignación, debido a que la ruta o el nombre del archivo que especificó no es válido; por favor, intente más tarde", "Guardado Fallido", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (ObjectDisposedException)
            {
                MessageBox.Show("Ocurrió un error al intentar generar el oficio de asignación; por favor, intente más tarde", "Guardado Fallido", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                unitOfWork.Dispose();
                GoBackToCoordinatorMenu();
            }
        }
 protected void OnStatusChanged(RetrieveStatus status)
 {
     Coordinator.SetStatus(status, _result);
 }
        public void PostNoTopic()
        {
            var request = new Coordinator { Message = "msg", Numbers = new List<string> { "1" }, StartTimeUtc = DateTime.Now.AddHours(1), SendAllByUtc = DateTime.Now.AddDays(1), Topic = string.Empty};
            var service = new CoordinatorService();
            var response = service.OnPost(request) as CoordinatorResponse;

            Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("InvalidMessage"));
            Assert.That(response.ResponseStatus.Errors[0].Message, Is.EqualTo("Topic must be set"));
        }
Example #33
0
 /// <summary>
 /// Called when new TensorFlow session is created.
 /// </summary>
 /// <param name="session"></param>
 /// <param name="coord"></param>
 public virtual void after_create_session(Session session, Coordinator coord)
 {
 }
Example #34
0
 /// <summary>
 /// 根据时间查询传感器数据
 /// </summary>
 /// <param name="dtStart">开始时间</param>
 /// <param name="dtEnd">截止时间</param>
 /// <returns></returns>
 public static List <ShowRefer> ShowCoorTimeList(Coordinator coordinator, DateTime dtStart, DateTime dtEnd)
 {
     return(ShowReferCoorList(coordinator).Where(p => p.Time >= dtStart.Date && p.Time <= dtEnd.Date).OrderByDescending(p => p.Time).ToList());
 }
Example #35
0
        public async Task <IActionResult> PostInputsAsync([FromBody, Required] InputsRequest request)
        {
            // Validate request.
            if (request.RoundId < 0 || !ModelState.IsValid)
            {
                return(BadRequest("Invalid request."));
            }

            if (request.Inputs.Count() > 7)
            {
                return(BadRequest("Maximum 7 inputs can be registered."));
            }

            using (await InputsLock.LockAsync())
            {
                CcjRound round = Coordinator.TryGetRound(request.RoundId);

                if (round is null || round.Phase != CcjRoundPhase.InputRegistration)
                {
                    return(NotFound("No such running round in InputRegistration. Try another round."));
                }

                // Do more checks.
                try
                {
                    uint256[] blindedOutputs        = request.BlindedOutputScripts.ToArray();
                    int       blindedOutputCount    = blindedOutputs.Length;
                    int       maxBlindedOutputCount = round.MixingLevels.Count();
                    if (blindedOutputCount > maxBlindedOutputCount)
                    {
                        return(BadRequest($"Too many blinded output was provided: {blindedOutputCount}, maximum: {maxBlindedOutputCount}."));
                    }

                    if (blindedOutputs.Distinct().Count() < blindedOutputs.Length)
                    {
                        return(BadRequest("Duplicate blinded output found."));
                    }

                    if (round.ContainsAnyBlindedOutputScript(blindedOutputs))
                    {
                        return(BadRequest("Blinded output has already been registered."));
                    }

                    if (request.ChangeOutputAddress.Network != Network)
                    {
                        // RegTest and TestNet address formats are sometimes the same.
                        if (Network == Network.Main)
                        {
                            return(BadRequest($"Invalid ChangeOutputAddress Network."));
                        }
                    }

                    var uniqueInputs = new HashSet <TxoRef>();
                    foreach (InputProofModel inputProof in request.Inputs)
                    {
                        if (uniqueInputs.Contains(inputProof.Input))
                        {
                            return(BadRequest("Cannot register an input twice."));
                        }
                        uniqueInputs.Add(inputProof.Input);
                    }

                    var alicesToRemove    = new HashSet <Guid>();
                    var getTxOutResponses = new List <(InputProofModel inputModel, Task <GetTxOutResponse> getTxOutTask)>();

                    var batch = RpcClient.PrepareBatch();

                    foreach (InputProofModel inputProof in request.Inputs)
                    {
                        if (round.ContainsInput(inputProof.Input.ToOutPoint(), out List <Alice> tr))
                        {
                            alicesToRemove.UnionWith(tr.Select(x => x.UniqueId));                             // Input is already registered by this alice, remove it later if all the checks are completed fine.
                        }
                        if (Coordinator.AnyRunningRoundContainsInput(inputProof.Input.ToOutPoint(), out List <Alice> tnr))
                        {
                            if (tr.Union(tnr).Count() > tr.Count())
                            {
                                return(BadRequest("Input is already registered in another round."));
                            }
                        }

                        OutPoint outpoint   = inputProof.Input.ToOutPoint();
                        var      bannedElem = await Coordinator.UtxoReferee.TryGetBannedAsync(outpoint, notedToo : false);

                        if (bannedElem != null)
                        {
                            return(BadRequest($"Input is banned from participation for {(int)bannedElem.BannedRemaining.TotalMinutes} minutes: {inputProof.Input.Index}:{inputProof.Input.TransactionId}."));
                        }

                        var txoutResponseTask = batch.GetTxOutAsync(inputProof.Input.TransactionId, (int)inputProof.Input.Index, includeMempool: true);
                        getTxOutResponses.Add((inputProof, txoutResponseTask));
                    }

                    // Perform all RPC request at once
                    var waiting = Task.WhenAll(getTxOutResponses.Select(x => x.getTxOutTask));
                    await batch.SendBatchAsync();

                    await waiting;

                    byte[]  blindedOutputScriptHashesByte = ByteHelpers.Combine(blindedOutputs.Select(x => x.ToBytes()));
                    uint256 blindedOutputScriptsHash      = new uint256(Hashes.SHA256(blindedOutputScriptHashesByte));

                    var inputs = new HashSet <Coin>();

                    foreach (var responses in getTxOutResponses)
                    {
                        var(inputProof, getTxOutResponseTask) = responses;
                        var getTxOutResponse = await getTxOutResponseTask;

                        // Check if inputs are unspent.
                        if (getTxOutResponse is null)
                        {
                            return(BadRequest($"Provided input is not unspent: {inputProof.Input.Index}:{inputProof.Input.TransactionId}."));
                        }

                        // Check if unconfirmed.
                        if (getTxOutResponse.Confirmations <= 0)
                        {
                            // If it spends a CJ then it may be acceptable to register.
                            if (!await Coordinator.ContainsCoinJoinAsync(inputProof.Input.TransactionId))
                            {
                                return(BadRequest("Provided input is neither confirmed, nor is from an unconfirmed coinjoin."));
                            }

                            // Check if mempool would accept a fake transaction created with the registered inputs.
                            // This will catch ascendant/descendant count and size limits for example.
                            var result = await RpcClient.TestMempoolAcceptAsync(new[] { new Coin(inputProof.Input.ToOutPoint(), getTxOutResponse.TxOut) });

                            if (!result.accept)
                            {
                                return(BadRequest($"Provided input is from an unconfirmed coinjoin, but a limit is reached: {result.rejectReason}"));
                            }
                        }

                        // Check if immature.
                        if (getTxOutResponse.Confirmations <= 100)
                        {
                            if (getTxOutResponse.IsCoinBase)
                            {
                                return(BadRequest("Provided input is immature."));
                            }
                        }

                        // Check if inputs are native segwit.
                        if (getTxOutResponse.ScriptPubKeyType != "witness_v0_keyhash")
                        {
                            return(BadRequest("Provided input must be witness_v0_keyhash."));
                        }

                        TxOut txout = getTxOutResponse.TxOut;

                        var address = (BitcoinWitPubKeyAddress)txout.ScriptPubKey.GetDestinationAddress(Network);
                        // Check if proofs are valid.
                        if (!address.VerifyMessage(blindedOutputScriptsHash, inputProof.Proof))
                        {
                            return(BadRequest("Provided proof is invalid."));
                        }

                        inputs.Add(new Coin(inputProof.Input.ToOutPoint(), txout));
                    }

                    var acceptedBlindedOutputScripts = new List <uint256>();

                    // Calculate expected networkfee to pay after base denomination.
                    int   inputCount = inputs.Count();
                    Money networkFeeToPayAfterBaseDenomination = (inputCount * round.FeePerInputs) + (2 * round.FeePerOutputs);

                    // Check if inputs have enough coins.
                    Money inputSum     = inputs.Sum(x => x.Amount);
                    Money changeAmount = (inputSum - (round.MixingLevels.GetBaseDenomination() + networkFeeToPayAfterBaseDenomination));
                    if (changeAmount < Money.Zero)
                    {
                        return(BadRequest($"Not enough inputs are provided. Fee to pay: {networkFeeToPayAfterBaseDenomination.ToString(false, true)} BTC. Round denomination: {round.MixingLevels.GetBaseDenomination().ToString(false, true)} BTC. Only provided: {inputSum.ToString(false, true)} BTC."));
                    }
                    acceptedBlindedOutputScripts.Add(blindedOutputs.First());

                    Money networkFeeToPay = networkFeeToPayAfterBaseDenomination;
                    // Make sure we sign the proper number of additional blinded outputs.
                    var moneySoFar = Money.Zero;
                    for (int i = 1; i < blindedOutputCount; i++)
                    {
                        if (!round.MixingLevels.TryGetDenomination(i, out Money denomination))
                        {
                            break;
                        }

                        Money coordinatorFee = denomination.Percentage(round.CoordinatorFeePercent * round.AnonymitySet);                         // It should be the number of bobs, but we must make sure they'd have money to pay all.
                        changeAmount    -= (denomination + round.FeePerOutputs + coordinatorFee);
                        networkFeeToPay += round.FeePerOutputs;

                        if (changeAmount < Money.Zero)
                        {
                            break;
                        }

                        acceptedBlindedOutputScripts.Add(blindedOutputs[i]);
                    }

                    // Make sure Alice checks work.
                    var alice = new Alice(inputs, networkFeeToPayAfterBaseDenomination, request.ChangeOutputAddress, acceptedBlindedOutputScripts);

                    foreach (Guid aliceToRemove in alicesToRemove)
                    {
                        round.RemoveAlicesBy(aliceToRemove);
                    }
                    round.AddAlice(alice);

                    // All checks are good. Sign.
                    var blindSignatures = new List <uint256>();
                    for (int i = 0; i < acceptedBlindedOutputScripts.Count; i++)
                    {
                        var     blindedOutput  = acceptedBlindedOutputScripts[i];
                        var     signer         = round.MixingLevels.GetLevel(i).Signer;
                        uint256 blindSignature = signer.Sign(blindedOutput);
                        blindSignatures.Add(blindSignature);
                    }
                    alice.BlindedOutputSignatures = blindSignatures.ToArray();

                    // Check if phase changed since.
                    if (round.Status != CcjRoundStatus.Running || round.Phase != CcjRoundPhase.InputRegistration)
                    {
                        return(StatusCode(StatusCodes.Status503ServiceUnavailable, "The state of the round changed while handling the request. Try again."));
                    }

                    // Progress round if needed.
                    if (round.CountAlices() >= round.AnonymitySet)
                    {
                        await round.RemoveAlicesIfAnInputRefusedByMempoolAsync();

                        if (round.CountAlices() >= round.AnonymitySet)
                        {
                            await round.ExecuteNextPhaseAsync(CcjRoundPhase.ConnectionConfirmation);
                        }
                    }

                    var resp = new InputsResponse {
                        UniqueId = alice.UniqueId,
                        RoundId  = round.RoundId
                    };
                    return(Ok(resp));
                }
                catch (Exception ex)
                {
                    Logger.LogDebug <ChaumianCoinJoinController>(ex);
                    return(BadRequest(ex.Message));
                }
            }
        }
 protected void OnCommandCompleted()
 {
     Coordinator.OnStatusChanged(RetrieveStatus.Completed, _result);
 }
 protected void OnCommandCompleted(string message)
 {
     Coordinator.OnStatusChanged(RetrieveStatus.Completed, message, _result);
 }
Example #38
0
 private void checkBoxItemCounts_CheckedChanged(object sender, EventArgs e)
 {
     Coordinator.ShowLabelsOnGroupsChecked(this.ListView, (CheckBox)sender);
 }
Example #39
0
 private void checkBoxGroups_CheckedChanged(object sender, EventArgs e)
 {
     Coordinator.ShowGroupsChecked(this.ListView, (CheckBox)sender);
 }
 protected void OnError(string errorMessage)
 {
     Coordinator.OnStatusChanged(RetrieveStatus.Error, errorMessage, _result);
 }
 protected void OnStatusChanged(RetrieveStatus status, string message)
 {
     Coordinator.SetStatus(status, message, _result);
 }
Example #42
0
 /// <summary>
 /// 对应协调器的传感器集合
 /// </summary>
 /// <param name="coor"></param>
 /// <returns></returns>
 public static List <Sensor> GetCoorList(Coordinator coor)
 {
     return(GetList().Where(p => p.CoordinatorID == coor.ID).OrderBy(p => p.Type).ToList());
 }
Example #43
0
        public XDocument SaveBusinessObject(ServiceDocument document)
        {
            DictionaryMapper.Instance.CheckForChanges();

            //load alternate version
            if (!document.IsNew)
            {
                IBusinessObject alternateBusinessObject = this.mapper.LoadBusinessObject(document.BOType, document.Id.Value);
                document.SetAlternateVersion(alternateBusinessObject);
            }

            //update status
            document.UpdateStatus(true);

            if (document.AlternateVersion != null)
            {
                document.AlternateVersion.UpdateStatus(false);
            }

            document.Validate();

            this.ExecuteCustomLogic(document);
            this.ExecuteDocumentOptions(document);

            //validate
            document.Validate();

            //update status
            document.UpdateStatus(true);

            if (document.AlternateVersion != null)
            {
                document.AlternateVersion.UpdateStatus(false);
            }

            SqlConnectionManager.Instance.BeginTransaction();

            try
            {
                DictionaryMapper.Instance.CheckForChanges();
                this.mapper.CheckBusinessObjectVersion(document);

                this.ExecuteCustomLogicDuringTransaction(document);

                DocumentLogicHelper.AssignNumber(document, this.mapper);

                //Make operations list
                XDocument operations = XDocument.Parse("<root/>");

                document.SaveChanges(operations);

                if (document.AlternateVersion != null)
                {
                    document.AlternateVersion.SaveChanges(operations);
                }

                if (operations.Root.HasElements)
                {
                    this.mapper.ExecuteOperations(operations);
                    this.mapper.UpdateDictionaryIndex(document);
                }

                Coordinator.LogSaveBusinessObjectOperation();

                document.SaveRelatedObjects();

                operations = XDocument.Parse("<root/>");

                document.SaveRelations(operations);

                if (document.AlternateVersion != null)
                {
                    ((Document)document.AlternateVersion).SaveRelations(operations);
                }

                if (operations.Root.HasElements)
                {
                    this.mapper.ExecuteOperations(operations);
                }

                if (ProcessManager.Instance.IsServiceReservationEnabled(document))
                {
                    this.ValidateServiceReservation(document);
                    this.mapper.UpdateReservationAndOrderStock(document);
                }

                XDocument returnXml = XDocument.Parse(String.Format(CultureInfo.InvariantCulture, "<root><id>{0}</id></root>", document.Id.ToUpperString()));

                //Custom validation
                this.mapper.ExecuteOnCommitValidationCustomProcedure(document);

                if (this.coordinator.CanCommitTransaction)
                {
                    if (!ConfigurationMapper.Instance.ForceRollbackTransaction)
                    {
                        SqlConnectionManager.Instance.CommitTransaction();
                    }
                    else
                    {
                        SqlConnectionManager.Instance.RollbackTransaction();
                    }
                }

                return(returnXml);
            }
            catch (SqlException sqle)
            {
                RoboFramework.Tools.RandomLogHelper.GetLog().Debug("FractusRefactorTraceCatch:89");
                Coordinator.ProcessSqlException(sqle, document.BOType, this.coordinator.CanCommitTransaction);
                throw;
            }
            catch (Exception)
            {
                RoboFramework.Tools.RandomLogHelper.GetLog().Debug("FractusRefactorTraceCatch:90");
                if (this.coordinator.CanCommitTransaction)
                {
                    SqlConnectionManager.Instance.RollbackTransaction();
                }
                throw;
            }
        }
Example #44
0
 public static void NullCoordinator(this IGuardClause guardClause, int coordinatorid, Coordinator coordinators)
 {
     if (coordinators == null)
     {
         throw new CoordinatorNotFoundException(coordinatorid);
     }
 }
Example #45
0
        // TODO: Move into a common ConsoleHelper class.
        // TODO: Move parameters into a GameRunnerConfiguration class.
        private static void RunSolverInConsole <TGameState, TSolver>(
            string appName, string serverUrl, string loggingRootFolder, string gameFilePath, int tickToReplayTo, bool errorReadingTickToReplayTo)
            where TGameState : GameState <TGameState>, new()
            where TSolver : ISolver <TGameState>, new()
        {
            // Set up debugging:
            DebugHelper.InitializeLogFolder(DateTime.Now, loggingRootFolder, appName);
            DebugHelper.WireUpDebugListeners(includeConsoleListener: true);
            try
            {
                // Set up web service adapter:
                WebServiceAdapter wsAdapter = new WebServiceAdapter
                {
                    Url = serverUrl,
                    EndPointConfigurationName = "ChallengePort"
                };

                // Set up solvers and coordinators:
                ISolver <TGameState>     solver = new TSolver();
                ICommunicatorCallback    communicatorCallback = new RemoteCommunicatorCallback();
                Coordinator <TGameState> coordinator          = new Coordinator <TGameState>(solver, wsAdapter, communicatorCallback);

                bool stepIntoGame = false;
                if (!string.IsNullOrEmpty(gameFilePath))
                {
                    if (tickToReplayTo == 0 || tickToReplayTo == 1)
                    {
                        stepIntoGame = true;
                    }
                    else
                    {
                        DebugHelper.LogDebugMessage(appName, "Replaying game: {0}", gameFilePath);
                        if (errorReadingTickToReplayTo)
                        {
                            DebugHelper.LogDebugMessage(appName,
                                                        "WARNING: The fourth parameter can't be parsed as a 'Tick To Replay To'. Using default.");
                        }

                        Game gameToReplay = Game.Load(gameFilePath);
                        if (tickToReplayTo == -1)
                        {
                            tickToReplayTo = gameToReplay.CurrentTurn.Tick;
                        }
                        DebugHelper.LogDebugMessage(appName, "Replaying to turn {0}.", tickToReplayTo);
                        if (gameToReplay.Turns[tickToReplayTo].TankActionsTakenAfterPreviousTurn == null)
                        {
                            throw new ApplicationException(
                                      String.Format(
                                          "No tank actions were recorded for the game's last tick ({0})",
                                          tickToReplayTo
                                          )
                                      );
                        }

                        solver.GameToReplay   = gameToReplay;
                        solver.TickToReplayTo = tickToReplayTo;
                    }
                }

                // Write log file headers and set the coordinator running:
                DebugHelper.LogDebugMessage(appName, "Running solver: {0}", solver.Name);
                DebugHelper.WriteLine('=');
                DebugHelper.WriteLine();
                try
                {
                    if (stepIntoGame)
                    {
                        // The tickToReplayTo is actually the playerIndex
                        // Load the game state as the initial game state of the game:
                        DebugHelper.LogDebugMessage(appName,
                                                    "Stepping into solver for player {0} with initial game state loaded from game file {1}",
                                                    tickToReplayTo, gameFilePath);
                        coordinator.StepInto(yourPlayerIndex: tickToReplayTo, initialGameStateFilePath: gameFilePath);
                        DebugHelper.LogDebugMessage(appName, "coordinator.BestMoveSoFar =\r\n{0}", coordinator.BestMoveSoFar);
                    }
                    else
                    {
                        coordinator.Run();
                    }
                }
                catch (Exception exc)
                {
                    DebugHelper.LogDebugError(appName, exc);
                }
            }
            finally
            {
                DebugHelper.LogDebugMessage(appName, "EXITING");
                DebugHelper.WriteLine('-');
            }
        }
        public XDocument ProcessWarehouseCorrectiveDocument(WarehouseDocument document)
        {
            SqlConnectionManager.Instance.BeginTransaction();

            try
            {
                DictionaryMapper.Instance.CheckForChanges();

                this.MakeDifferentialDocument(document);

                if (document.DocumentType.WarehouseDocumentOptions.UpdateLastPurchasePrice)
                {
                    UpdateLastPurchasePriceRequest updateLastPurchasePriceRequest = new UpdateLastPurchasePriceRequest(document);
                    this.mapper.UpdateStock(updateLastPurchasePriceRequest);
                }

                //sprawdzamy czy nie zmniejszylismy gdzies ilosci ponizej ilosci ktora zostala juz rozchodowana
                bool outcomeCorrectionNeeded = this.CheckForQuantityBelowRelated(document);

                document.AlternateVersion = null;
                this.coordinator.UpdateStock(document);

                WarehouseDocument incomeCorrection = (WarehouseDocument)this.coordinator.CreateNewBusinessObject(BusinessObjectType.WarehouseDocument, document.Source.Attribute("template").Value, null);
                incomeCorrection.Contractor  = document.Contractor;
                incomeCorrection.WarehouseId = document.WarehouseId;
                DuplicableAttributeFactory.CopyAttributes(document, incomeCorrection);
                incomeCorrection.UpdateStatus(true);
                this.SaveDocumentHeaderAndAttributes(incomeCorrection);

                WarehouseDocument outcomeCorrection = null;
                int? outcomeCorrectionOrdinalNumber = null;
                Guid?outcomeCorrectionHeaderId      = null;

                if (outcomeCorrectionNeeded)
                {
                    DocumentType dt       = incomeCorrection.DocumentType;
                    string       template = dt.WarehouseDocumentOptions.AutomaticCostCorrectionTemplate;

                    if (String.IsNullOrEmpty(template))
                    {
                        throw new InvalidOperationException("automaticCostCorrectionTemplate is not set for the document type: " + dt.Symbol);
                    }

                    outcomeCorrection             = (WarehouseDocument)this.coordinator.CreateNewBusinessObject(BusinessObjectType.WarehouseDocument, template, null);
                    outcomeCorrection.WarehouseId = document.WarehouseId;
                    outcomeCorrection.UpdateStatus(true);
                    this.SaveDocumentHeaderAndAttributes(outcomeCorrection);
                    outcomeCorrectionOrdinalNumber = 0;
                    outcomeCorrectionHeaderId      = outcomeCorrection.Id.Value;
                }

                int       incomeCorrectionOrdinalNumber = 0;
                XDocument xml        = null;
                XDocument operations = XDocument.Parse("<root><incomeOutcomeRelation/><commercialWarehouseRelation/><commercialWarehouseValuation/></root>");

                foreach (WarehouseDocumentLine line in document.Lines.Children)
                {
                    Guid?commercialCorrectiveLineId = null;

                    if (line.CommercialCorrectiveLine != null)
                    {
                        commercialCorrectiveLineId = line.CommercialCorrectiveLine.Id;
                    }

                    xml = this.mapper.CreateIncomeQuantityCorrection(line.Id.Value, line.Version.Value, incomeCorrection.Id.Value,
                                                                     outcomeCorrectionHeaderId, line.Quantity, line.Value, line.IncomeDate.Value, incomeCorrectionOrdinalNumber,
                                                                     outcomeCorrectionOrdinalNumber, commercialCorrectiveLineId);

                    //Prowizorka umieszczona w celu wychwycenia trudnego do zlokalizowania błędu - przerzucam komunikat od Czarka w wyjątku
                    if (!xml.Root.HasElements)
                    {
                        throw new ClientException(ClientExceptionId.ForwardError, null
                                                  , String.Format("message:{0}", xml.Root.Value));
                    }

                    incomeCorrectionOrdinalNumber = Convert.ToInt32(xml.Root.Element("incomeOrdinalNumber").Value, CultureInfo.InvariantCulture);

                    if (outcomeCorrectionOrdinalNumber != null)
                    {
                        outcomeCorrectionOrdinalNumber = Convert.ToInt32(xml.Root.Element("outcomeOrdinalNumber").Value, CultureInfo.InvariantCulture);
                    }

                    if (xml.Root.Element("incomeOutcomeRelation") != null)
                    {
                        operations.Root.Element("incomeOutcomeRelation").Add(xml.Root.Element("incomeOutcomeRelation").Elements());
                    }

                    if (xml.Root.Element("commercialWarehouseRelation") != null)
                    {
                        operations.Root.Element("commercialWarehouseRelation").Add(xml.Root.Element("commercialWarehouseRelation").Elements());
                    }

                    if (xml.Root.Element("commercialWarehouseValuation") != null)
                    {
                        operations.Root.Element("commercialWarehouseValuation").Add(xml.Root.Element("commercialWarehouseValuation").Elements());
                    }
                }

                if (ConfigurationMapper.Instance.IsWmsEnabled &&
                    DictionaryMapper.Instance.GetWarehouse(incomeCorrection.WarehouseId).ValuationMethod == ValuationMethod.DeliverySelection)
                {
                    using (WarehouseCoordinator whC = new WarehouseCoordinator(false, false))
                    {
                        ShiftTransaction st = (ShiftTransaction)whC.CreateNewBusinessObject(BusinessObjectType.ShiftTransaction, null, null);
                        st.UpdateStatus(true);
                        XDocument shiftTransactionOperations = XDocument.Parse("<root/>");
                        st.SaveChanges(shiftTransactionOperations);
                        this.mapper.ExecuteOperations(shiftTransactionOperations);
                        this.mapper.CreateShiftCorrection(incomeCorrection.Id.Value, st.Id.Value);
                    }
                }

                if (outcomeCorrection != null)
                {
                    this.mapper.ValuateOutcomeWarehouseDocument(outcomeCorrection);
                }

                this.mapper.CreateCommunicationXml(incomeCorrection);

                if (outcomeCorrection != null)
                {
                    this.mapper.CreateCommunicationXml(outcomeCorrection);
                }

                this.mapper.CreateCommunicationXmlForDocumentRelations(operations);

                XDocument returnXml = XDocument.Parse(String.Format(CultureInfo.InvariantCulture, "<root><id>{0}</id></root>", incomeCorrection.Id.ToUpperString()));

                //Custom validation
                this.mapper.ExecuteOnCommitValidationCustomProcedure(incomeCorrection);
                if (outcomeCorrection != null)
                {
                    this.mapper.ExecuteOnCommitValidationCustomProcedure(outcomeCorrection);
                }

                if (this.coordinator.CanCommitTransaction)
                {
                    if (!ConfigurationMapper.Instance.ForceRollbackTransaction)
                    {
                        SqlConnectionManager.Instance.CommitTransaction();
                    }
                    else
                    {
                        SqlConnectionManager.Instance.RollbackTransaction();
                    }
                }

                return(returnXml);
            }
            catch (SqlException sqle)
            {
                RoboFramework.Tools.RandomLogHelper.GetLog().Debug("FractusRefactorTraceCatch:55");
                Coordinator.ProcessSqlException(sqle, document.BOType, this.coordinator.CanCommitTransaction);
                throw;
            }
            catch (Exception)
            {
                RoboFramework.Tools.RandomLogHelper.GetLog().Debug("FractusRefactorTraceCatch:56");
                if (this.coordinator.CanCommitTransaction)
                {
                    SqlConnectionManager.Instance.RollbackTransaction();
                }
                throw;
            }
        }
        public void PostValidWithEndDateCoordinator()
        {
            var request = new Coordinator { Message = "msg", Numbers = new List<string> { "1" }, StartTimeUtc = DateTime.Now.AddDays(1), SendAllByUtc = DateTime.Now.AddDays(1), Topic = "topic"};

            var bus = MockRepository.GenerateMock<IBus>();
            var mapper = MockRepository.GenerateMock<ICoordinatorApiModelToMessageMapping>();

            mapper.Expect(m => m.MapToTrickleOverPeriod(Arg<Coordinator>.Is.Equal(request), Arg<Guid>.Is.Anything));
            bus.Expect(b => b.Send(Arg<TrickleSmsOverCalculatedIntervalsBetweenSetDates>.Is.NotNull));

            var service = new CoordinatorService { Bus = bus, Mapper = mapper };
            var response = service.OnPost(request) as CoordinatorResponse;

            Assert.That(response.ResponseStatus.ErrorCode, Is.Null);
            Assert.That(response.RequestId, Is.Not.EqualTo(Guid.Empty));

            bus.VerifyAllExpectations();
            mapper.VerifyAllExpectations();
        }
 protected void OnCommandExecuted()
 {
     Coordinator.OnCommandExecuted();
 }
Example #49
0
 public EnumConverter(IDataProtectionProvider dataProtectionProvider, JsonSerializerOptions options)
     : base(dataProtectionProvider.CreateProtector(_purpose), options, Coordinator.GetByteConverter <T>())
 {
 }
Example #50
0
 public void OnHandshakeCompleted(HandshakeCompleted data)
 {
     Coordinator?.Connect(data.Connection, data.Handshake);
 }
Example #51
0
 public void Remove(Coordinator coordinator)
 {
     _context.Coordinators.Remove(coordinator);
 }
 protected void OnProgressUpdated(string message)
 {
     Coordinator.OnStatusChanged(_result.Status, message, _result);
 }
Example #53
0
        private void SetupColumns()
        {
            // The column setup here is identical to the File Explorer example tab --
            // nothing specific to the TreeListView.

            // The only difference is that we don't setup anything to do with grouping,
            // since TreeListViews can't show groups.

            SysImageListHelper helper = new SysImageListHelper(this.treeListView);

            this.olvColumnName.ImageGetter = delegate(object x) {
                return(helper.GetImageIndex(((MyFileSystemInfo)x).FullName));
            };

            // Get the size of the file system entity.
            // Folders and errors are represented as negative numbers
            this.olvColumnSize.AspectGetter = delegate(object x) {
                MyFileSystemInfo myFileSystemInfo = (MyFileSystemInfo)x;

                if (myFileSystemInfo.IsDirectory)
                {
                    return((long)-1);
                }

                try {
                    return(myFileSystemInfo.Length);
                }
                catch (System.IO.FileNotFoundException) {
                    // Mono 1.2.6 throws this for hidden files
                    return((long)-2);
                }
            };

            // Show the size of files as GB, MB and KBs. By returning the actual
            // size in the AspectGetter, and doing the conversion in the
            // AspectToStringConverter, sorting on this column will work off the
            // actual sizes, rather than the formatted string.
            this.olvColumnSize.AspectToStringConverter = delegate(object x) {
                long sizeInBytes = (long)x;
                if (sizeInBytes < 0) // folder or error
                {
                    return("");
                }
                return(Coordinator.FormatFileSize(sizeInBytes));
            };

            // Show the system description for this object
            this.olvColumnFileType.AspectGetter = delegate(object x) {
                return(ShellUtilities.GetFileType(((MyFileSystemInfo)x).FullName));
            };

            // Show the file attributes for this object
            // A FlagRenderer masks off various values and draws zero or images based
            // on the presence of individual bits.
            this.olvColumnAttributes.AspectGetter = delegate(object x) {
                return(((MyFileSystemInfo)x).Attributes);
            };
            FlagRenderer attributesRenderer = new FlagRenderer();

            attributesRenderer.ImageList = imageListSmall;
            attributesRenderer.Add(FileAttributes.Archive, "archive");
            attributesRenderer.Add(FileAttributes.ReadOnly, "readonly");
            attributesRenderer.Add(FileAttributes.System, "system");
            attributesRenderer.Add(FileAttributes.Hidden, "hidden");
            attributesRenderer.Add(FileAttributes.Temporary, "temporary");
            this.olvColumnAttributes.Renderer = attributesRenderer;

            // Tell the filtering subsystem that the attributes column is a collection of flags
            this.olvColumnAttributes.ClusteringStrategy = new FlagClusteringStrategy(typeof(FileAttributes));
        }
Example #54
0
        public static void ProcessBatchedTurnDamage(AbstractActor actor)
        {
            int heatdamage = 0;

            if (ShouldSkipProcessing(actor))
            {
                return;
            }

            AbstractActor attacker = TurnDamageTracker.attackActor();

            LogReport($"\n{new string('═', 46)}");
            LogReport($"Damage to {actor.DisplayName}/{actor.Nickname}/{actor.GUID}");
            LogReport($"Damage by {attacker.DisplayName}/{attacker.Nickname}/{attacker.GUID}");

            // get the attacker in case they have mech quirks
            AbstractActor defender = null;

            switch (actor)
            {
            case Vehicle _:
                defender = (Vehicle)actor;
                break;

            case Mech _:
                defender = (Mech)actor;
                break;
            }

            // a building or turret?
            if (defender == null)
            {
                LogDebug("Not a mech or vehicle");
                return;
            }

            if (defender.IsDead || defender.IsFlaggedForDeath)
            {
                LogDebug("He's dead Jim.....");
                return;
            }

            var index = GetActorIndex(defender);

            if (modSettings.OneChangePerTurn &&
                TrackedActors[index].PanicWorsenedRecently)
            {
                LogDebug($"OneChangePerTurn {defender.Nickname} - abort");
                return;
            }

            float damageIncludingHeatDamage = 0;

            if (!modSettings.AlwaysPanic &&
                !ShouldPanic(defender, attacker, out heatdamage, out damageIncludingHeatDamage))
            {
                return;
            }

            // automatically eject a klutzy pilot on knockdown with an additional roll failing on 13
            if (defender.IsFlaggedForKnockdown)
            {
                var defendingMech = (Mech)defender;
                if (defendingMech.pilot.pilotDef.PilotTags.Contains("pilot_klutz"))
                {
                    if (Random.Range(1, 100) == 13)
                    {
                        defender.Combat.MessageCenter.PublishMessage(new AddSequenceToStackMessage
                                                                         (new ShowActorInfoSequence(defender, "WOOPS!", FloatieMessage.MessageNature.Debuff, false)));
                        LogReport("Very klutzy!");
                        return;
                    }
                }
            }

            // store saving throw
            // check it against panic
            // check it again ejection
            var savingThrow = SavingThrows.GetSavingThrow(defender, attacker, heatdamage, damageIncludingHeatDamage);

            // panic saving throw
            if (SavingThrows.SavedVsPanic(defender, savingThrow))
            {
                return;
            }

            if (!modSettings.OneChangePerTurn)
            {
                TurnDamageTracker.resetDamageTrackerFor(defender);
            }

            // stop if pilot isn't Panicked
            if (TrackedActors[index].PanicStatus != PanicStatus.Panicked)
            {
                return;
            }

            // eject saving throw
            if (!modSettings.AlwaysPanic &&
                SavingThrows.SavedVsEject(defender, savingThrow))
            {
                return;
            }

            // ejecting
            // random phrase
            if (modSettings.EnableEjectPhrases &&
                defender is Mech &&
                Random.Range(1, 100) <= modSettings.EjectPhraseChance)
            {
                var ejectMessage = ejectPhraseList[Random.Range(0, ejectPhraseList.Count)];
                var castDef      = Coordinator.CreateCast(defender);
                var content      = Coordinator.BuildDialogueContent(castDef, ejectMessage, Color.white);
                defender.Combat.MessageCenter.PublishMessage(new PanicSystemDialogMessage(defender, content, 6));
            }

            // remove effects, to prevent exceptions that occur for unknown reasons
            var combat           = UnityGameInstance.BattleTechGame.Combat;
            var effectsTargeting = combat.EffectManager.GetAllEffectsTargeting(defender);

            foreach (var effect in effectsTargeting)
            {
                // some effects removal throw, so silently drop them
                try
                {
                    defender.CancelEffect(effect);
                }
                catch
                {
                    // ignored
                }
            }

            if (modSettings.VehiclesCanPanic &&
                defender is Vehicle v)
            {
                // make the regular Pilot Ejected floatie not appear, for this ejection
                Patches.VehicleRepresentation.supressDeathFloatieOnce();
                defender.EjectPilot(defender.GUID, -1, DeathMethod.PilotEjection, true);
                CastDef castDef = Coordinator.CreateCast(defender);
                var     content = Coordinator.BuildDialogueContent(castDef, "Destroy the tech, let's get outta here!", Color.white);
                defender.Combat.MessageCenter.PublishMessage(new PanicSystemDialogMessage(defender, content, 5));
            }
            else
            {
                defender.EjectPilot(defender.GUID, -1, DeathMethod.PilotEjection, false);
            }

            LogReport("Ejected");
            //LogDebug($"Runtime {stopwatch.Elapsed}");

            if (!modSettings.CountAsKills)
            {
                return;
            }

            //handle weird cases due to damage from all sources
            if (attacker.GUID == defender.GUID)
            {
                //killed himself - possibly mines or made a building land on his own head ;)
                LogReport("Self Kill not counting");
                return;
            }

            if (attacker.team.GUID == defender.team.GUID)
            {
                //killed a friendly
                LogReport("Friendly Fire, Same Team Kill, not counting");
                return;
            }

            if (TurnDamageTracker.EjectionAlreadyCounted(defender))
            {
                return;
            }

            try
            {
                // this seems pretty convoluted
                var attackerPilot = combat.AllMechs.Where(mech => mech.pilot.Team.IsLocalPlayer)
                                    .Where(x => x.PilotableActorDef == attacker.PilotableActorDef).Select(y => y.pilot).FirstOrDefault();

                var statCollection = attackerPilot?.StatCollection;
                if (statCollection == null)
                {
                    return;
                }

                if (defender is Mech)
                {
                    // add UI icons.. and pilot history?   ... MechsKilled already incremented??
                    // TODO count kills recorded on pilot history so it's not applied twice -added a check above should work unless other mods are directly modifying stats
                    statCollection.Set("MechsKilled", attackerPilot.MechsKilled + 1);
                    var stat = statCollection.GetStatistic("MechsEjected");
                    if (stat == null)
                    {
                        statCollection.AddStatistic("MechsEjected", 1);
                    }
                    else
                    {
                        var value = stat.Value <int>();
                        statCollection.Set("MechsEjected", value + 1);
                    }
                }
                else if (modSettings.VehiclesCanPanic &&
                         defender is Vehicle)
                {
                    statCollection.Set("OthersKilled", attackerPilot.OthersKilled + 1);
                    var stat = statCollection.GetStatistic("VehiclesEjected");
                    if (stat == null)
                    {
                        statCollection.AddStatistic("VehiclesEjected", 1);
                        //return;
                    }
                    else
                    {
                        var value = stat.Value <int>();
                        statCollection.Set("VehiclesEjected", value + 1);
                    }
                }

                try
                {
                    object PlayerMechStats = playerMechStatsField.GetValue(CombatProcessor);
                    bool   result          = (bool)tryGetValue.Invoke(PlayerMechStats, new[] { attackerPilot.GUID, mechCombatStats });

                    if (result)
                    {
                        incrementKillCount.Invoke(mechCombatStats, null);
                    }
                }
                catch (Exception e)
                {
                    LogError(e);
                    // add achievement kill (more complicated)
                    var combatProcessors = Traverse.Create(UnityGameInstance.BattleTechGame.Achievements).Field("combatProcessors").GetValue <AchievementProcessor[]>();
                    var combatProcessor  = combatProcessors.FirstOrDefault(x => x.GetType() == AccessTools.TypeByName("BattleTech.Achievements.CombatProcessor"));

                    // field is of type Dictionary<string, CombatProcessor.MechCombatStats>
                    var playerMechStats = Traverse.Create(combatProcessor).Field("playerMechStats").GetValue <IDictionary>();
                    if (playerMechStats != null)
                    {
                        foreach (DictionaryEntry kvp in playerMechStats)
                        {
                            if ((string)kvp.Key == attackerPilot.GUID)
                            {
                                Traverse.Create(kvp.Value).Method("IncrementKillCount").GetValue();
                            }
                        }
                    }
                }


                var r = attackerPilot.StatCollection.GetStatistic("MechsEjected") == null
                        ? 0
                        : attackerPilot.StatCollection.GetStatistic("MechsEjected").Value <int>();
                LogDebug($"{attackerPilot.Callsign} SetMechEjectionCount {r}");

                r = attackerPilot.StatCollection.GetStatistic("VehiclesEjected") == null
                    ? 0
                    : attackerPilot.StatCollection.GetStatistic("VehiclesEjected").Value <int>();
                LogDebug($"{attackerPilot.Callsign} SetVehicleEjectionCount {r}");
            }
            catch (Exception ex)
            {
                LogDebug(ex);
            }
        }
Example #55
0
 public void Update(Coordinator coordinator)
 {
     _context.Coordinators.Update(coordinator);
 }
 public UnsignedShortConverter(IDataProtectionProvider dataProtectionProvider, JsonSerializerOptions options)
     : base(dataProtectionProvider.CreateProtector(_purpose), options, Coordinator.GetByteConverter <ushort>())
 {
 }
Example #57
0
 private void comboBoxEditable_SelectedIndexChanged(object sender, EventArgs e)
 {
     Coordinator.ChangeEditable(this.ListView, (ComboBox)sender);
 }
 private void OnResultUpdated(RetrieveProgressResult result)
 {
     Coordinator.OnResultUpdated(result);
 }
Example #59
0
 protected Coordinator(CoordinatorFactory coordinatorFactory, Coordinator parent, Coordinator next)
 {
     CoordinatorFactory = coordinatorFactory;
     Parent = parent;
     Next = next;
 }
Example #60
0
        public async Task <IActionResult> PostOutputAsync([FromQuery, Required] long roundId, [FromBody, Required] OutputRequest request)
        {
            if (roundId < 0 ||
                request.Level < 0 ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            CcjRound round = Coordinator.TryGetRound(roundId);

            if (round is null)
            {
                TryLogLateRequest(roundId, CcjRoundPhase.OutputRegistration);
                return(NotFound("Round not found."));
            }

            if (round.Status != CcjRoundStatus.Running)
            {
                TryLogLateRequest(roundId, CcjRoundPhase.OutputRegistration);
                return(Gone("Round is not running."));
            }

            CcjRoundPhase phase = round.Phase;

            if (phase != CcjRoundPhase.OutputRegistration)
            {
                TryLogLateRequest(roundId, CcjRoundPhase.OutputRegistration);
                return(Conflict($"Output registration can only be done from OutputRegistration phase. Current phase: {phase}."));
            }

            if (request.OutputAddress.Network != Network)
            {
                // RegTest and TestNet address formats are sometimes the same.
                if (Network == Network.Main)
                {
                    return(BadRequest($"Invalid OutputAddress Network."));
                }
            }

            if (request.OutputAddress == Constants.GetCoordinatorAddress(Network))
            {
                Logger.LogWarning <ChaumianCoinJoinController>($"Bob is registering the coordinator's address. Address: {request.OutputAddress}, Level: {request.Level}, Signature: {request.UnblindedSignature}.");
            }

            if (request.Level > round.MixingLevels.GetMaxLevel())
            {
                return(BadRequest($"Invalid mixing Level is provided. Provided: {request.Level}. Maximum: {round.MixingLevels.GetMaxLevel()}."));
            }

            if (round.ContainsRegisteredUnblindedSignature(request.UnblindedSignature))
            {
                return(NoContent());
            }

            MixingLevel mixinglevel = round.MixingLevels.GetLevel(request.Level);
            Signer      signer      = mixinglevel.Signer;

            if (signer.VerifyUnblindedSignature(request.UnblindedSignature, request.OutputAddress.ScriptPubKey.ToBytes()))
            {
                using (await OutputLock.LockAsync())
                {
                    Bob bob = null;
                    try
                    {
                        bob = new Bob(request.OutputAddress, mixinglevel);
                        round.AddBob(bob);
                        round.AddRegisteredUnblindedSignature(request.UnblindedSignature);
                    }
                    catch (Exception ex)
                    {
                        return(BadRequest($"Invalid outputAddress is provided. Details: {ex.Message}"));
                    }

                    int bobCount      = round.CountBobs();
                    int blindSigCount = round.CountBlindSignatures();
                    if (bobCount == blindSigCount)                     // If there'll be more bobs, then round failed. Someone may broke the crypto.
                    {
                        await round.ExecuteNextPhaseAsync(CcjRoundPhase.Signing);
                    }
                }

                return(NoContent());
            }
            return(BadRequest("Invalid signature provided."));
        }