Esempio n. 1
0
 public void IsDisconnected_should_return_true_when_not_connected()
 {
     using (var requester = new Requester())
     {
         Assert.IsTrue(requester.IsDisconnected);
     }
 }
Esempio n. 2
0
 private void TryLoggingIn()
 {
     _singleton.CurrentUsername = Username;
     _singleton.CurrentPassword = Password;
     var requester = new Requester();
     requester.LogIn();
 }
Esempio n. 3
0
        public MainWindow()
        {
            InitializeComponent();
            AdjustTreeWidth();
            this.MinWidth = this.Width;
            this.MinHeight = 500;
            requester = new Requester("http://snf-185147.vm.okeanos.grnet.gr:8080/qorderws/orders/business/1/order?status=PENDING");
            //requester = new Requester("http://83.212.118.113/mockJsons/mockCategoryJson.json");

            requesterThread = new Thread(
                o =>
                {
                    while (true)
                    {
                        while (!requester.Flag)
                        {
                            requester.Update();
                        }
                        requester.Flag = false;
                        this.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            foreach (Order order in requester.orders)
                            {
                                DynamicVisualTemplate mock1 = new DynamicVisualTemplate(order);
                                mock1.removeEvent += removeOrderEvent;
                                this.InboxView.Items.Add(mock1.OrderTemplate);
                            }
                            this.InboxCounter.Content = this.InboxView.Items.Count;
                        }));
                    }
                });
            requesterThread.Start();

        }
Esempio n. 4
0
        public static AuthInfo Authorization(string login, string password)
        {
            ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
            var requester = new Requester(new AuthRequest(login, password));

            return requester.GetResponse<AuthInfo>();
        }
 public static void Main()
 {
     ICommandManager commandManager = new CommandManager();
     IUserInterface userInterface = new ConsoleInterface();
     IRequester requester = new Requester();
    
     var engine = new GameEngine(userInterface, commandManager, requester);
     engine.Run();
 }
Esempio n. 6
0
 private static Document SaveFile(string accessToken, UploadedFileInfo uploadedFileInfo, string title)
 {
     var requester = new Requester(new SaveDocumentRequest(accessToken, uploadedFileInfo.Info, title));
     var documentsCollection = requester.GetResponse<IList<Document>>();
     if (documentsCollection.Count == 0)
     {
         throw new NotSavedFileException(title);
     }
     return documentsCollection[0];
 }
        private async void ExecuteLoginCommand()
        {
            Requester requester = new Requester();

            UserRequestModel requestModel = new UserRequestModel
            {
                UserName = this.UserName,
                Password = Password
            };

            string requestBody = JsonConvert.SerializeObject(requestModel);

            HttpStringContent requestContent = new HttpStringContent(requestBody, UnicodeEncoding.Utf8, "application/json");

            string response = string.Empty;

            try
            {
                response = await requester.PutJsonAsync("/api/users/token", requestContent);
            }
            catch (Exception)
            {
                MessageDialogNotifier.Notify("There was an error on the server. Please contact the server administrators.");
            }

            UserResponseModel user = JsonConvert.DeserializeObject<UserResponseModel>(response);

            if (string.IsNullOrEmpty(user.UserName) || 
                string.IsNullOrEmpty(user.Token))
            {
                MessageDialogNotifier.Notify("Invalid username or password.");
            }
            else
            {
                Data data = new Data();

                UserDatabaseModel databaseUser = new UserDatabaseModel
                {
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Id = user.Id,
                    RegistrationDate = user.RegistrationDate,
                    UserName = user.UserName,
                    Token = user.Token
                };

                await data.UpdateCurrentUserAsync(databaseUser);

                UserDatabaseModel currentUser = await data.GetCurrentUser();

                MessageDialogNotifier.Notify(string.Format("Hello {0} {1}!\nYou are now logged in.", currentUser.FirstName, currentUser.LastName));
            }
        }
Esempio n. 8
0
        public void Connect_with_timeout_to_non_existing_endpoint_should_throw_TimeoutException()
        {
            using (var requester = new Requester())
            {
                var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp);

                var sw = Stopwatch.StartNew();

                Assert.Throws<TimeoutException>(() =>
                    requester.Connect(endpoint, TimeSpan.FromMilliseconds(100)));

                sw.Stop();
                Assert.GreaterOrEqual(sw.ElapsedMilliseconds, 100);
            }
        }
		public void Typed_Bad_DiscardResponse(object responseValue)
		{
			using (var request = new Requester<StandardResponse>(
				responseValue,
				settings => settings.ExposeRawResponse(false),
				(settings, stream) => FakeResponse.Bad(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				Assert.IsNull(r.Response);
				r.ResponseRaw.Should().BeNull();

			}
		}
Esempio n. 10
0
        public Client(Credentials credentials) {
            if (credentials == null) throw new ArgumentNullException("credentials");
            requester = new Requester(credentials);

            Account = new AccountResource(requester);
            Balance = new BalanceResource(requester);
            Cards = new CardResourceShim(requester);
            Charges = new ChargeResource(requester);
            Customers = new CustomerResource(requester);
            Disputes = new DisputeResource(requester);
            Events = new EventResource(requester);
            Recipients = new RecipientResource(requester);
            Refunds = new RefundResourceShim(requester);
            Tokens = new TokenResource(requester);
            Transactions = new TransactionResource(requester);
            Transfers = new TransferResource(requester);
        }
Esempio n. 11
0
        public void Requester_Request_should_obey_ReceiveTimeout_in_socket_configuration_and_throw_IOException()
        {
            using (var responder = TestHelpers.CreateTestResponder(1000))
            using (var requester = new Requester())
            {
                var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp);
                var socketConfiguration = new SocketConfiguration { ReceiveTimeout = TimeSpan.FromMilliseconds(100) };

                responder.Bind(endpoint);
                requester.Connect(endpoint, socketConfiguration);

                var disconnected = new ManualResetEventSlim();
                requester.Disconnected += disconnected.Set;

                Assert.Throws<IOException>(() => requester.Request(new TestMessage()));
            }
        }
		public void Typed_Ok_KeepResponse(object responseValue)
		{
			using (var request = new Requester<StandardResponse>(
				responseValue,
				settings => settings.ExposeRawResponse(true),
				(settings, stream) => FakeResponse.Ok(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeTrue();
				object v = r.Response.value;

				v.ShouldBeEquivalentTo(responseValue);
				r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);

			}
		}
        public async void GetAllRoomsAsync()
        {
            Requester requester = new Requester();

            Data data = new Data();

            UserDatabaseModel currentUser = await Data.GetCurrentUser();

            if (currentUser == null || string.IsNullOrEmpty(currentUser.Token))
            {
                MessageDialogNotifier.Notify("You must be logged in to get all rooms.");
                return;
            }

            string result = string.Empty;

            try
            {
                result = await requester.GetJsonAsync("/api/roomGeometry", currentUser.Token);
            }
            catch (Exception)
            {
                MessageDialogNotifier.Notify("You must be logged in to get all rooms.");
                return;
            }

            IEnumerable<RoomResponseModel> allRoomsResponseModels = JsonConvert.DeserializeObject<IEnumerable<RoomResponseModel>>(result);

            if (allRoomsResponseModels == null || allRoomsResponseModels.Count() <= 0)
            {
                MessageDialogNotifier.Notify("You must be logged in to get all rooms.");
                return;
            }

            if (allRoomsResponseModels != null)
            {
                allRoomsResponseModels
                           .Select(r => r.Room)
                           .ToList()
                           .ForEach(r =>
                           {
                               this.allRooms.Add(r);
                           });
            }
        }
Esempio n. 14
0
        public void RequestAsync_Cancel_single_message(RedFoxTransport transport)
        {
            using (var responder = TestHelpers.CreateTestResponder(1000))
            using (var requester = new Requester())
            {
                var endpoint = TestHelpers.CreateEndpointForTransport(transport);

                responder.Bind(endpoint);

                requester.Connect(endpoint);

                Thread.Sleep(100);

                var messageSent = new TestMessage { Text = "Hello" };
                var cancellationToken = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)).Token;
                Assert.Throws<AggregateException>(() => requester.RequestAsync(messageSent, cancellationToken).Wait());
            }
        }
Esempio n. 15
0
        public void Subscribe_to_Responder_should_cause_protocol_exception(RedFoxTransport transport)
        {
            using (var publisher = new Publisher())
            using (var requester = new Requester())
            {
                var endpoint = TestHelpers.CreateEndpointForTransport(transport);

                publisher.Bind(endpoint);

                try
                {
                    requester.Connect(endpoint);
                }
                catch (AggregateException ex)
                {
                    throw ex.InnerExceptions.First();
                }
            }
        }
	protected void Page_Load(object sender, EventArgs e)
	{
		string activationKey = Request["ActivationKey"];
		if (string.IsNullOrEmpty(activationKey))
		{
			ShowAccessDenied();
			return;
		}

		requester = PasswordRecovery.RetrieveByActivationKey(activationKey);
		
		if (requester == null)
		{
			ShowAccessDenied();
			return;
		}
		
		requesterName.Text = string.Format("{0} {1}", requester.FirstName, requester.LastName);
	}
Esempio n. 17
0
        public void RequestAsync_Response_single_message(RedFoxTransport transport)
        {
            using (var responder = TestHelpers.CreateTestResponder())
            using (var requester = new Requester())
            {
                var endpoint = TestHelpers.CreateEndpointForTransport(transport);

                responder.Bind(endpoint);

                requester.Connect(endpoint);

                Thread.Sleep(100);

                var messageSent = new TestMessage { Text = "Hello" };
                var messageReceived = (TestMessage)requester.RequestAsync(messageSent).Result;

                Assert.AreEqual(messageSent.Text, messageReceived.Text);
            }
        }
Esempio n. 18
0
	private void PerformLogin(Requester requester)
	{
		Response.Cookies.Remove(Globals.LOGIN_COOKIE);
		Response.Cookies.Remove(Globals.PASSWORD_COOKIE);

		DataPortal.Instance.ResetCachedValue(typeof(Requester), requester.ID);

		FormsAuthentication.RedirectFromLoginPage(requester.ID.GetValueOrDefault().ToString(CultureInfo.InvariantCulture), RememberMe.Checked);

		if (RememberMe.Checked)
		{
			var authCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
			if (authCookie != null)
			{
				authCookie.Expires = authCookie.Expires.AddMinutes(20130);
			}
		}

		Globals.IsLogOut = false;
	}
Esempio n. 19
0
        public async void TestRequest() {
            var expectedAuthHeader = DummyCredentials.SecretKey.EncodeForAuthorizationHeader();
            var roundtripper = new MockRoundtripper((req) => {
                    var authHeader = req.Headers.GetValues("Authorization").FirstOrDefault();
                    Assert.AreEqual(expectedAuthHeader, authHeader);

                    var libVersion = new AssemblyName(typeof(Requester).Assembly.FullName).Version.ToString();
                    var clrVersion = new AssemblyName(typeof(object).Assembly.FullName).Version.ToString();

                    var userAgents = req.Headers.GetValues("User-Agent").ToList();
                    Assert.Contains("Omise.Net/" + libVersion, userAgents);
                    Assert.Contains(".Net/" + clrVersion, userAgents);

                    var apiVersion = req.Headers.GetValues("Omise-Version").FirstOrDefault();
                    Assert.AreEqual("2000-02-01", apiVersion);
                });
                
            var requester = new Requester(DummyCredentials, roundtripper, "2000-02-01");
            await requester.Request<object>(Endpoint.Api, "GET", "/test");

            Assert.AreEqual(1, roundtripper.RoundtripCount);
        }
Esempio n. 20
0
        public void unbind_disconnects_client()
        {
            using (var responder = TestHelpers.CreateTestResponder())
            using (var requester = new Requester())
            {
                var endpoint = new RedFoxEndpoint("/path");

                var connected = new ManualResetEventSlim();
                var disconnected = new ManualResetEventSlim();

                responder.ClientConnected += (s, c) => connected.Set();
                responder.ClientDisconnected += s => disconnected.Set();

                responder.Bind(endpoint);
                requester.Connect(endpoint);

                Assert.IsTrue(connected.Wait(TimeSpan.FromSeconds(1)));

                responder.Unbind(endpoint);

                Assert.IsTrue(disconnected.Wait(TimeSpan.FromSeconds(1)));
            }
        }
        public void One_Responder_1_Requester()
        {
            var echoWorker = new ResponderWorker();
            var workerFactory = new ResponderWorkerFactory(request => echoWorker);
            using (var responder = new Responder(workerFactory))
            using (var requester = new Requester())
            {
                var endpoint = GetEndpoint();
                responder.Bind(endpoint);
                requester.Connect(endpoint);

                Thread.Sleep(100);

                var sw = Stopwatch.StartNew();
                var messageSent = new TestMessage();
                for (var i = 0; i < NumberOfRequests; i++)
                {
                    requester.Request(messageSent);
                }
                sw.Stop();

                Assert.Inconclusive("{0} elapsed sending/receiving {1} messages ({2:N0} per second)", sw.Elapsed, NumberOfRequests, NumberOfRequests / sw.Elapsed.TotalSeconds);
            }
        }
Esempio n. 22
0
 public static uint256 BlindMessage(this Requester requester, uint256 messageHash, SchnorrPubKey schnorrPubKey) => requester.BlindMessage(messageHash, schnorrPubKey.RpubKey, schnorrPubKey.SignerPubKey);
		public void String_Bad_KeepResponse(object responseValue)
		{
			using (var request = new Requester<string>(
				responseValue,
				settings => settings.ExposeRawResponse(true),
				(settings, stream) => FakeResponse.Bad(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
				r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
			}
		}
		public void DynamicDictionary_Bad_KeepResponse(object responseValue)
		{
			using (var request = new Requester<DynamicDictionary>(
				responseValue,
				settings => settings.ExposeRawResponse(true),
				(settings, stream) => FakeResponse.Bad(settings, response: stream),
				client => client.Info()
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				Assert.IsNull(r.Response);
				r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);

			}
		}
Esempio n. 25
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as ProcedureRequest;

            if (dest == null)
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }

            base.CopyTo(dest);
            if (Identifier != null)
            {
                dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
            }
            if (Definition != null)
            {
                dest.Definition = new List <Hl7.Fhir.Model.ResourceReference>(Definition.DeepCopy());
            }
            if (BasedOn != null)
            {
                dest.BasedOn = new List <Hl7.Fhir.Model.ResourceReference>(BasedOn.DeepCopy());
            }
            if (Replaces != null)
            {
                dest.Replaces = new List <Hl7.Fhir.Model.ResourceReference>(Replaces.DeepCopy());
            }
            if (Requisition != null)
            {
                dest.Requisition = (Hl7.Fhir.Model.Identifier)Requisition.DeepCopy();
            }
            if (StatusElement != null)
            {
                dest.StatusElement = (Code <Hl7.Fhir.Model.RequestStatus>)StatusElement.DeepCopy();
            }
            if (IntentElement != null)
            {
                dest.IntentElement = (Code <Hl7.Fhir.Model.RequestIntent>)IntentElement.DeepCopy();
            }
            if (PriorityElement != null)
            {
                dest.PriorityElement = (Code <Hl7.Fhir.Model.RequestPriority>)PriorityElement.DeepCopy();
            }
            if (DoNotPerformElement != null)
            {
                dest.DoNotPerformElement = (Hl7.Fhir.Model.FhirBoolean)DoNotPerformElement.DeepCopy();
            }
            if (Category != null)
            {
                dest.Category = new List <Hl7.Fhir.Model.CodeableConcept>(Category.DeepCopy());
            }
            if (Code != null)
            {
                dest.Code = (Hl7.Fhir.Model.CodeableConcept)Code.DeepCopy();
            }
            if (Subject != null)
            {
                dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
            }
            if (Context != null)
            {
                dest.Context = (Hl7.Fhir.Model.ResourceReference)Context.DeepCopy();
            }
            if (Occurrence != null)
            {
                dest.Occurrence = (Hl7.Fhir.Model.Element)Occurrence.DeepCopy();
            }
            if (AsNeeded != null)
            {
                dest.AsNeeded = (Hl7.Fhir.Model.Element)AsNeeded.DeepCopy();
            }
            if (AuthoredOnElement != null)
            {
                dest.AuthoredOnElement = (Hl7.Fhir.Model.FhirDateTime)AuthoredOnElement.DeepCopy();
            }
            if (Requester != null)
            {
                dest.Requester = (Hl7.Fhir.Model.ProcedureRequest.RequesterComponent)Requester.DeepCopy();
            }
            if (PerformerType != null)
            {
                dest.PerformerType = (Hl7.Fhir.Model.CodeableConcept)PerformerType.DeepCopy();
            }
            if (Performer != null)
            {
                dest.Performer = (Hl7.Fhir.Model.ResourceReference)Performer.DeepCopy();
            }
            if (ReasonCode != null)
            {
                dest.ReasonCode = new List <Hl7.Fhir.Model.CodeableConcept>(ReasonCode.DeepCopy());
            }
            if (ReasonReference != null)
            {
                dest.ReasonReference = new List <Hl7.Fhir.Model.ResourceReference>(ReasonReference.DeepCopy());
            }
            if (SupportingInfo != null)
            {
                dest.SupportingInfo = new List <Hl7.Fhir.Model.ResourceReference>(SupportingInfo.DeepCopy());
            }
            if (Specimen != null)
            {
                dest.Specimen = new List <Hl7.Fhir.Model.ResourceReference>(Specimen.DeepCopy());
            }
            if (BodySite != null)
            {
                dest.BodySite = new List <Hl7.Fhir.Model.CodeableConcept>(BodySite.DeepCopy());
            }
            if (Note != null)
            {
                dest.Note = new List <Hl7.Fhir.Model.Annotation>(Note.DeepCopy());
            }
            if (RelevantHistory != null)
            {
                dest.RelevantHistory = new List <Hl7.Fhir.Model.ResourceReference>(RelevantHistory.DeepCopy());
            }
            return(dest);
        }
Esempio n. 26
0
        /// <summary>
        /// Run the given argument list (as taken directly from a request) with the given module for the given requester. Parses the arglist,
        /// finds the module, runs the command and returns the output. Things like sending messages to other users is also performed, but
        /// against the database and in the background
        /// </summary>
        /// <param name="module"></param>
        /// <param name="arglist"></param>
        /// <param name="requester"></param>
        /// <returns></returns>
        public string RunCommand(string module, string arglist, Requester requester, long parentId = 0)
        {
            LoadedModule mod = GetModule(module);

            if (mod == null)
            {
                throw new BadRequestException($"No module with name {module}");
            }

            arglist = arglist?.Trim();

            //By DEFAULT, we call the default function with whatever is leftover in the arglist
            var           cmdfuncname = config.DefaultFunction;
            List <object> scriptArgs  = new List <object> {
                requester.userId
            };                                                               //Args always includes the calling user first

            //Can only check for subcommands if there's an argument list!
            if (arglist != null)
            {
                var match = Regex.Match(arglist, @"^\s*(\w+)\s*(.*)$");

                //NOTE: Subcommand currently case sensitive!
                if (match.Success)
                {
                    var newArglist = match.Groups[2].Value.Trim();
                    ModuleSubcommandInfo subcommandInfo = null;
                    mod.subcommands.TryGetValue(match.Groups[1].Value, out subcommandInfo); //ParseSubcommandInfo(mod, match.Groups[1].Value);

                    //Special re-check: sometimes, we can have commands that have NO subcommand name, or the "blank" subcommand. Try that one.
                    if (subcommandInfo == null) //subcommandExists == true)
                    {
                        newArglist = arglist;   //undo the parsing
                        mod.subcommands.TryGetValue("", out subcommandInfo);
                        //subcommandInfo = ParseSubcommandInfo(mod, "");
                    }

                    //There is a defined subcommand, which means we may need to parse the input and call
                    //a different function than the default!
                    if (subcommandInfo != null) //subcommandExists == true) //subcommandInfo != null)
                    {
                        arglist     = newArglist;
                        cmdfuncname = subcommandInfo.FunctionName;

                        //Arguments were defined! From this point on, we're being VERY strict with parsing! This could throw exceptions!
                        if (subcommandInfo.Arguments != null)
                        {
                            ParseArgs(subcommandInfo, arglist, scriptArgs);
                        }
                    }
                }
            }

            if (!mod.script.Globals.Keys.Any(x => x.String == cmdfuncname))
            {
                throw new BadRequestException($"Command function '{cmdfuncname}' not found in module {module}");
            }

            //Oops, didn't fill up the arglist with anything! Careful, this is dangerous!
            if (scriptArgs.Count == 1)
            {
                scriptArgs.Add(arglist);
            }

            //We lock so nobody else can run commands while we're running them. This guarantees thread safety
            //within the modules so they don't have to worry about it.
            lock (moduleLocks.GetOrAdd(module, s => new object()))
            {
                using (mod.dataConnection = new SqliteConnection(config.ModuleDataConnectionString))
                {
                    mod.dataConnection.Open();
                    mod.currentRequester = requester;
                    mod.currentFunction  = cmdfuncname;
                    mod.currentParentId  = parentId;
                    mod.currentArgs      = arglist;
                    DynValue res = mod.script.Call(mod.script.Globals[cmdfuncname], scriptArgs.ToArray());
                    return(res.String);
                }
            }
        }
Esempio n. 27
0
        public override ErrorList Validate()
        {
            var result = new ErrorList();

            result.AddRange(base.Validate());

            if (TypeElement != null)
            {
                result.AddRange(TypeElement.Validate());
            }
            if (Subtype != null)
            {
                result.AddRange(Subtype.Validate());
            }
            if (Identifier != null)
            {
                Identifier.ForEach(elem => result.AddRange(elem.Validate()));
            }
            if (DateTimeElement != null)
            {
                result.AddRange(DateTimeElement.Validate());
            }
            if (Subject != null)
            {
                result.AddRange(Subject.Validate());
            }
            if (Requester != null)
            {
                result.AddRange(Requester.Validate());
            }
            if (Operator != null)
            {
                result.AddRange(Operator.Validate());
            }
            if (View != null)
            {
                result.AddRange(View.Validate());
            }
            if (DeviceNameElement != null)
            {
                result.AddRange(DeviceNameElement.Validate());
            }
            if (HeightElement != null)
            {
                result.AddRange(HeightElement.Validate());
            }
            if (WidthElement != null)
            {
                result.AddRange(WidthElement.Validate());
            }
            if (FramesElement != null)
            {
                result.AddRange(FramesElement.Validate());
            }
            if (LengthElement != null)
            {
                result.AddRange(LengthElement.Validate());
            }
            if (Content != null)
            {
                result.AddRange(Content.Validate());
            }

            return(result);
        }
Esempio n. 28
0
 public string RunCommand(string module, string command, string data, Requester requester)
 {
     return("Not implemented");
 }
Esempio n. 29
0
        private async Task TryRegisterCoinsAsync(CcjClientRound inputRegistrableRound)
        {
            try
            {
                // Select the most suitable coins to regiter.
                List <TxoRef> registrableCoins = State.GetRegistrableCoins(
                    inputRegistrableRound.State.MaximumInputCountPerPeer,
                    inputRegistrableRound.State.Denomination,
                    inputRegistrableRound.State.FeePerInputs,
                    inputRegistrableRound.State.FeePerOutputs).ToList();

                // If there are no suitable coins to register return.
                if (!registrableCoins.Any())
                {
                    return;
                }

                (HdPubKey change, IEnumerable <HdPubKey> actives)outputAddresses = GetOutputsToRegister(inputRegistrableRound.State.Denomination, inputRegistrableRound.State.SchnorrPubKeys.Count(), registrableCoins);

                SchnorrPubKey[]  schnorrPubKeys = inputRegistrableRound.State.SchnorrPubKeys.ToArray();
                List <Requester> requesters     = new List <Requester>();
                var blindedOutputScriptHashes   = new List <uint256>();

                var registeredAddresses = new List <BitcoinAddress>();
                for (int i = 0; i < schnorrPubKeys.Length; i++)
                {
                    if (outputAddresses.actives.Count() <= i)
                    {
                        break;
                    }

                    BitcoinAddress address = outputAddresses.actives.Select(x => x.GetP2wpkhAddress(Network)).ElementAt(i);

                    SchnorrPubKey schnorrPubKey           = schnorrPubKeys[i];
                    var           outputScriptHash        = new uint256(Hashes.SHA256(address.ScriptPubKey.ToBytes()));
                    var           requester               = new Requester();
                    uint256       blindedOutputScriptHash = requester.BlindMessage(outputScriptHash, schnorrPubKey);
                    requesters.Add(requester);
                    blindedOutputScriptHashes.Add(blindedOutputScriptHash);
                    registeredAddresses.Add(address);
                }

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

                var inputProofs = new List <InputProofModel>();
                foreach (TxoRef coinReference in registrableCoins)
                {
                    SmartCoin coin = State.GetSingleOrDefaultFromWaitingList(coinReference);
                    if (coin is null)
                    {
                        throw new NotSupportedException("This is impossible.");
                    }

                    coin.Secret = coin.Secret ?? KeyManager.GetSecrets(SaltSoup(), coin.ScriptPubKey).Single();
                    var inputProof = new InputProofModel {
                        Input = coin.GetTxoRef(),
                        Proof = coin.Secret.PrivateKey.SignCompact(blindedOutputScriptsHash)
                    };
                    inputProofs.Add(inputProof);
                }

                AliceClient aliceClient = null;
                try
                {
                    aliceClient = await AliceClient.CreateNewAsync(inputRegistrableRound.RoundId, registeredAddresses, schnorrPubKeys, requesters, Network, outputAddresses.change.GetP2wpkhAddress(Network), blindedOutputScriptHashes, inputProofs, CcjHostUriAction, TorSocks5EndPoint);
                }
                catch (HttpRequestException ex) when(ex.Message.Contains("Input is banned", StringComparison.InvariantCultureIgnoreCase))
                {
                    string[] parts             = ex.Message.Split(new[] { "Input is banned from participation for ", " minutes: " }, StringSplitOptions.RemoveEmptyEntries);
                    string   minutesString     = parts[1];
                    int      minuteInt         = int.Parse(minutesString);
                    string   bannedInputString = parts[2].TrimEnd('.');

                    string[]  bannedInputStringParts = bannedInputString.Split(':', StringSplitOptions.RemoveEmptyEntries);
                    TxoRef    coinReference          = new TxoRef(new uint256(bannedInputStringParts[1]), uint.Parse(bannedInputStringParts[0]));
                    SmartCoin coin = State.GetSingleOrDefaultFromWaitingList(coinReference);

                    if (coin is null)
                    {
                        throw new NotSupportedException("This is impossible.");
                    }

                    coin.BannedUntilUtc = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(minuteInt);

                    Logger.LogWarning <CcjClient>(ex.Message.Split('\n')[1]);

                    await DequeueCoinsFromMixNoLockAsync(coinReference, "Failed to register the coin with the coordinator.");

                    aliceClient?.Dispose();
                    return;
                }
                catch (HttpRequestException ex) when(ex.Message.Contains("Provided input is not unspent", StringComparison.InvariantCultureIgnoreCase))
                {
                    string[] parts            = ex.Message.Split(new[] { "Provided input is not unspent: " }, StringSplitOptions.RemoveEmptyEntries);
                    string   spentInputString = parts[1].TrimEnd('.');

                    string[]  bannedInputStringParts = spentInputString.Split(':', StringSplitOptions.RemoveEmptyEntries);
                    TxoRef    coinReference          = new TxoRef(new uint256(bannedInputStringParts[1]), uint.Parse(bannedInputStringParts[0]));
                    SmartCoin coin = State.GetSingleOrDefaultFromWaitingList(coinReference);

                    if (coin is null)
                    {
                        throw new NotSupportedException("This is impossible.");
                    }

                    coin.SpentAccordingToBackend = true;

                    Logger.LogWarning <CcjClient>(ex.Message.Split('\n')[1]);

                    await DequeueCoinsFromMixNoLockAsync(coinReference, "Failed to register the coin with the coordinator. The coin is already spent.");

                    aliceClient?.Dispose();
                    return;
                }
                catch (HttpRequestException ex) when(ex.Message.Contains("No such running round in InputRegistration.", StringComparison.InvariantCultureIgnoreCase))
                {
                    Logger.LogInfo <CcjClient>("Client tried to register a round that isn't in InputRegistration anymore. Trying again later.");
                    aliceClient?.Dispose();
                    return;
                }
                catch (HttpRequestException ex) when(ex.Message.Contains("too-long-mempool-chain", StringComparison.InvariantCultureIgnoreCase))
                {
                    Logger.LogInfo <CcjClient>("Coordinator failed because too much unconfirmed parent transactions. Trying again later.");
                    aliceClient?.Dispose();
                    return;
                }

                var coinsRegistered = new List <SmartCoin>();
                foreach (TxoRef coinReference in registrableCoins)
                {
                    var coin = State.GetSingleOrDefaultFromWaitingList(coinReference);
                    if (coin is null)
                    {
                        throw new NotSupportedException("This is impossible.");
                    }

                    coinsRegistered.Add(coin);
                    State.RemoveCoinFromWaitingList(coin);
                }

                var registration = new ClientRoundRegistration(aliceClient, coinsRegistered, outputAddresses.change.GetP2wpkhAddress(Network));

                CcjClientRound roundRegistered = State.GetSingleOrDefaultRound(aliceClient.RoundId);
                if (roundRegistered is null)
                {
                    // If our SatoshiClient doesn't yet know about the round, because of delay, then delay the round registration.
                    DelayedRoundRegistration?.Dispose();
                    DelayedRoundRegistration = registration;
                }

                roundRegistered.Registration = registration;
            }
            catch (Exception ex)
            {
                Logger.LogError <CcjClient>(ex);
            }
        }
Esempio n. 30
0
 public SchemaEndpoint(Requester requester)
 {
     this.requester = requester;
 }
Esempio n. 31
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as DeviceRequest;

            if (dest == null)
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }

            base.CopyTo(dest);
            if (Identifier != null)
            {
                dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
            }
            if (Definition != null)
            {
                dest.Definition = new List <Hl7.Fhir.Model.ResourceReference>(Definition.DeepCopy());
            }
            if (BasedOn != null)
            {
                dest.BasedOn = new List <Hl7.Fhir.Model.ResourceReference>(BasedOn.DeepCopy());
            }
            if (PriorRequest != null)
            {
                dest.PriorRequest = new List <Hl7.Fhir.Model.ResourceReference>(PriorRequest.DeepCopy());
            }
            if (GroupIdentifier != null)
            {
                dest.GroupIdentifier = (Hl7.Fhir.Model.Identifier)GroupIdentifier.DeepCopy();
            }
            if (StatusElement != null)
            {
                dest.StatusElement = (Code <Hl7.Fhir.Model.RequestStatus>)StatusElement.DeepCopy();
            }
            if (Intent != null)
            {
                dest.Intent = (Hl7.Fhir.Model.CodeableConcept)Intent.DeepCopy();
            }
            if (PriorityElement != null)
            {
                dest.PriorityElement = (Code <Hl7.Fhir.Model.RequestPriority>)PriorityElement.DeepCopy();
            }
            if (Code != null)
            {
                dest.Code = (Hl7.Fhir.Model.DataType)Code.DeepCopy();
            }
            if (Subject != null)
            {
                dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
            }
            if (Context != null)
            {
                dest.Context = (Hl7.Fhir.Model.ResourceReference)Context.DeepCopy();
            }
            if (Occurrence != null)
            {
                dest.Occurrence = (Hl7.Fhir.Model.DataType)Occurrence.DeepCopy();
            }
            if (AuthoredOnElement != null)
            {
                dest.AuthoredOnElement = (Hl7.Fhir.Model.FhirDateTime)AuthoredOnElement.DeepCopy();
            }
            if (Requester != null)
            {
                dest.Requester = (Hl7.Fhir.Model.DeviceRequest.RequesterComponent)Requester.DeepCopy();
            }
            if (PerformerType != null)
            {
                dest.PerformerType = (Hl7.Fhir.Model.CodeableConcept)PerformerType.DeepCopy();
            }
            if (Performer != null)
            {
                dest.Performer = (Hl7.Fhir.Model.ResourceReference)Performer.DeepCopy();
            }
            if (ReasonCode != null)
            {
                dest.ReasonCode = new List <Hl7.Fhir.Model.CodeableConcept>(ReasonCode.DeepCopy());
            }
            if (ReasonReference != null)
            {
                dest.ReasonReference = new List <Hl7.Fhir.Model.ResourceReference>(ReasonReference.DeepCopy());
            }
            if (SupportingInfo != null)
            {
                dest.SupportingInfo = new List <Hl7.Fhir.Model.ResourceReference>(SupportingInfo.DeepCopy());
            }
            if (Note != null)
            {
                dest.Note = new List <Hl7.Fhir.Model.Annotation>(Note.DeepCopy());
            }
            if (RelevantHistory != null)
            {
                dest.RelevantHistory = new List <Hl7.Fhir.Model.ResourceReference>(RelevantHistory.DeepCopy());
            }
            return(dest);
        }
Esempio n. 32
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as Immunization;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (DateElement != null)
                {
                    dest.DateElement = (Hl7.Fhir.Model.FhirDateTime)DateElement.DeepCopy();
                }
                if (VaccineType != null)
                {
                    dest.VaccineType = (Hl7.Fhir.Model.CodeableConcept)VaccineType.DeepCopy();
                }
                if (Subject != null)
                {
                    dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
                }
                if (RefusedIndicatorElement != null)
                {
                    dest.RefusedIndicatorElement = (Hl7.Fhir.Model.FhirBoolean)RefusedIndicatorElement.DeepCopy();
                }
                if (ReportedElement != null)
                {
                    dest.ReportedElement = (Hl7.Fhir.Model.FhirBoolean)ReportedElement.DeepCopy();
                }
                if (Performer != null)
                {
                    dest.Performer = (Hl7.Fhir.Model.ResourceReference)Performer.DeepCopy();
                }
                if (Requester != null)
                {
                    dest.Requester = (Hl7.Fhir.Model.ResourceReference)Requester.DeepCopy();
                }
                if (Manufacturer != null)
                {
                    dest.Manufacturer = (Hl7.Fhir.Model.ResourceReference)Manufacturer.DeepCopy();
                }
                if (Location != null)
                {
                    dest.Location = (Hl7.Fhir.Model.ResourceReference)Location.DeepCopy();
                }
                if (LotNumberElement != null)
                {
                    dest.LotNumberElement = (Hl7.Fhir.Model.FhirString)LotNumberElement.DeepCopy();
                }
                if (ExpirationDateElement != null)
                {
                    dest.ExpirationDateElement = (Hl7.Fhir.Model.Date)ExpirationDateElement.DeepCopy();
                }
                if (Site != null)
                {
                    dest.Site = (Hl7.Fhir.Model.CodeableConcept)Site.DeepCopy();
                }
                if (Route != null)
                {
                    dest.Route = (Hl7.Fhir.Model.CodeableConcept)Route.DeepCopy();
                }
                if (DoseQuantity != null)
                {
                    dest.DoseQuantity = (Hl7.Fhir.Model.Quantity)DoseQuantity.DeepCopy();
                }
                if (Explanation != null)
                {
                    dest.Explanation = (Hl7.Fhir.Model.Immunization.ImmunizationExplanationComponent)Explanation.DeepCopy();
                }
                if (Reaction != null)
                {
                    dest.Reaction = new List <Hl7.Fhir.Model.Immunization.ImmunizationReactionComponent>(Reaction.DeepCopy());
                }
                if (VaccinationProtocol != null)
                {
                    dest.VaccinationProtocol = new List <Hl7.Fhir.Model.Immunization.ImmunizationVaccinationProtocolComponent>(VaccinationProtocol.DeepCopy());
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
Esempio n. 33
0
        private Requester CreateRequester()
        {
            var requester = new Requester(this.httpClient);

            if (this.RequestBodySerializer is RequestBodySerializer requestBodySerializer)
            {
                requester.RequestBodySerializer = requestBodySerializer;
            }
            else if (this.RequestBodySerializer != null)
            {
                requester.RequestBodySerializer = new RequestBodySerializerWrapper(this.RequestBodySerializer);
            }
            else if (this.JsonSerializerSettings != null)
            {
                requester.RequestBodySerializer = new JsonRequestBodySerializer()
                {
                    JsonSerializerSettings = this.JsonSerializerSettings
                }
            }
            ;

            requester.RequestPathParamSerializer = this.RequestPathParamSerializer;

            if (this.RequestQueryParamSerializer is RequestQueryParamSerializer requestQueryParamSerializer)
            {
                requester.RequestQueryParamSerializer = requestQueryParamSerializer;
            }
            else if (this.RequestQueryParamSerializer != null)
            {
                requester.RequestQueryParamSerializer = new RequestQueryParamSerializerWrapper(this.RequestQueryParamSerializer);
            }
            else if (this.JsonSerializerSettings != null)
            {
                requester.RequestQueryParamSerializer = new JsonRequestQueryParamSerializer()
                {
                    JsonSerializerSettings = this.JsonSerializerSettings
                }
            }
            ;

            if (this.ResponseDeserializer is ResponseDeserializer responseDeserializer)
            {
                requester.ResponseDeserializer = responseDeserializer;
            }
            else if (this.ResponseDeserializer != null)
            {
                requester.ResponseDeserializer = new ResponseDeserializerWrapper(this.ResponseDeserializer);
            }
            else if (this.JsonSerializerSettings != null)
            {
                requester.ResponseDeserializer = new JsonResponseDeserializer()
                {
                    JsonSerializerSettings = this.JsonSerializerSettings
                }
            }
            ;

            requester.QueryStringBuilder = this.QueryStringBuilder;

            requester.FormatProvider = this.FormatProvider;

            return(requester);
        }
        public async Task GetInstrumentsAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("GetInstrumentsAsync started {now}", DateTime.Now);

            Instrument  ins;
            List <char> characters;
            IAsyncEnumerable <Instrument> instruments;

            _dataAdapter.JsonSerializerOptions = new();
            _dataAdapter.JsonSerializerOptions.PropertyNameCaseInsensitive = true;

            characters = new();
            for (byte i = Convert.ToByte('A'); i <= Convert.ToByte('Z'); i++)
            {
                characters.Add(Convert.ToChar(i));
            }

            foreach (char character in characters)
            {
                try
                {
                    using StocksDbContext stocksDbContext = _dataAdapter.StocksDbContextFactory.CreateDbContext();
                    _dataAdapter.Json = await Requester.SendRequestAsync(Enums.HttpVerb.Get, $"{_dataAdapter.Settings["InstrumentsUri"]}?apikey={_dataAdapter.Settings["ApiKey"]}&symbol={character}.*&projection=symbol-regex", null, cancellationToken);

                    _dataAdapter.Json = Toolbox.Json.RemoveTopLevelKeys(_dataAdapter.Json);
                    instruments       = JsonSerializer.Deserialize <IAsyncEnumerable <Instrument> >(_dataAdapter.Json, _dataAdapter.JsonSerializerOptions);
                    await foreach (Instrument instrument in instruments)
                    {
                        try
                        {
                            _logger.LogInformation("GetInstrumentsAsync processing {exchange} {symbol}", instrument.Exchange, instrument.Symbol);
                            ins = await stocksDbContext.FindAsync <Instrument>(new object[] { instrument.Exchange, instrument.Symbol }, cancellationToken);

                            if (ins == null)
                            {
                                await stocksDbContext.AddAsync(instrument, cancellationToken);
                            }

                            else
                            {
                                ins.Cusip     = instrument.Cusip;
                                ins.AssetType = instrument.AssetType;
                                ins.Updated   = DateTime.UtcNow;
                                stocksDbContext.Update(ins);
                            }

                            await stocksDbContext.SaveChangesAsync(cancellationToken);
                        }

                        catch
                        {
                            _logger.LogError("GetInstrumentsAsync error updaing {symbol}", instrument.Symbol);
                        }

                        finally
                        {
                            _logger.LogInformation("GetInstrumentsAsync processed {exchange} {symbol}", instrument.Exchange, instrument.Symbol);
                        }
                    }
                }

                catch (Exception exception)
                {
                    _logger.LogError("GetInstrumentsAsync {message}", exception.Message);
                }
            }

            _logger.LogInformation("GetInstrumentsAsync completed {now}", DateTime.Now);
        }
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as CommunicationRequest;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (Category != null)
                {
                    dest.Category = (Hl7.Fhir.Model.CodeableConcept)Category.DeepCopy();
                }
                if (Sender != null)
                {
                    dest.Sender = (Hl7.Fhir.Model.ResourceReference)Sender.DeepCopy();
                }
                if (Recipient != null)
                {
                    dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
                }
                if (Payload != null)
                {
                    dest.Payload = new List <Hl7.Fhir.Model.CommunicationRequest.PayloadComponent>(Payload.DeepCopy());
                }
                if (Medium != null)
                {
                    dest.Medium = new List <Hl7.Fhir.Model.CodeableConcept>(Medium.DeepCopy());
                }
                if (Requester != null)
                {
                    dest.Requester = (Hl7.Fhir.Model.ResourceReference)Requester.DeepCopy();
                }
                if (StatusElement != null)
                {
                    dest.StatusElement = (Code <Hl7.Fhir.Model.CommunicationRequest.CommunicationRequestStatus>)StatusElement.DeepCopy();
                }
                if (Encounter != null)
                {
                    dest.Encounter = (Hl7.Fhir.Model.ResourceReference)Encounter.DeepCopy();
                }
                if (Scheduled != null)
                {
                    dest.Scheduled = (Hl7.Fhir.Model.Element)Scheduled.DeepCopy();
                }
                if (Reason != null)
                {
                    dest.Reason = new List <Hl7.Fhir.Model.CodeableConcept>(Reason.DeepCopy());
                }
                if (RequestedOnElement != null)
                {
                    dest.RequestedOnElement = (Hl7.Fhir.Model.FhirDateTime)RequestedOnElement.DeepCopy();
                }
                if (Subject != null)
                {
                    dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
                }
                if (Priority != null)
                {
                    dest.Priority = (Hl7.Fhir.Model.CodeableConcept)Priority.DeepCopy();
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
		public void VoidResponse_Bad_KeepResponse(object responseValue)
		{
			using (var request = new Requester<VoidResponse>(
				responseValue,
				settings => settings.ExposeRawResponse(true),
				(settings, stream) => FakeResponse.Bad(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				//Response and rawresponse should ALWAYS be null for VoidResponse responses
				r.Response.Should().BeNull();
				r.ResponseRaw.Should().BeNull();
			}
		}
Esempio n. 37
0
 private void Start()
 {
     _requester = new Requester();
     _requester.Start();
 }
Esempio n. 38
0
 public SetAccountInfo(Requester requester) : base(requester)
 {
     endpoint = "/v1/accounts:update";
 }
Esempio n. 39
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as ReferralRequest;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (StatusElement != null)
                {
                    dest.StatusElement = (Code <Hl7.Fhir.Model.ReferralRequest.ReferralStatus>)StatusElement.DeepCopy();
                }
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (DateElement != null)
                {
                    dest.DateElement = (Hl7.Fhir.Model.FhirDateTime)DateElement.DeepCopy();
                }
                if (Type != null)
                {
                    dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy();
                }
                if (Specialty != null)
                {
                    dest.Specialty = (Hl7.Fhir.Model.CodeableConcept)Specialty.DeepCopy();
                }
                if (Priority != null)
                {
                    dest.Priority = (Hl7.Fhir.Model.CodeableConcept)Priority.DeepCopy();
                }
                if (Patient != null)
                {
                    dest.Patient = (Hl7.Fhir.Model.ResourceReference)Patient.DeepCopy();
                }
                if (Requester != null)
                {
                    dest.Requester = (Hl7.Fhir.Model.ResourceReference)Requester.DeepCopy();
                }
                if (Recipient != null)
                {
                    dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
                }
                if (Encounter != null)
                {
                    dest.Encounter = (Hl7.Fhir.Model.ResourceReference)Encounter.DeepCopy();
                }
                if (DateSentElement != null)
                {
                    dest.DateSentElement = (Hl7.Fhir.Model.FhirDateTime)DateSentElement.DeepCopy();
                }
                if (Reason != null)
                {
                    dest.Reason = (Hl7.Fhir.Model.CodeableConcept)Reason.DeepCopy();
                }
                if (DescriptionElement != null)
                {
                    dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy();
                }
                if (ServiceRequested != null)
                {
                    dest.ServiceRequested = new List <Hl7.Fhir.Model.CodeableConcept>(ServiceRequested.DeepCopy());
                }
                if (SupportingInformation != null)
                {
                    dest.SupportingInformation = new List <Hl7.Fhir.Model.ResourceReference>(SupportingInformation.DeepCopy());
                }
                if (FulfillmentTime != null)
                {
                    dest.FulfillmentTime = (Hl7.Fhir.Model.Period)FulfillmentTime.DeepCopy();
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
 public CachedRequestersModel(Requester requester)
 {
     CachedRequester = requester;
 }
Esempio n. 41
0
        void Work()
        {
            Stopwatch sw_total = new Stopwatch();

            sw_total.Start();


            //	Parallel.For(0, reader.records.Count, i =>
            //	{
            //		if (!canceled)
            //		{
            //			reader.records[i].Status = Requester.Send(reader.records[i].GetURL(), timeOut);
            //
            //			Logger.Log(string.Format("HOST {0} is {1}", reader.records[i].GetURL(), reader.records[i].Status));
            //			Logger.Log(string.Format("[{0} of {1}] at [{2}] s", completed, reader.records.Count, sw_total.ElapsedMilliseconds / 1000));
            //
            //			completed++;
            //			ProgressBarChanged(reader.records.Count);
            //		}
            //
            //	});


            int completed = 0;
            int counter   = 0;

            try
            {
                Logger.Log("\n******Begin Reading********\n");
                totalLines = File.ReadAllLines(filePath).Length;

                Logger.Log(string.Format("File: " + filePath));
                Logger.Log(string.Format("Total Lines: " + totalLines));

                Record record;

                Output.Write(string.Format("MachineName: {0} ProviderName: {1} Total {2} URL's\n",
                                           Environment.MachineName, providerName, totalLines));
                Output.Write(new string('=', 100));

                using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default))
                {
                    string   line;
                    string[] temp;

                    while ((line = sr.ReadLine()) != null)
                    {
                        temp = line.Split('\t');

                        record = new Record(long.Parse(temp[0]), temp[1], temp[2], temp[3], temp[4]);

                        //records.Add(new Record(temp[0], temp[1], temp[2]));
                        //records.Add(new Record(long.Parse(temp[0]), temp[1], temp[2], temp[3], temp[4]));
                        Logger.Log(string.Format("#{0} URL: {1} DOMAIN: {2} IP: {3}", temp[0], temp[4], temp[3], temp[2]));
                        record.Status = Requester.Send(record.GetURL(), timeOut);
                        completed++;

                        Logger.Log(string.Format("HOST {0} is {1}", record.GetURL(), record.Status));
                        Logger.Log(string.Format("[{0} of {1}] at [{2}] s", completed, totalLines, sw_total.Elapsed.Seconds));

                        if (record.Status == Status.Available)
                        {
                            Output.Write(record.ToString());
                            counter++;
                        }

                        ProgressBarChanged(totalLines);
                        double calc = sw_total.Elapsed.TotalSeconds / completed * totalLines;
                        UpdateTimer(calc - sw_total.Elapsed.TotalSeconds);
                    }

                    Output.Write((string.Format("[{0} of {1}] Avaible", counter, totalLines)));
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message);
            }
            //-------------вывод результата таймера----------------------------------------------------------------------//
            sw_total.Stop();
            Logger.Log(string.Format("Checked [{0}] URL's at [{1}] ms", counter, sw_total.ElapsedMilliseconds));



            //sw_total.Stop();

            Console.WriteLine("Total Time: [{0} s]", sw_total.ElapsedMilliseconds / 1000);
            Logger.Log(string.Format("Total Time: [{0} s]", sw_total.ElapsedMilliseconds / 1000));

            //foreach (var item in reader.records)
            //{
            //	Logger.Log(item.ToString());
            //}


            //	Output.InTXT(reader.records, providerName);
            //	PrintResult(reader.records);

            //Logger.WriteLogs();
        }
        public async Task <List <UnifiedModuleMessageView> > SearchAsync(UnifiedModuleMessageViewSearch search, Requester requester)
        {
            var result = new List <UnifiedModuleMessageView>();

            var uresult = await moduleMessageService.SearchAsync(search, requester);

            result.AddRange(uresult.Select(x => services.mapper.Map <UnifiedModuleMessageView>(x)));

            var rresult = await moduleRoomMessageService.SearchAsync(services.mapper.Map <CommentSearch>(search), requester);

            result.AddRange(rresult.Select(x =>
            {
                var result = services.mapper.Map <UnifiedModuleMessageView>(x);
                moduleMessageService.SetUsersInMessage(result);
                return(result);
            }));

            return(result);
        }
Esempio n. 43
0
        public static void Main(string[] args)
        {
            var requester = new Requester();

            Console.WriteLine(requester.GetTankIdByName("E 100"));
        }
Esempio n. 44
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as CommunicationRequest;

            if (dest == null)
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }

            base.CopyTo(dest);
            if (Identifier != null)
            {
                dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
            }
            if (BasedOn != null)
            {
                dest.BasedOn = new List <Hl7.Fhir.Model.ResourceReference>(BasedOn.DeepCopy());
            }
            if (Replaces != null)
            {
                dest.Replaces = new List <Hl7.Fhir.Model.ResourceReference>(Replaces.DeepCopy());
            }
            if (GroupIdentifier != null)
            {
                dest.GroupIdentifier = (Hl7.Fhir.Model.Identifier)GroupIdentifier.DeepCopy();
            }
            if (StatusElement != null)
            {
                dest.StatusElement = (Code <Hl7.Fhir.Model.RequestStatus>)StatusElement.DeepCopy();
            }
            if (StatusReason != null)
            {
                dest.StatusReason = (Hl7.Fhir.Model.CodeableConcept)StatusReason.DeepCopy();
            }
            if (Category != null)
            {
                dest.Category = new List <Hl7.Fhir.Model.CodeableConcept>(Category.DeepCopy());
            }
            if (PriorityElement != null)
            {
                dest.PriorityElement = (Code <Hl7.Fhir.Model.RequestPriority>)PriorityElement.DeepCopy();
            }
            if (DoNotPerformElement != null)
            {
                dest.DoNotPerformElement = (Hl7.Fhir.Model.FhirBoolean)DoNotPerformElement.DeepCopy();
            }
            if (Medium != null)
            {
                dest.Medium = new List <Hl7.Fhir.Model.CodeableConcept>(Medium.DeepCopy());
            }
            if (Subject != null)
            {
                dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
            }
            if (About != null)
            {
                dest.About = new List <Hl7.Fhir.Model.ResourceReference>(About.DeepCopy());
            }
            if (Encounter != null)
            {
                dest.Encounter = (Hl7.Fhir.Model.ResourceReference)Encounter.DeepCopy();
            }
            if (Payload != null)
            {
                dest.Payload = new List <Hl7.Fhir.Model.CommunicationRequest.PayloadComponent>(Payload.DeepCopy());
            }
            if (Occurrence != null)
            {
                dest.Occurrence = (Hl7.Fhir.Model.DataType)Occurrence.DeepCopy();
            }
            if (AuthoredOnElement != null)
            {
                dest.AuthoredOnElement = (Hl7.Fhir.Model.FhirDateTime)AuthoredOnElement.DeepCopy();
            }
            if (Requester != null)
            {
                dest.Requester = (Hl7.Fhir.Model.ResourceReference)Requester.DeepCopy();
            }
            if (Recipient != null)
            {
                dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
            }
            if (Sender != null)
            {
                dest.Sender = (Hl7.Fhir.Model.ResourceReference)Sender.DeepCopy();
            }
            if (ReasonCode != null)
            {
                dest.ReasonCode = new List <Hl7.Fhir.Model.CodeableConcept>(ReasonCode.DeepCopy());
            }
            if (ReasonReference != null)
            {
                dest.ReasonReference = new List <Hl7.Fhir.Model.ResourceReference>(ReasonReference.DeepCopy());
            }
            if (Note != null)
            {
                dest.Note = new List <Hl7.Fhir.Model.Annotation>(Note.DeepCopy());
            }
            return(dest);
        }
		public void DynamicDictionary_Ok_DiscardResponse(object responseValue)
		{
			using (var request = new Requester<DynamicDictionary>(
				responseValue,
				settings => settings.ExposeRawResponse(false),
				(settings, stream) => FakeResponse.Ok(settings, response: stream),
				client => client.Info()
			))
			{
				var r = request.Result;
				r.Success.Should().BeTrue();
				object v = r.Response["value"];

				v.ShouldBeEquivalentTo(responseValue);
				r.ResponseRaw.Should().BeNull();

			}
		}
Esempio n. 46
0
        public static uint256 BlindScript(this Requester requester, PubKey signerPubKey, PubKey RPubKey, Script script)
        {
            var msg = new uint256(Hashes.SHA256(script.ToBytes()));

            return(requester.BlindMessage(msg, RPubKey, signerPubKey));
        }
		public void ByteArray_Bad_DiscardResponse(object responseValue)
		{
			using (var request = new Requester<byte[]>(
				responseValue,
				settings => settings.ExposeRawResponse(false),
				(settings, stream) => FakeResponse.Bad(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
				r.ResponseRaw.Should().BeNull();

			}
		}
 public BenchmarksEndpoint(Requester requester)
 {
     this.requester = requester;
 }
		public void Stream_Bad_DiscardResponse(object responseValue)
		{
			using (var request = new Requester<Stream>(
				responseValue,
				settings => settings.ExposeRawResponse(false),
				(settings, stream) => FakeResponse.Bad(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				using (r.Response)
				using (var ms = new MemoryStream())
				{
					r.Response.CopyTo(ms);
					var bytes = ms.ToArray();
					bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
				}
				r.ResponseRaw.Should().BeNull();

			}
		}
        public async Task WhenUserIsImpersonated_ItShouldNotReport()
        {
            await this.target.HandleAsync(new SendIdentifiedUserInformationCommand(Requester.Authenticated(UserId.Random(), Requester.Authenticated(UserId.Random())), false, Email, Name, Username));

            // Test verification handled by strict behaviour.
        }
		public void Stream_Bad_KeepResponse(object responseValue)
		{
			using (var request = new Requester<Stream>(
				responseValue,
				settings => settings.ExposeRawResponse(true),
				(settings, stream) => FakeResponse.Bad(settings, response: stream)
			))
			{
				var r = request.Result;
				r.Success.Should().BeFalse();
				using (r.Response)
				using (var ms = new MemoryStream())
				{
					r.Response.CopyTo(ms);
					var bytes = ms.ToArray();
					bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
				}
				//raw response is ALWAYS null when requesting the stream directly
				//the client should not interfere with it
				r.ResponseRaw.Should().BeNull();
			}
		}
 public bool IsSuper(Requester requester)
 {
     return(requester.system || config.SuperUsers.Contains(requester.userId));
 }
Esempio n. 53
0
        /// <summary>
        /// 执行认证.
        /// </summary>
        public async override Task <AuthenticateResponse> PerformRequestAsync()
        {
            try
            {
                this.PostContent = new JObject(
                    new JProperty("agent",
                                  new JObject(
                                      new JProperty("name", "Minecraft"),
                                      new JProperty("version", "1"))),
                    new JProperty("username", this.Arguments[0]),
                    new JProperty("password", this.Arguments[1]),
                    new JProperty("clientToken", Requester.ClientToken),
                    new JProperty("requestUser", true)).ToString();

                this.Response = await Requester.Post(this);

                if (this.Response.IsSuccess)
                {
                    JObject     user = JObject.Parse(this.Response.RawMessage);
                    List <Uuid> availableProfiles = new List <Uuid>();

                    foreach (JObject profile in user["availableProfiles"])
                    {
                        var playerName = profile["name"].ToObject <string>();
                        var value      = profile["id"].ToObject <string>();
                        var legacy     = (profile.ContainsKey("legacyProfile") ? profile["legacyProfile"].ToObject <bool>() : false);
                        availableProfiles.Add(new Uuid()
                        {
                            PlayerName = playerName,
                            Value      = value,
                            Legacy     = legacy,
                            Demo       = null
                        });
                    }


                    return(new AuthenticateResponse(this.Response)
                    {
                        AccessToken = user["accessToken"].ToObject <string>(),
                        ClientToken = user["clientToken"].ToObject <string>(),
                        AvailableProfiles = availableProfiles,
                        SelectedProfile = new Uuid()
                        {
                            PlayerName = user["selectedProfile"]["name"].ToObject <string>(),
                            Value = user["selectedProfile"]["id"].ToObject <string>(),
                            Legacy = (user["selectedProfile"].ToString().Contains("legacyProfile") ? user["selectedProfile"]["legacyProfile"].ToObject <bool>() : false),
                            Demo = null
                        },
                        User = user["user"].ToObject <UserData>()
                    });
                }
                else
                {
                    try
                    {
                        AuthenticationResponseError error = new AuthenticationResponseError(JObject.Parse(this.Response.RawMessage));
                        return(new AuthenticateResponse(this.Response)
                        {
                            Error = error
                        });
                    }
                    catch (Exception)
                    {
                        return(new AuthenticateResponse(Error.GetError(this.Response)));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 54
0
 public HealthEndpoint(Requester requester)
 {
     this.requester = requester;
 }
		public void SetUser(Requester user)
		{
			HttpContext.Current.Items[LOGGED_USER] = user;
		}
Esempio n. 56
0
        public static List <Item> GetLinks(string url)
        {
            PageTypes typepage = PageTypes.Unkown;

            string[] arr  = url.Split('/');
            bool     give = false;
            string   id   = "";

            foreach (string str in arr)
            {
                if (give)
                {
                    id = str;
                    break;
                }
                if (str.Split('.')[0] == "30nama")
                {
                    give = true;
                }
            }
            switch (id)
            {
            case "series":
                typepage = PageTypes.Series;
                break;

            case "movies":
                typepage = PageTypes.Movie;
                break;
            }

            Account ac = Accounts.GetAccount(SiteDetecter.TypeSite._30Nama);

            Config    config = new Config();
            Requester Rer    = new Requester();

            config.LoginURL = _30namaserver + "login";

            RequestManage login = Rer.GETData(config);

            config.Cookies = login.CookiesString;
            string pst = "log=<USER>&pwd=<PASS>&rememberme=forever&wp-submit=%D9%88%D8%B1%D9%88%D8%AF&redirect_to=http%3A%2F%2F30nama.site%2Fwp-admin%2F&instance=&action=login";

            config.DataSet           = "<USER>*<PASS>";
            config.PostData          = Rer.ReplaceAccount(ac, pst, config);
            config.AllowAutoRedirect = true;
            config.KeepAlive         = true;
            config.ContectType       = "application/x-www-form-urlencoded";
            config.Referer           = config.LoginURL;
            login = Rer.POSTData(config, login);

            config.LoginURL = url;
            config.Cookies  = "";
            RequestManage manage = Rer.GETData(config, login);


            HtmlDocument HD = new HtmlDocument();

            HD.LoadHtml(manage.SourcePage);

            switch (typepage)
            {
            case PageTypes.Movie:
                return(MovieLeech(HD, manage));

            case PageTypes.Series:
                return(SeriesLeech(HD, manage));
            }

            return(null);
        }
 //A special endpoint for MODULES (not users) to add module messages
 public async Task <UnifiedModuleMessageView> AddMessageAsync(UnifiedModuleMessageView basic, Requester requester) //long senderuid, long receiveruid, string message, string module)
 {
     //This is IF the message is sent to a user
     if (basic.parentId == 0)
     {
         return(services.mapper.Map <UnifiedModuleMessageView>(await moduleMessageService.AddMessageAsync(basic)));
     }
     else
     {
         return(services.mapper.Map <UnifiedModuleMessageView>(await moduleRoomMessageService.WriteAsync(services.mapper.Map <CommentView>(basic), requester)));
     }
 }
Esempio n. 58
0
 public SearchEndpoint(Requester requester)
 {
     this.requester = requester;
 }
        private async void ExecuteSendToServerCommand()
        {
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();
            if (accessStatus == GeolocationAccessStatus.Denied)
            {
                return;
            }

            Geolocator geolocator = new Geolocator();
            Geoposition position = await geolocator.GetGeopositionAsync();

            double latitude = position.Coordinate.Latitude;
            double longitude = position.Coordinate.Longitude;

            this.Room.Latitude = latitude;
            this.Room.Longitude = longitude;

            RoomRequestModel roomDatabaseModel = new RoomRequestModel
            {
                Geometry = await RoomGeometryViewModel.CreateFromRoom(this.Room),
                Room = this.Room
            };

            string requestBody = JsonConvert.SerializeObject(roomDatabaseModel);
            HttpStringContent requestContent = new HttpStringContent(requestBody, UnicodeEncoding.Utf8, "application/json");

            Data data = new Data();

            UserDatabaseModel currentUser = await data.GetCurrentUser();

            if (currentUser == null || string.IsNullOrEmpty(currentUser.Token))
            {
                MessageDialogNotifier.Notify("You must be logged in to send room information on the server.");
                return;
            }

            string token = currentUser.Token;

            Requester requester = new Requester();
            string serverResult = string.Empty;

            try
            {
                serverResult = await requester.PostJsonAsync("/api/roomGeometry", requestContent, token);
            }
            catch (COMException)
            {
                MessageDialogNotifier.Notify("There was an error on the server. Please contact the server administrators..");
            }

            RoomRequestModel result = JsonConvert.DeserializeObject<RoomRequestModel>(serverResult);

            if (result == null)
            {
                MessageDialogNotifier.Notify("The room information was not valid or you are not authenticated.");
            }
            else
            {
                MessageDialogNotifier.Notify("The room information was successfully saved in the database.");
            }
        }
 public Task <EntityPackage> CanUserDoOnParent(long parentId, string action, Requester requester)
 {
     return(moduleRoomMessageService.CanUserDoOnParent(parentId, action, requester));
 }