Exemple #1
0
        public async Task <IEnumerable <CurrencyRate> > GetCurrencyRatesByDate(DateTime date)
        {
            IEnumerable <CurrencyRate> currencyRates = new List <CurrencyRate>();
            List <NationalBankUaDto>   responseBankClientSerialize = new List <NationalBankUaDto>();

            string responseBankClient = await HttpModule.DownloadData(UrlConfigurator(date));

            try
            {
                responseBankClientSerialize = ApiParserData(responseBankClient);
            }
            catch (Exception ex)
            {
                throw new Exception("Can't parse response. BankClient - NationalBankUa. Error: " + ex.Message);
            }

            if (responseBankClientSerialize.Count == 0 || responseBankClientSerialize.Count == 1)
            {
                throw new Exception("NationalBankUa - Wrong date. Error date: " + date);
            }

            currencyRates = responseBankClientSerialize.Select(currencyItem => new CurrencyRate
            {
                BankId       = BankClientType.NationalBankUa.ToString(),
                CurrencyCode = currencyItem.Code,
                Rate         = currencyItem.Rate,
                Timestamp    = date.Date
            });

            return(currencyRates);
        }
Exemple #2
0
        public async Task <IEnumerable <CurrencyRate> > GetCurrencyRatesByDate(DateTime date)
        {
            IEnumerable <CurrencyRate>    currencyRates = new List <CurrencyRate>();
            OpenExchangeRateBankClientDto responseBankClientSerialize = new OpenExchangeRateBankClientDto();

            string responseBankClient = await HttpModule.DownloadData(UrlConfigurator(date));

            try
            {
                responseBankClientSerialize = ApiParserData(responseBankClient);
            }
            catch (Exception ex)
            {
                throw new Exception("Can't parse response. BankClient - OpenExchangeRateBankClient. Error: " + ex.Message);
            }

            if (responseBankClientSerialize.Error == true)
            {
                throw new Exception("OpenExchangeRateBankClient - returned error: " + responseBankClientSerialize.Message + ". Date: " + date);
            }

            currencyRates = responseBankClientSerialize.Rates.Select(currencyItem => new CurrencyRate
            {
                BankId       = BankClientType.OpenExchangeRateBankClient.ToString(),
                CurrencyCode = currencyItem.Key,
                Rate         = currencyItem.Value,
                Timestamp    = date.Date
            });

            return(currencyRates);
        }
        public async Task <IEnumerable <CurrencyRate> > GetCurrencyRatesByDate(DateTime date)
        {
            IEnumerable <CurrencyRate> currencyRates = new List <CurrencyRate>();
            NationalBankKzDto          responseBankClientSerialize = new NationalBankKzDto();

            string responseBankClient = await HttpModule.DownloadData(UrlConfigurator(date));

            responseBankClientSerialize = XmlApiSerializer.DataConverterDto <NationalBankKzDto>(responseBankClient);

            if (responseBankClientSerialize.Error == "введена неверная дата")
            {
                throw new Exception("NationalBankKz - Wrong format date. Error date: " + date);
            }

            if (responseBankClientSerialize.Rates.Count == 0)
            {
                throw new Exception("NationalBankKz - returned error. Date: " + date + ". Add information: " + responseBankClientSerialize.Info);
            }

            currencyRates = responseBankClientSerialize.Rates.Select(currencyItem => new CurrencyRate
            {
                BankId       = BankClientType.NationalBankKz.ToString(),
                CurrencyCode = currencyItem.Code,
                Rate         = currencyItem.Rate / currencyItem.Quantity,
                Timestamp    = date.Date
            });

            return(currencyRates);
        }
Exemple #4
0
        public void AttachFilterEventHandler_AttachToCompatibleHandler(string handlerAssemblyName, string handlerTypeName)
        {
            // Arrange
            var container = Mocks.Create <IContainer>();

            container.Setup(c => c.Resolve <IHtmlBuilder>()).Returns(Mocks.Create <IHtmlBuilder>().Object);

            var response = Mocks.Create <HttpResponseBase>();

            response.Setup(r => r.ContentType).Returns(ContentTypes.Html);
            response.Setup(r => r.Filter).Returns(new MemoryStream());
            response.SetupSet(r => r.Filter = It.IsAny <HttpResponseFilter>());

            var handlerAssembly = Assembly.Load(handlerAssemblyName);
            var handlerType     = handlerAssembly.GetType(handlerTypeName);
            var handler         = (IHttpHandler)Activator.CreateInstance(handlerType, new RequestContext());

            var context = Mocks.Create <HttpContextBase>();

            context.Setup(c => c.Items.Contains(HttpModule.ContainerKey)).Returns(false);
            context.Setup(c => c.Items.Add(HttpModule.ContainerKey, true));
            context.Setup(c => c.CurrentHandler).Returns(handler);
            context.Setup(c => c.Response).Returns(response.Object);

            var module = new HttpModule(context.Object, container.Object, null, null);

            // Act
            module.AttachFilterEventHandler(null, null);

            // Assert
            Mocks.VerifyAll();
        }
Exemple #5
0
    IEnumerator MatchStatusPolling()
    {
        LogModule.WriteToLogFile("[ClientModule] Send Polling with TicketId - " + this.ClientConnection.TicketId);
        yield return(new WaitForSeconds(5.0f));

        StartCoroutine(HttpModule.PutRequest(ApiModule.GetMatchStatusAPI(),
                                             new APIModule.MatchstatusRequest(this.PlayerId, this.ClientConnection.TicketId), MatchStatusCallback));
    }
		public void StaticRenderer_WhenExecutingArequest_ShouldApplyFilters()
		{
			var assemblyLocation = Assembly.GetExecutingAssembly().Location;
			var runner = new RunnerForTest();
			NodeMainInitializer.InitializeFakeMain(assemblyLocation, runner);
			var rootDir = InferWebRootDir(assemblyLocation);
			var pathProvider = new StaticContentPathProvider(rootDir);
			var filterHandler = new FilterHandler();

			var globalFilter = new Mock<IFilter>();
			globalFilter.Setup(a => a.OnPreExecute(It.IsAny<IHttpContext>())).Returns(true);
			filterHandler.AddFilter(globalFilter.Object);
			ServiceLocator.Locator.Register<IFilterHandler>(filterHandler);

			var http = new HttpModule();
			http.SetParameter(HttpParameters.HttpPort, 8881);
			http.SetParameter(HttpParameters.HttpVirtualDir, "nodecs");
			http.SetParameter(HttpParameters.HttpHost, "localhost");


			var routingService = new RoutingService();
			http.RegisterRouting(routingService);

			http.Initialize();

			http.RegisterPathProvider(pathProvider);

			const string uri = "http://localhost:8881/nodecs";

			var context = CreateRequest(uri);
			var outputStream = (MockStream)context.Response.OutputStream;
			outputStream.Initialize();


            globalFilter.Setup(a => a.OnPostExecute(It.IsAny<IHttpContext>()))
                .Callback(() =>
                {
                    Console.WriteLine("AAAA");
                });

			//request.
			http.ExecuteRequest(context);
			runner.RunCycleFor(200);
			var os = (MemoryStream)context.Response.OutputStream;
			os.Seek(0, SeekOrigin.Begin);
			var bytes = os.ToArray();
			var result = Encoding.UTF8.GetString(bytes);

			Assert.IsTrue(outputStream.WrittenBytes > 0);
			Assert.IsNotNull(result);

			globalFilter.Verify(a => a.OnPreExecute(It.IsAny<IHttpContext>()), Times.Once);
			globalFilter.Verify(a => a.OnPostExecute(It.IsAny<IHttpContext>()), Times.Once);
		}
Exemple #7
0
 public void MoveToWorld(string worldId)
 {
     if (ConnectionStatus != null)
     {
         ConnectionStatus.text = "Searching World . . .";
     }
     this.ClientConnection.Init();
     this.ClientConnection.WorldId = worldId;
     StartCoroutine(HttpModule.PutRequest(ApiModule.GetMatchRequestAPI(),
                                          new APIModule.MatchmakingRequest(this.PlayerId, worldId), MatchRequestCallback));
 }
        private ExpModule parseFormToExp()
        {
            ExpModule exp = new ExpModule();

            exp.Name     = ExpNameTextBox.Text;
            exp.Language = LanguafeComboBox.Text;
            exp.Status   = 1;
            if (ExpStatusComboBox.Text.Equals("禁用"))
            {
                exp.Status = 0;
            }
            exp.FormatUrl = false;
            if (FormatUrlComboBox.Text.Equals("是"))
            {
                exp.FormatUrl = true;
            }
            ExpVerification verification = new ExpVerification();

            verification.Context = VerificationValueTextBox.Text;
            foreach (Int32 key in MainForm.verificationTypes.Keys)
            {
                if (MainForm.verificationTypes[key].Equals(VerificationComboBox.Text))
                {
                    verification.Type = key;
                }
            }
            exp.Verification      = verification;
            exp.Verification.Calc = CalcComboBox.Text;
            HttpModule expContext = new HttpModule();
            Dictionary <String, String> headers = new Dictionary <string, string>();

            for (int index = 0; index < HeaderListview.Items.Count; index++)
            {
                try {
                    headers.Add(HeaderListview.Items[index].SubItems[0].Text, HeaderListview.Items[index].SubItems[1].Text);
                }
                catch { }
            }
            expContext.Header = headers;
            expContext.Encode = EncodeComBox.Text;
            expContext.Body   = BodyTextBox.Text;
            if (!String.IsNullOrEmpty(expContext.Body))
            {
                if (ExpHandle.IsHexadecimal(expContext.Body))
                {
                    expContext.IsHex = true;
                }
            }
            expContext.Method = RequestMethodComboBox.Text;
            exp.ExpContext    = expContext;
            return(exp);
        }
Exemple #9
0
        public void Activated(PluginRuntime pluginRuntime)
        {
            var meta = pluginRuntime.Metadata;

            Logger.Info(string.Format("{0} v{1} [{2}] by {3}", meta.Name, meta.PluginVersion, meta.Description, meta.Author));

            IResourceServer server = ServiceRegistration.Get <IResourceServer>();

            if (server != null)
            {
                ServiceRegistration.Set <IFanArtService>(new FanArtService());
                _fanartModule = new FanartAccessModule();
                server.AddHttpModule(_fanartModule);
            }
        }
Exemple #10
0
        public void AttachFilterEventHAndler_AlreadyAttached()
        {
            // Arrange
            var context = Mocks.Create <HttpContextBase>();

            context.Setup(c => c.Items.Contains(HttpModule.ContainerKey)).Returns(true);

            var module = new HttpModule(context.Object, null, null, null);

            // Act
            module.AttachFilterEventHandler(null, null);

            // Assert
            Mocks.VerifyAll();
        }
Exemple #11
0
 public static bool getFile(this HttpModule http, params dynamic[] files)
 {
     try
     {
         List <dynamic> allFiles       = new List <dynamic>();
         var            invokerContext = ContextManager.GetTaskInvokerContext();
         if (invokerContext == null)
         {
             throw new Exception("failed to get the taskInvokerContext.");
         }
         foreach (var item in files)
         {
             if (item is JSArray)
             {
                 allFiles.AddRange((JSArray)item);
             }
             else
             {
                 allFiles.Add(item);
             }
         }
         foreach (var file in allFiles)
         {
             if (!FileUnity.SafeCreateDirectory(file.savePath.Substring(0, file.savePath.LastIndexOf("\\"))))
             {
                 return(false);
             }
         }
         var result = http.getFiles(allFiles.ToArray());
         if (result)
         {
             invokerContext.Task?.SetStat(files.Length, TaskStatTypes.File);
         }
         return(result);
     }
     catch (Exception ex)
     {
         LoggerProxy.Error("HttpModuleExtend", "call getFile error.", ex);
     }
     return(false);
 }
		public void ItShouldBePossibleToExecuteArequest()
		{
			var assemblyLocation = Assembly.GetExecutingAssembly().Location;
			var runner = new RunnerForTest();
			NodeMainInitializer.InitializeFakeMain(assemblyLocation, runner);
			var rootDir = InferWebRootDir(assemblyLocation);
			var pathProvider = new StaticContentPathProvider(rootDir);
			var http = new HttpModule();
			http.SetParameter(HttpParameters.HttpPort, 8881);
			http.SetParameter(HttpParameters.HttpVirtualDir, "nodecs");
			http.SetParameter(HttpParameters.HttpHost, "localhost");


			var routingService = new RoutingService();
			http.RegisterRouting(routingService);

			http.Initialize();

			http.RegisterPathProvider(pathProvider);

			const string uri = "http://localhost:8881/nodecs";

			var context = CreateRequest(uri);
			var outputStream = (MockStream)context.Response.OutputStream;
			outputStream.Initialize();

			//request.
			http.ExecuteRequest(context);
			runner.RunCycleFor(200);
			var os = (MemoryStream)context.Response.OutputStream;
			os.Seek(0, SeekOrigin.Begin);
			var bytes = os.ToArray();
			var result = Encoding.UTF8.GetString(bytes);

			Assert.IsTrue(outputStream.WrittenBytes > 0);
			Assert.IsNotNull(result);
			Assert.IsTrue(result.Length > 0);
			Assert.IsTrue(result.IndexOf("Exception", StringComparison.Ordinal) < 0, result);
			Assert.AreEqual(1, outputStream.ClosesCall);
		}
		protected byte[] RunRequest(string uri, HttpModule http, RunnerForTest runner, int timeoutMs = 250)
		{
			var context = PrepareRequest(uri);
			http.ExecuteRequest(context);
			var outputStream = (MockStream)context.Response.OutputStream;

			var sw = new Stopwatch();
			sw.Start();
			while (outputStream.ClosesCall != 1 && sw.ElapsedMilliseconds < timeoutMs)
			{
				runner.RunCycleFor(timeoutMs);
			}
			Console.WriteLine(outputStream.WrittenBytes + " " + uri);
			Assert.AreEqual(1, outputStream.ClosesCall);
			Assert.IsTrue(outputStream.WrittenBytes > 0);
			var os = (MemoryStream)context.Response.OutputStream;
			os.Seek(0, SeekOrigin.Begin);
			var bytes = os.ToArray();
			var strings = Encoding.UTF8.GetString(bytes);
			Assert.IsTrue(strings.Length > 0);
			Assert.IsTrue(strings.IndexOf("Exception", StringComparison.Ordinal) < 0, strings);
			return bytes;
		}
 public void RemoveHttpModule(HttpModule module)
 {
     _httpServers.Values.ToList().ForEach(x => x.Remove(module));
 }
 public void AddHttpModule(HttpModule module)
 {
     _httpServers.Values.ToList().ForEach(x => x.Add(module));
 }
Exemple #16
0
 /// <summary>
 /// Removes a <see cref="HttpModule"/> from the server.
 /// </summary>
 /// <param name="module">Module to remove.</param>
 // Added by Albert, Team-MediaPortal: It must be possible to remove modules at runtime.
 public void Remove(HttpModule module)
 {
     _modules.Remove(module);
 }
Exemple #17
0
 /// <summary>
 /// Add a <see cref="HttpModule"/> to the server.
 /// </summary>
 /// <param name="module">module to add</param>
 public void Add(HttpModule module)
 {
     _modules.Add(module);
 }
 public static WebConfiguration AsSinglePageApplication(this WebConfiguration configuration)
 {
     HttpModule.AddPipe(new SinglePageApplication());
     return(configuration);
 }
 public void AddHttpModule(HttpModule module)
 {
     server.Add(module);
 }
		public void ItShouldBePossibleToSimulateRequest()
		{
			var assemblyLocation = Assembly.GetExecutingAssembly().Location;
			var runner = new RunnerForTest();
			NodeMainInitializer.InitializeFakeMain(assemblyLocation, runner);
			var rootDir = InferWebRootDir(assemblyLocation);
			var pathProvider = new StaticContentPathProvider(rootDir);
			var http = new HttpModule();
			http.SetParameter(HttpParameters.HttpPort, 8881);
			http.SetParameter(HttpParameters.HttpVirtualDir, "nodecs");
			http.SetParameter(HttpParameters.HttpHost, "localhost");


			var routingService = new RoutingService();
			http.RegisterRouting(routingService);

			http.Initialize();

			http.RegisterPathProvider(pathProvider);

			const string uri = "http://*****:*****@src");
			var contexts = new List<SimpleHttpContext>();
			if (nodes != null)
			{
				foreach (HtmlNode node in nodes)
				{
					var src = node.Attributes["src"].Value;
					if (!src.StartsWith("http")) src = uri + "/" + src.Trim('/');
					contexts.Add((SimpleHttpContext)PrepareRequest(src));
					http.ExecuteRequest(contexts.Last());
				}
			}
			runner.RunCycleFor(500);
			for (int index = 0; index < contexts.Count; index++)
			{
				var ctx = contexts[index];
				VerifyContext(ctx);
			}
		}
Exemple #21
0
 public OpenExchangeRateBankClientTest(IConfigurationFixture fixture)
 {
     _configuration = fixture.Configuration;
     _httpModule    = new HttpModule();
     _bankClient    = new OpenExchangeRateBankClient(_configuration);
 }
 public void AddHttpModule(HttpModule module)
 {
     _httpServerV4.Add(module);
     _httpServerV6.Add(module);
 }
		public RazorViewHandler()
		{
			_mvcModule = NodeRoot.GetModule("http.mvc") as MvcModule;
			_httpModule = ServiceLocator.Locator.Resolve<HttpModule>();
		}
 public void RemoveHttpModule(HttpModule module)
 {
     _httpServerV4.Remove(module);
     _httpServerV6.Remove(module);
 }
 public NationalBankKzTest(IConfigurationFixture fixture)
 {
     _configuration = fixture.Configuration;
     _httpModule    = new HttpModule();
     _bankClient    = new NationalBankKz(_configuration);
 }