Example #1
0
 public static void Unsubscribe(IBus bus, HttpService service)
 {
     bus.Unsubscribe<SystemMessage.SystemInit>(service);
     bus.Unsubscribe<SystemMessage.BecomeShuttingDown>(service);
     bus.Unsubscribe<HttpMessage.SendOverHttp>(service);
     bus.Unsubscribe<HttpMessage.UpdatePendingRequests>(service);
 }
 public static void Subscribe(IBus bus, HttpService service)
 {
     bus.Subscribe<SystemMessage.SystemInit>(service);
     bus.Subscribe<SystemMessage.BecomeShuttingDown>(service);
     bus.Subscribe<HttpMessage.SendOverHttp>(service);
     bus.Subscribe<HttpMessage.PurgeTimedOutRequests>(service);
 }
Example #3
0
 public Projections(
     TFChunkDb db, QueuedHandler mainQueue, InMemoryBus mainBus, TimerService timerService,
     HttpService httpService, int projectionWorkerThreadCount)
 {
     _projectionWorkerThreadCount = projectionWorkerThreadCount;
     SetupMessaging(db, mainQueue, mainBus, timerService, httpService);
 }
Example #4
0
 public void Run()
 {
     using (var sut = new HttpService("samplehttpservice.exe", "", new Uri("http://localhost:1234")))
     {
         var result = sut.Process("hello-äöüÄÖÜß");
         Assert.AreEqual("<<<hello-äöüÄÖÜß>>>", result);
     }
 }
Example #5
0
        public static ProjectionManagerNode Create(TFChunkDb db, QueuedHandler inputQueue, HttpService httpService, IPublisher[] queues)
        {
            var projectionManagerNode =
                new ProjectionManagerNode(inputQueue, queues, db.Config.WriterCheckpoint);
            httpService.SetupController(new ProjectionsController(inputQueue));

            return projectionManagerNode;
        }
		public void RegisterHttpControllers(HttpService externalHttpService, HttpService internalHttpService, HttpSendService httpSendService, IPublisher mainQueue, IPublisher networkSendQueue)
		{
			var usersController = new UsersController(httpSendService, mainQueue, networkSendQueue);
			externalHttpService.SetupController(usersController);
            if(internalHttpService != null) {
			    internalHttpService.SetupController(usersController);
            }
		}
Example #7
0
 public void Register(
     TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService,
     ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendService)
 {
     _projections = new EventStore.Projections.Core.Projections(
         db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendService,
         projectionWorkerThreadCount: _projectionWorkerThreadCount, runProjections: _runProjections);
 }
        public void SetUp()
        {
            _bus = new InMemoryBus(string.Format("bus_{0}", _serverEndPoint.Port));

            _service = new HttpService(ServiceAccessibility.Private, _bus, 1, _serverEndPoint.ToHttpUrl());
            _client = new HttpAsyncClient();

            HttpBootstrap.Subscribe(_bus, _service);
        }
Example #9
0
 public static Bitmap GetStockMinNPic(string stockCode)
 {
     string xmlString = string.Empty;
     HttpService web = new HttpService();
     web.TargetUrl = string.Format("http://image2.sinajs.cn/newchart/min/n/{0}.gif", stockCode);
     web.RefererUrl = "http://image2.sinajs.cn/";
     web.UserAgent = "StockTrace";
     Bitmap requestPicture = web.RequestPicture();
     return requestPicture;
 }
Example #10
0
        public Projections(
            TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
            IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
            int projectionWorkerThreadCount, RunProjections runProjections)
        {
            _projectionWorkerThreadCount = projectionWorkerThreadCount;
            SetupMessaging(
                db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendQueue,
                runProjections);

        }
 public static ProjectionManagerNode Create(
     TFChunkDb db, QueuedHandler inputQueue, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
     IPublisher[] queues, RunProjections runProjections)
 {
     var projectionManagerNode = new ProjectionManagerNode(inputQueue, queues, runProjections);
     var projectionsController = new ProjectionsController(httpForwarder, inputQueue, networkSendQueue);
     foreach (var httpService in httpServices)
     {
         httpService.SetupController(projectionsController);
     }
     return projectionManagerNode;
 }
Example #12
0
        public Endpoint Build()
        {
            var clientFactory = _clientFactory ?? new DefaultHttpClientFactory();
            var serializer = _serializer ?? new JsonSerializer();
            var oDataQueryFactory = _oDataQueryFactory ?? new DefaultODataQueryFactory();

            var uriFactory = new UriFactory(_uri);
            var httpService = new HttpService(clientFactory, serializer);
            var restQueryableFactory = new RestQueryableFactory(httpService, new RestQueryModelVisitor(oDataQueryFactory));

            return new Endpoint(restQueryableFactory, httpService, uriFactory);
        }
Example #13
0
        void IModule.Install(ModuleManager manager)
        {
            _manager = manager;
            _client = manager.Client;
            _http = _client.Services.Get<HttpService>();
            _settings = _client.Services.Get<SettingsService>()
                .AddModule<StatusModule, Settings>(manager);

            manager.CreateCommands("status", group =>
            {
                group.MinPermissions((int)PermissionLevel.BotOwner);

                group.CreateCommand("enable")
                    .Parameter("channel", ParameterType.Optional)
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);

                        Channel channel;
                        if (e.Args[0] != "")
                            channel = await _client.FindChannel(e, e.Args[0], ChannelType.Text);
                        else
                            channel = e.Channel;
                        if (channel == null) return;

                        settings.Channel = channel.Id;
                        await _settings.Save(e.Server, settings);

                        await _client.Reply(e, $"Enabled status reports in {channel.Name}");
                    });
                group.CreateCommand("disable")
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);

                        settings.Channel = null;
                        await _settings.Save(e.Server, settings);

                        await _client.Reply(e, "Disabled status reports on this server.");
                    });
            });

            _client.LoggedIn += (s, e) =>
            {
                if (!_isRunning)
                {
                    Task.Run(Run);
                    _isRunning = true;
                }
            };
        }
        public override async Task DownloadData(HttpService http)
        {
            try
            {
                Logger.FormattedWrite(GetType().Name, $"Fetching emote data for {GetType().Name}", ConsoleColor.Green);

                HttpContent content = await http.Send(HttpMethod.Get, DataSource);
                PopulateDictionary(JObject.Parse(await content.ReadAsStringAsync()));
            }
            catch (Exception ex)
            {
                Logger.FormattedWrite(GetType().Name, $"Failed fetching emote data. Ex: {ex}", ConsoleColor.Red);
            }
        }
Example #15
0
        /// <summary>
        /// 查询某地区某运营商充值价格
        /// </summary>
        /// <param name="provinceID">省ID</param>
        /// <param name="netID">运营商ID(中移动:0,中联通:1)</param>
        /// <returns>某地区某运营商充值价格</returns>
        public static string[] SearchMainPrice()
        {
            string[] info = new string[2];
            string priceHtml = string.Empty;
            lock (obj)
            {
                HttpService web = new HttpService();
                web.TargetUrl = "http://www.google.cn/finance";
                web.RefererUrl = "http://www.google.cn/";
                string htmlContent = web.GetHttp(true, true);

                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(htmlContent);

                HtmlNode infoTableNode = htmlDoc.GetElementbyId("md");
                if (infoTableNode == null)
                {
                    return info;
                }

                HtmlNodeCollection spans = infoTableNode.SelectNodes("tr//td//span");

                int exitFlg = 0;
                foreach (HtmlNode span in spans)
                {
                    //if (span.GetAttributeValue("class", "") == "pr")
                    //{
                    //    info.PriceNow = spans[0].InnerText;
                    //    exitFlg++;
                    //}
                    //if (span.GetAttributeValue("class", "") == "chr" && !span.InnerText.Contains("%"))
                    //{
                    //    info.PriceChange = spans[1].InnerText;
                    //    exitFlg++;
                    //}
                    //if (span.GetAttributeValue("class", "") == "chr" && span.InnerText.Contains("%"))
                    //{
                    //    info.Range = spans[3].InnerText;
                    //    exitFlg++;
                    //}
                    //if (exitFlg == 3)
                    //{
                    //    break;
                    //}
                }
            }
            return info;
        }
        public override async Task<string> GetEmote(string emote, HttpService http)
        {
            if (!EmoteDict.ContainsKey(emote))
                return null;

            string url = EmoteDict[emote];
            string dir = Path.Combine(Constants.TwitchEmoteFolderDir, emote + ".png");

            if (!File.Exists(dir))
            {
                HttpContent content = await http.Send(HttpMethod.Get, url);
                File.WriteAllBytes(dir, await content.ReadAsByteArrayAsync());
            }

            return dir;
        }
Example #17
0
        public static string GetStockPic()
        {
            string xmlString = string.Empty;

            //http://quotes.cnfol.com/searchFile/ajax.xml

            HttpService web = new HttpService();
            web.TargetUrl = "http://hq.sinajs.cn/list=sh000001_zdp,sz399001_zdp,sh000300_zdp,sz399107_zdp,";
            web.RefererUrl = "http://hq.sinajs.cn/";
            web.UserAgent = "StockTrace";
            string htmlContent = web.GetHttp(true, false);
            xmlString = htmlContent;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlString);
            XmlNode list = doc.SelectSingleNode("/neverModules/autocomplete/dataSource");
            return xmlString;
        }
 public StandardComponents(
     TFChunkDb db,
     QueuedHandler mainQueue,
     ISubscriber mainBus,
     TimerService timerService,
     ITimeProvider timeProvider,
     IHttpForwarder httpForwarder,
     HttpService[] httpServices,
     IPublisher networkSendService)
 {
     _db = db;
     _mainQueue = mainQueue;
     _mainBus = mainBus;
     _timerService = timerService;
     _timeProvider = timeProvider;
     _httpForwarder = httpForwarder;
     _httpServices = httpServices;
     _networkSendService = networkSendService;
 }
        public void SetUp()
        {
            _bus = new InMemoryBus(string.Format("bus_{0}", _serverEndPoint.Port));

            {

                var pipelineBus = InMemoryBus.CreateTest();
                var queue = new QueuedHandlerThreadPool(pipelineBus, "Test", true, TimeSpan.FromMilliseconds(50));
                _multiQueuedHandler = new MultiQueuedHandler(new IQueuedHandler[]{queue}, null);
                var httpAuthenticationProviders = new HttpAuthenticationProvider[] {new AnonymousHttpAuthenticationProvider()};

                _service = new HttpService(ServiceAccessibility.Private, _bus, new NaiveUriRouter(),
                                           _multiQueuedHandler, _serverEndPoint.ToHttpUrl());
                HttpService.CreateAndSubscribePipeline(pipelineBus, httpAuthenticationProviders);
                _client = new HttpAsyncClient();
            }

            HttpBootstrap.Subscribe(_bus, _service);
        }
		/// <summary>
		/// Performs a post action.  If first action fails there will occur up to 10 retries each backing off an incrementing number of seconds (wait 1 second, retry, wait 2 seconds, retry, etc).
		/// 
		/// </summary>
		/// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception>
		/// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception>
		private DynamicJsonObject DoPost(Uri uri, DynamicJsonObject data, bool retry = true, int retryCounter = 1)
		{
			int retrySleepTime = 1000;
			try
			{
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11
																								| SecurityProtocolType.Tls12;
				ServicePointManager.Expect100Continue = true;
				Dictionary<string, string> processedHeaders = GetProcessedHeaders();
				var response = serializer.Deserialize(httpService.Post(GetSecuredUri(uri), serializer.Serialize(data), processedHeaders));

				if (retry && response[response.Fields.First()].Errors.Count > 0 && retryCounter < 10)
				{
					ConnectionInfo.SecurityToken = GetSecurityToken();
					httpService = new HttpService(authManger, ConnectionInfo);
					Thread.Sleep(retrySleepTime * retryCounter);
					return DoPost(uri, data, true, retryCounter++);
				}

				return response;
			}
			catch (Exception)
			{
				if (retryCounter < 10)
				{
					Thread.Sleep(retrySleepTime * retryCounter);
					return DoPost(uri, data, true, retryCounter++);
				}
				throw;
			}
		}
Example #21
0
 public Task Delete()
 {
     return(Delete(HttpService.GetNewCancellationToken()));
 }
Example #22
0
 public NationalCNILPageViewModel(HttpService httpService, INavigationService navigationService, IPageDialogService dialogService, SettingsModel settings, AppRepository documentsRepository) : base(httpService, navigationService, dialogService, settings, documentsRepository)
 {
 }
        private async Task <BulkUploadOperation> SubmitUploadAsyncImpl(SubmitUploadParameters parameters)
        {
            var request = new GetBulkUploadUrlRequest
            {
                ResponseMode = parameters.ResponseMode
            };

            GetBulkUploadUrlResponse getUploadUrlResponse;

            using (var apiService = new ServiceClient <IBulkService>(_authorizationData, _apiEnvironment))
            {
                try
                {
                    getUploadUrlResponse = await apiService.CallAsync((s, r) => s.GetBulkUploadUrlAsync(r), request).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    throw new CouldNotSubmitBulkUploadException("Get upload url failed.", e);
                }
            }

            var uploadUrl = getUploadUrlResponse.UploadUrl;

            Action <HttpRequestHeaders> addHeaders = headers =>
            {
                headers.Add("DeveloperToken", _authorizationData.DeveloperToken);
                headers.Add("CustomerId", _authorizationData.CustomerId.ToString());
                headers.Add("AccountId", _authorizationData.AccountId.ToString());

                _authorizationData.Authentication.AddAuthenticationHeaders(headers);
            };

            string effectiveFileUploadPath = parameters.UploadFilePath;

            if (parameters.RenameUploadFileToMatchRequestId)
            {
                effectiveFileUploadPath = RenameUploadFileToMatchRequestId(effectiveFileUploadPath, getUploadUrlResponse);
            }

            var shouldCompress = parameters.CompressUploadFile && Path.GetExtension(effectiveFileUploadPath) != ".zip";

            string compressedFilePath = null;

            if (shouldCompress)
            {
                compressedFilePath = CompressUploadFile(effectiveFileUploadPath);

                effectiveFileUploadPath = compressedFilePath;
            }

            await HttpService.UploadFileAsync(new Uri(uploadUrl), effectiveFileUploadPath, addHeaders, UploadHttpTimeout).ConfigureAwait(false);

            if (shouldCompress && compressedFilePath != null)
            {
                FileSystem.DeleteFile(compressedFilePath);
            }

            return(new BulkUploadOperation(getUploadUrlResponse.RequestId, _authorizationData, getUploadUrlResponse.TrackingId, _apiEnvironment)
            {
                StatusPollIntervalInMilliseconds = StatusPollIntervalInMilliseconds,
                DownloadHttpTimeout = DownloadHttpTimeout
            });
        }
Example #24
0
 public Task <ParticipantAudio> GetParticipantAudio()
 {
     return(GetParticipantAudio(HttpService.GetNewCancellationToken()));
 }
Example #25
0
        private void SetupMessaging(
            TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
            IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue, RunProjections runProjections)
        {
            _coreQueues = new List<QueuedHandler>();
            _managerInputBus = new InMemoryBus("manager input bus");
            _managerInputQueue = new QueuedHandler(_managerInputBus, "Projections Master");
            while (_coreQueues.Count < _projectionWorkerThreadCount)
            {
                var coreInputBus = new InMemoryBus("bus");
                var coreQueue = new QueuedHandler(
                    coreInputBus, "Projection Core #" + _coreQueues.Count, groupName: "Projection Core");
                var projectionNode = new ProjectionWorkerNode(db, coreQueue, timeProvider, runProjections);
                projectionNode.SetupMessaging(coreInputBus);


                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: coreQueue, externalRequestQueue: mainQueue);
                // forwarded messages
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadEvent>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadAllEventsForward>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.WriteEvents>(forwarder);


                if (runProjections >= RunProjections.System)
                {
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.StateReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.ResultReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.StatisticsReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Started>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Stopped>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Faulted>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Prepared>(_managerInputQueue));

                }
                projectionNode.CoreOutput.Subscribe(timerService);


                projectionNode.CoreOutput.Subscribe(Forwarder.Create<Message>(coreQueue)); // forward all

                coreInputBus.Subscribe(new UnwrapEnvelopeHandler());

                _coreQueues.Add(coreQueue);
            }

            _managerInputBus.Subscribe(
            Forwarder.CreateBalancing<FeedReaderMessage.ReadPage>(_coreQueues.Cast<IPublisher>().ToArray()));

            _projectionManagerNode = ProjectionManagerNode.Create(
                db, _managerInputQueue, httpForwarder, httpServices, networkSendQueue,
                _coreQueues.Cast<IPublisher>().ToArray(), runProjections);
            _projectionManagerNode.SetupMessaging(_managerInputBus);
            {
                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: _managerInputQueue, externalRequestQueue: mainQueue);
                _projectionManagerNode.Output.Subscribe<ClientMessage.ReadEvent>(forwarder);
                _projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder);
                _projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder);
                _projectionManagerNode.Output.Subscribe<ClientMessage.WriteEvents>(forwarder);
                _projectionManagerNode.Output.Subscribe(
                    Forwarder.Create<ProjectionManagementMessage.RequestSystemProjections>(mainQueue));
                _projectionManagerNode.Output.Subscribe(Forwarder.Create<Message>(_managerInputQueue));

                _projectionManagerNode.Output.Subscribe(timerService);

                // self forward all

                mainBus.Subscribe(Forwarder.Create<SystemMessage.StateChangeMessage>(_managerInputQueue));
                _managerInputBus.Subscribe(new UnwrapEnvelopeHandler());
            }
        }
Example #26
0
 public Task <byte[]> GetContactPhone()
 {
     return(GetContactPhone(HttpService.GetNewCancellationToken()));
 }
Example #27
0
        public ActionResult GetRedPacket()
        {
            ViewBag.state = "2";
            ViewBag.err   = "";
            string flow    = Request["flow"];
            string redcode = Request["redcode"];
            string rurl    = Request["rurl"];//成功后的返回页
            //红包相关检测
            M_WX_RedDetail detMod = new M_WX_RedDetail();

            try
            {
                detMod = detBll.SelModelByCode(redcode);
                Appinfo uaMod = uaBll.SelModelByUid(mu.UserID, "wechat");
                if (detMod == null)
                {
                    ViewBag.err = "红包不存在";
                }
                else if (detMod.ZStatus != 1)
                {
                    ViewBag.err = "该红包已经被使用";
                }
                else if (detMod.Amount < 1 || detMod.Amount > 200)
                {
                    ViewBag.err = "红包金额不正确";
                }
                if (!string.IsNullOrEmpty(ViewBag.err))
                {
                    return(View("RedPacket"));
                }
                M_WX_RedPacket redMod = redBll.SelReturnModel(detMod.MainID);
                if (!redMod.Flow.Equals(flow))
                {
                    ViewBag.err = "匹配码不正确";
                }
                else if (redMod.SDate > DateTime.Now)
                {
                    ViewBag.err = "活动尚未开始";
                }
                else if (redMod.EDate < DateTime.Now)
                {
                    ViewBag.err = "活动已经结束";
                }
                if (!string.IsNullOrEmpty(ViewBag.err))
                {
                    return(View("RedPacket"));
                }
                WxAPI api = WxAPI.Code_Get(redMod.AppID);
                WxAPI.AutoSync(Request.RawUrl, api.AppId);
                if (mu.IsNull)
                {
                    ViewBag.err = "用户不存在";
                }
                if (uaMod == null)
                {
                    ViewBag.err = "用户信息不存在";
                }
                if (!string.IsNullOrEmpty(ViewBag.err))
                {
                    return(View("RedPacket"));
                }
                //-------------------
                string apiUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
                //生成提交参数
                WxPayData wxdata = new WxPayData();
                wxdata.SetValue("nonce_str", WxAPI.nonce);
                wxdata.SetValue("mch_billno", api.AppId.Pay_AccountID + DateTime.Now.ToString("yyyyMMdd") + function.GetRandomString(10, 2));
                wxdata.SetValue("mch_id", api.AppId.Pay_AccountID);
                wxdata.SetValue("wxappid", api.AppId.APPID);
                wxdata.SetValue("send_name", SiteConfig.SiteInfo.SiteName);
                //接受红包的用户用户在wxappid下的openid
                wxdata.SetValue("re_openid", uaMod.OpenID);//oDTTbwLa7WuySP0WcJJzYJmErCQ4
                wxdata.SetValue("total_amount", (int)(detMod.Amount * 100));
                wxdata.SetValue("total_num", 1);
                wxdata.SetValue("wishing", redMod.Wishing);   //红包祝福语
                wxdata.SetValue("client_ip", "58.215.75.11"); //调用接口的机器IP地址
                wxdata.SetValue("act_name", redMod.Name);     //活动名称
                wxdata.SetValue("remark", redMod.Remind);
                wxdata.SetValue("sign", wxdata.MakeSign());
                //随机码,签名
                string xml      = wxdata.ToXml();
                string response = HttpService.Post(xml, apiUrl, true, 60, api.AppId);
                //------------------------发放完成(不论成功失败均算已领取,记录好返回)
                detMod.UserID   = mu.UserID;
                detMod.UserName = mu.UserName;
                detMod.UseTime  = DateTime.Now.ToString();
                //WxPayData result = new WxPayData(api.AppId.Pay_Key);
                //result.FromXml(response);
                //if (result.GetValue("return_code").ToString().Equals("SUCCESS"))//return_msg
                //{
                //    detMod.ZStatus = 99;
                //}
                //else
                //{
                //    detMod.ZStatus = -1;
                //    detMod.Remind = response;
                //}
                detMod.ZStatus = 99; detMod.Remind = response;
                detBll.UpdateByID(detMod);
                ViewBag.state  = "3";
                ViewBag.amount = detMod.Amount.ToString("f2");
                return(View("RedPacket"));
            }
            catch (Exception ex)
            {
                ZLLog.L(ZLEnum.Log.pay, "微信红包异常,领取码:" + redcode + ",原因:" + ex.Message);
                ViewBag.state = "3";
                ViewBag.err   = ex.Message;
                //如异常,该红包禁用,等待管理员审核
                detMod.ZStatus = -1;
                detMod.Remind  = ex.Message;
                detBll.UpdateByID(detMod);
                return(View("RedPacket"));
            }
        }
 public HttpServiceTests()
 {
     _httpService = new HttpService();
 }
Example #29
0
 public async Task <MyOnlineMeeting> Update(CancellationToken cancellationToken)
 {
     return(await HttpService.Put <MyOnlineMeeting>(Self, this, cancellationToken));
 }
Example #30
0
 public Task <MyOnlineMeeting> Update()
 {
     return(Update(HttpService.GetNewCancellationToken()));
 }
Example #31
0
 public async Task Delete(CancellationToken cancellationToken)
 {
     await HttpService.Delete(Self, cancellationToken);
 }
		/// <summary>
		/// Logs this API out from any connection to Rally and clears the authentication configuration.
		/// </summary>
		/// <example>
		/// <code language="C#">
		/// RallyRestApi restApi = new RallyRestApi();
		/// WebProxy myProxy = new WebProxy();
		/// restApi.AuthenticateWithZSessionID("*****@*****.**", "zSessionID", proxy: myProxy);
		/// 
		/// restApi.Logout();
		/// </code>
		/// </example>
		public void Logout()
		{
			AuthenticationState = AuthenticationResult.NotAuthorized;
			ConnectionInfo = null;
			httpService = null;
		}
Example #33
0
        public SingleVNode(TFChunkDb db, SingleVNodeSettings vNodeSettings, SingleVNodeAppSettings appSettings)
        {
            Ensure.NotNull(db, "db");
            Ensure.NotNull(vNodeSettings, "vNodeSettings");

            db.OpenVerifyAndClean();

            _tcpEndPoint = vNodeSettings.ExternalTcpEndPoint;
            _httpEndPoint = vNodeSettings.HttpEndPoint;

            _outputBus = new InMemoryBus("OutputBus");
            _controller = new SingleVNodeController(Bus, _httpEndPoint);
            _mainQueue = new QueuedHandler(_controller, "MainQueue");
            _controller.SetMainQueue(MainQueue);

            //MONITORING
            var monitoringInnerBus = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false);
            var monitoringRequestBus = new InMemoryBus("MonitoringRequestBus", watchSlowMsg: false);
            var monitoringQueue = new QueuedHandler(monitoringInnerBus, "MonitoringQueue", watchSlowMsg: true, slowMsgThresholdMs: 100);
            var monitoring = new MonitoringService(monitoringQueue, monitoringRequestBus, db.Config.WriterCheckpoint, appSettings.StatsPeriod);
            Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.SystemInit, Message>());
            Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.BecomeShuttingDown, Message>());
            monitoringInnerBus.Subscribe<SystemMessage.SystemInit>(monitoring);
            monitoringInnerBus.Subscribe<SystemMessage.BecomeShuttingDown>(monitoring);
            monitoringInnerBus.Subscribe<MonitoringMessage.GetFreshStats>(monitoring);

            //STORAGE SUBSYSTEM
            var indexPath = Path.Combine(db.Config.Path, "index");
            var tableIndex = new TableIndex(indexPath,
                                            () => new HashListMemTable(),
                                            new InMemoryCheckpoint(),
                                            maxSizeForMemory: 1000000,
                                            maxTablesPerLevel: 2);

            var readIndex = new ReadIndex(_mainQueue,
                                          db,
                                          () => new TFChunkReader(db, db.Config.WriterCheckpoint),
                                          TFConsts.ReadIndexReaderCount,
                                          db.Config.WriterCheckpoint,
                                          tableIndex,
                                          new XXHashUnsafe());
            var writer = new TFChunkWriter(db);
            var storageWriter = new StorageWriter(_mainQueue, _outputBus, writer, readIndex);
            var storageReader = new StorageReader(_mainQueue, _outputBus, readIndex, TFConsts.StorageReaderHandlerCount);
            monitoringRequestBus.Subscribe<MonitoringMessage.InternalStatsRequest>(storageReader);

            var chaser = new TFChunkChaser(db,
                                           db.Config.WriterCheckpoint,
                                           db.Config.GetNamedCheckpoint(Checkpoint.Chaser));
            var storageChaser = new StorageChaser(_mainQueue, chaser);
            _outputBus.Subscribe<SystemMessage.SystemInit>(storageChaser);
            _outputBus.Subscribe<SystemMessage.SystemStart>(storageChaser);
            _outputBus.Subscribe<SystemMessage.BecomeShuttingDown>(storageChaser);

            var storageScavenger = new StorageScavenger(db, readIndex);
            _outputBus.Subscribe<SystemMessage.ScavengeDatabase>(storageScavenger);

            //TCP
            var tcpService = new TcpService(MainQueue, _tcpEndPoint);
            Bus.Subscribe<SystemMessage.SystemInit>(tcpService);
            Bus.Subscribe<SystemMessage.SystemStart>(tcpService);
            Bus.Subscribe<SystemMessage.BecomeShuttingDown>(tcpService);

            //HTTP
            HttpService = new HttpService(MainQueue, _httpEndPoint.ToHttpUrl());
            Bus.Subscribe<SystemMessage.SystemInit>(HttpService);
            Bus.Subscribe<SystemMessage.BecomeShuttingDown>(HttpService);
            Bus.Subscribe<HttpMessage.SendOverHttp>(HttpService);
            Bus.Subscribe<HttpMessage.UpdatePendingRequests>(HttpService);
            HttpService.SetupController(new AdminController(MainQueue));
            HttpService.SetupController(new PingController());
            HttpService.SetupController(new StatController(monitoringQueue));
            HttpService.SetupController(new ReadEventDataController(MainQueue));
            HttpService.SetupController(new AtomController(MainQueue));
            HttpService.SetupController(new WebSiteController(MainQueue));

            //REQUEST MANAGEMENT
            var requestManagement = new RequestManagementService(MainQueue, 1, 1);
            Bus.Subscribe<ReplicationMessage.EventCommited>(requestManagement);
            Bus.Subscribe<ReplicationMessage.CreateStreamRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.WriteRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.TransactionStartRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.TransactionWriteRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.TransactionCommitRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.DeleteStreamRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.RequestCompleted>(requestManagement);
            Bus.Subscribe<ReplicationMessage.CommitAck>(requestManagement);
            Bus.Subscribe<ReplicationMessage.PrepareAck>(requestManagement);
            Bus.Subscribe<ReplicationMessage.WrongExpectedVersion>(requestManagement);
            Bus.Subscribe<ReplicationMessage.InvalidTransaction>(requestManagement);
            Bus.Subscribe<ReplicationMessage.StreamDeleted>(requestManagement);
            Bus.Subscribe<ReplicationMessage.PreparePhaseTimeout>(requestManagement);
            Bus.Subscribe<ReplicationMessage.CommitPhaseTimeout>(requestManagement);

            var clientService = new ClientService();
            Bus.Subscribe<TcpMessage.ConnectionClosed>(clientService);
            Bus.Subscribe<ClientMessage.SubscribeToStream>(clientService);
            Bus.Subscribe<ClientMessage.UnsubscribeFromStream>(clientService);
            Bus.Subscribe<ClientMessage.SubscribeToAllStreams>(clientService);
            Bus.Subscribe<ClientMessage.UnsubscribeFromAllStreams>(clientService);
            Bus.Subscribe<ReplicationMessage.EventCommited>(clientService);

            //TIMER
            //var timer = new TimerService(new TimerBasedScheduler(new RealTimer(), new RealTimeProvider()));
            TimerService = new TimerService(new ThreadBasedScheduler(new RealTimeProvider()));
            Bus.Subscribe<TimerMessage.Schedule>(TimerService);

            MainQueue.Start();
            monitoringQueue.Start();
        }
Example #34
0
 public async Task <byte[]> GetContactPhone(CancellationToken cancellationToken)
 {
     return(await HttpService.GetBinary(Links.contactPhoto, cancellationToken));
 }
Example #35
0
 public async Task ChangeVisibility(bool includeInContactCard)
 {
     await ChangeVisibility(includeInContactCard, HttpService.GetNewCancellationToken());
 }
Example #36
0
 public Task <ContactPresence> GetContactPresence()
 {
     return(GetContactPresence(HttpService.GetNewCancellationToken()));
 }
Example #37
0
        public async Task <TResponse <DatatableResponse <GetCustomerPagingResponse> > > GetByPaging(DatatableRequest request)
        {
            try
            {
                var code            = string.Empty;
                var name            = string.Empty;
                var provinceId      = 0;
                var districtId      = 0;
                var wardId          = 0;
                var address         = string.Empty;
                var phone           = string.Empty;
                var email           = string.Empty;
                var customerGroupId = 0;
                var customerVipId   = 0;
                if (request?.Columns != null)
                {
                    if (request.Columns.Any())
                    {
                        code = request.Columns[0]
                               .Search?.Value ?? string.Empty;
                        name = request.Columns[1]
                               .Search?.Value ?? string.Empty;
                        var province = request.Columns[2]
                                       .Search?.Value ?? string.Empty;
                        var district = request.Columns[3]
                                       .Search?.Value ?? string.Empty;
                        var ward = request.Columns[4]
                                   .Search?.Value ?? string.Empty;
                        address = request.Columns[5]
                                  .Search?.Value ?? string.Empty;
                        phone = request.Columns[6]
                                .Search?.Value ?? string.Empty;
                        email = request.Columns[7]
                                .Search?.Value ?? string.Empty;
                        var customerGroup = request.Columns[8]
                                            .Search?.Value ?? string.Empty;
                        var customerVip = request.Columns[9]
                                          .Search?.Value ?? string.Empty;

                        if (!string.IsNullOrEmpty(province))
                        {
                            int.TryParse(province,
                                         out provinceId);
                        }

                        if (!string.IsNullOrEmpty(district))
                        {
                            int.TryParse(district,
                                         out districtId);
                        }

                        if (!string.IsNullOrEmpty(ward))
                        {
                            int.TryParse(ward,
                                         out wardId);
                        }

                        if (!string.IsNullOrEmpty(customerGroup))
                        {
                            int.TryParse(customerGroup,
                                         out customerGroupId);
                        }

                        if (!string.IsNullOrEmpty(customerVip))
                        {
                            int.TryParse(customerVip,
                                         out customerVipId);
                        }
                    }
                }

                var start = 1;

                if (request != null)
                {
                    start = request.Start / request.Length + 1;
                }

                var columnOrder = "date_updated";
                var sortDir     = "DESC";

                if (request?.Order != null &&
                    request.Order.Any())
                {
                    if (request.Columns != null)
                    {
                        columnOrder = request.Columns[request.Order[0]
                                                      .Column]
                                      .Data;
                        sortDir = request.Order[0]
                                  .Dir.ToUpper();
                    }
                }

                var url = string.Format(ApiUrl.CUSTOMER_GET_BY_PAGING,
                                        code,
                                        name,
                                        provinceId,
                                        districtId,
                                        wardId,
                                        address,
                                        phone,
                                        email,
                                        customerGroupId,
                                        customerVipId,
                                        start,
                                        request?.Length ?? 10,
                                        columnOrder,
                                        sortDir);

                var response = await HttpService.Send <PageResult <GetCustomerPagingResponse> >(url,
                                                                                                null,
                                                                                                HttpMethod.Get,
                                                                                                true);

                if (response.IsSuccess)
                {
                    return(await Ok(new DatatableResponse <GetCustomerPagingResponse>
                    {
                        Draw = request?.Draw ?? 1,
                        RecordsFiltered = response.Data.TotalCount,
                        RecordsTotal = response.Data.TotalCount,
                        Data = response.Data.Data.ToList()
                    }));
                }

                return(await Fail <DatatableResponse <GetCustomerPagingResponse> >(response.Message));
            }
            catch (Exception exception)
            {
                return(await Fail <DatatableResponse <GetCustomerPagingResponse> >(exception));
            }
        }
Example #38
0
 public async Task <OnlineMeetingExtensions> GetOnlineMeetingExtensions(CancellationToken cancellationToken)
 {
     return(await HttpService.Get <OnlineMeetingExtensions>(Links.onlineMeetingExtensions, cancellationToken));
 }
Example #39
0
        public ClusterVNode(TFChunkDb db,
                            ClusterVNodeSettings vNodeSettings,
                            IGossipSeedSource gossipSeedSource,
                            params ISubsystem[] subsystems)
        {
            Ensure.NotNull(db, "db");
            Ensure.NotNull(vNodeSettings, "vNodeSettings");
            Ensure.NotNull(gossipSeedSource, "gossipSeedSource");

            var isSingleNode = vNodeSettings.ClusterNodeCount == 1;

            _nodeInfo = vNodeSettings.NodeInfo;
            _mainBus  = new InMemoryBus("MainBus");

            var forwardingProxy = new MessageForwardingProxy();

            // MISC WORKERS
            _workerBuses = Enumerable.Range(0, vNodeSettings.WorkerThreads).Select(queueNum =>
                                                                                   new InMemoryBus(string.Format("Worker #{0} Bus", queueNum + 1),
                                                                                                   watchSlowMsg: true,
                                                                                                   slowMsgThreshold: TimeSpan.FromMilliseconds(200))).ToArray();
            _workersHandler = new MultiQueuedHandler(
                vNodeSettings.WorkerThreads,
                queueNum => new QueuedHandlerThreadPool(_workerBuses[queueNum],
                                                        string.Format("Worker #{0}", queueNum + 1),
                                                        groupName: "Workers",
                                                        watchSlowMsg: true,
                                                        slowMsgThreshold: TimeSpan.FromMilliseconds(200)));

            _controller = new ClusterVNodeController(_mainBus, _nodeInfo, db, vNodeSettings, this, forwardingProxy);
            _mainQueue  = new QueuedHandler(_controller, "MainQueue");

            _controller.SetMainQueue(_mainQueue);

            _subsystems = subsystems;
            //SELF
            _mainBus.Subscribe <SystemMessage.StateChangeMessage>(this);

            // MONITORING
            var monitoringInnerBus   = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false);
            var monitoringRequestBus = new InMemoryBus("MonitoringRequestBus", watchSlowMsg: false);
            var monitoringQueue      = new QueuedHandlerThreadPool(monitoringInnerBus, "MonitoringQueue", true, TimeSpan.FromMilliseconds(100));
            var monitoring           = new MonitoringService(monitoringQueue,
                                                             monitoringRequestBus,
                                                             _mainQueue,
                                                             db.Config.WriterCheckpoint,
                                                             db.Config.Path,
                                                             vNodeSettings.StatsPeriod,
                                                             _nodeInfo.ExternalHttp,
                                                             vNodeSettings.StatsStorage);

            _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.SystemInit, Message>());
            _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.StateChangeMessage, Message>());
            _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.BecomeShuttingDown, Message>());
            _mainBus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.BecomeShutdown, Message>());
            _mainBus.Subscribe(monitoringQueue.WidenFrom <ClientMessage.WriteEventsCompleted, Message>());
            monitoringInnerBus.Subscribe <SystemMessage.SystemInit>(monitoring);
            monitoringInnerBus.Subscribe <SystemMessage.StateChangeMessage>(monitoring);
            monitoringInnerBus.Subscribe <SystemMessage.BecomeShuttingDown>(monitoring);
            monitoringInnerBus.Subscribe <SystemMessage.BecomeShutdown>(monitoring);
            monitoringInnerBus.Subscribe <ClientMessage.WriteEventsCompleted>(monitoring);
            monitoringInnerBus.Subscribe <MonitoringMessage.GetFreshStats>(monitoring);

            var truncPos = db.Config.TruncateCheckpoint.Read();

            if (truncPos != -1)
            {
                Log.Info("Truncate checkpoint is present. Truncate: {0} (0x{0:X}), Writer: {1} (0x{1:X}), Chaser: {2} (0x{2:X}), Epoch: {3} (0x{3:X})",
                         truncPos, db.Config.WriterCheckpoint.Read(), db.Config.ChaserCheckpoint.Read(), db.Config.EpochCheckpoint.Read());
                var truncator = new TFChunkDbTruncator(db.Config);
                truncator.TruncateDb(truncPos);
            }

            // STORAGE SUBSYSTEM
            db.Open(vNodeSettings.VerifyDbHash);
            var indexPath  = Path.Combine(db.Config.Path, "index");
            var readerPool = new ObjectPool <ITransactionFileReader>(
                "ReadIndex readers pool", ESConsts.PTableInitialReaderCount, ESConsts.PTableMaxReaderCount,
                () => new TFChunkReader(db, db.Config.WriterCheckpoint));
            var tableIndex = new TableIndex(indexPath,
                                            () => new HashListMemTable(maxSize: vNodeSettings.MaxMemtableEntryCount * 2),
                                            () => new TFReaderLease(readerPool),
                                            maxSizeForMemory: vNodeSettings.MaxMemtableEntryCount,
                                            maxTablesPerLevel: 2,
                                            inMem: db.Config.InMemDb);
            var hash      = new XXHashUnsafe();
            var readIndex = new ReadIndex(_mainQueue,
                                          readerPool,
                                          tableIndex,
                                          hash,
                                          ESConsts.StreamInfoCacheCapacity,
                                          Application.IsDefined(Application.AdditionalCommitChecks),
                                          Application.IsDefined(Application.InfiniteMetastreams) ? int.MaxValue : 1);
            var writer       = new TFChunkWriter(db);
            var epochManager = new EpochManager(ESConsts.CachedEpochCount,
                                                db.Config.EpochCheckpoint,
                                                writer,
                                                initialReaderCount: 1,
                                                maxReaderCount: 5,
                                                readerFactory: () => new TFChunkReader(db, db.Config.WriterCheckpoint));

            epochManager.Init();

            var storageWriter = new ClusterStorageWriterService(_mainQueue, _mainBus, vNodeSettings.MinFlushDelay,
                                                                db, writer, readIndex.IndexWriter, epochManager,
                                                                () => readIndex.LastCommitPosition); // subscribes internally

            monitoringRequestBus.Subscribe <MonitoringMessage.InternalStatsRequest>(storageWriter);

            var storageReader = new StorageReaderService(_mainQueue, _mainBus, readIndex, ESConsts.StorageReaderThreadCount, db.Config.WriterCheckpoint);

            _mainBus.Subscribe <SystemMessage.SystemInit>(storageReader);
            _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(storageReader);
            _mainBus.Subscribe <SystemMessage.BecomeShutdown>(storageReader);
            monitoringRequestBus.Subscribe <MonitoringMessage.InternalStatsRequest>(storageReader);

            var chaser        = new TFChunkChaser(db, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint);
            var storageChaser = new StorageChaser(_mainQueue, db.Config.WriterCheckpoint, chaser, readIndex.IndexCommitter, epochManager);

#if DEBUG
            QueueStatsCollector.InitializeCheckpoints(
                _nodeInfo.DebugIndex, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint);
#endif
            _mainBus.Subscribe <SystemMessage.SystemInit>(storageChaser);
            _mainBus.Subscribe <SystemMessage.SystemStart>(storageChaser);
            _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(storageChaser);

            var storageScavenger = new StorageScavenger(db, tableIndex, hash, readIndex,
                                                        Application.IsDefined(Application.AlwaysKeepScavenged),
                                                        mergeChunks: !vNodeSettings.DisableScavengeMerging);

            // ReSharper disable RedundantTypeArgumentsOfMethod
            _mainBus.Subscribe <ClientMessage.ScavengeDatabase>(storageScavenger);
            // ReSharper restore RedundantTypeArgumentsOfMethod

            // AUTHENTICATION INFRASTRUCTURE - delegate to plugins
            var authenticationProvider = vNodeSettings.AuthenticationProviderFactory.BuildAuthenticationProvider(_mainQueue, _mainBus, _workersHandler, _workerBuses);

            Ensure.NotNull(authenticationProvider, "authenticationProvider");

            {
                // EXTERNAL TCP
                var extTcpService = new TcpService(_mainQueue, _nodeInfo.ExternalTcp, _workersHandler,
                                                   TcpServiceType.External, TcpSecurityType.Normal, new ClientTcpDispatcher(),
                                                   vNodeSettings.IntTcpHeartbeatInterval, vNodeSettings.IntTcpHeartbeatTimeout,
                                                   authenticationProvider, null);
                _mainBus.Subscribe <SystemMessage.SystemInit>(extTcpService);
                _mainBus.Subscribe <SystemMessage.SystemStart>(extTcpService);
                _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(extTcpService);

                // EXTERNAL SECURE TCP
                if (_nodeInfo.ExternalSecureTcp != null)
                {
                    var extSecTcpService = new TcpService(_mainQueue, _nodeInfo.ExternalSecureTcp, _workersHandler,
                                                          TcpServiceType.External, TcpSecurityType.Secure, new ClientTcpDispatcher(),
                                                          vNodeSettings.ExtTcpHeartbeatInterval, vNodeSettings.ExtTcpHeartbeatTimeout,
                                                          authenticationProvider, vNodeSettings.Certificate);
                    _mainBus.Subscribe <SystemMessage.SystemInit>(extSecTcpService);
                    _mainBus.Subscribe <SystemMessage.SystemStart>(extSecTcpService);
                    _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(extSecTcpService);
                }
                if (!isSingleNode)
                {
                    // INTERNAL TCP
                    var intTcpService = new TcpService(_mainQueue, _nodeInfo.InternalTcp, _workersHandler,
                                                       TcpServiceType.Internal, TcpSecurityType.Normal,
                                                       new InternalTcpDispatcher(),
                                                       vNodeSettings.IntTcpHeartbeatInterval, vNodeSettings.IntTcpHeartbeatTimeout,
                                                       authenticationProvider, null);
                    _mainBus.Subscribe <SystemMessage.SystemInit>(intTcpService);
                    _mainBus.Subscribe <SystemMessage.SystemStart>(intTcpService);
                    _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(intTcpService);

                    // INTERNAL SECURE TCP
                    if (_nodeInfo.InternalSecureTcp != null)
                    {
                        var intSecTcpService = new TcpService(_mainQueue, _nodeInfo.InternalSecureTcp, _workersHandler,
                                                              TcpServiceType.Internal, TcpSecurityType.Secure,
                                                              new InternalTcpDispatcher(),
                                                              vNodeSettings.IntTcpHeartbeatInterval, vNodeSettings.IntTcpHeartbeatTimeout,
                                                              authenticationProvider, vNodeSettings.Certificate);
                        _mainBus.Subscribe <SystemMessage.SystemInit>(intSecTcpService);
                        _mainBus.Subscribe <SystemMessage.SystemStart>(intSecTcpService);
                        _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(intSecTcpService);
                    }
                }
            }

            SubscribeWorkers(bus =>
            {
                var tcpSendService = new TcpSendService();
                // ReSharper disable RedundantTypeArgumentsOfMethod
                bus.Subscribe <TcpMessage.TcpSend>(tcpSendService);
                // ReSharper restore RedundantTypeArgumentsOfMethod
            });

            var httpAuthenticationProviders = new List <HttpAuthenticationProvider>
            {
                new BasicHttpAuthenticationProvider(authenticationProvider),
            };
            if (vNodeSettings.EnableTrustedAuth)
            {
                httpAuthenticationProviders.Add(new TrustedHttpAuthenticationProvider());
            }
            httpAuthenticationProviders.Add(new AnonymousHttpAuthenticationProvider());

            var httpPipe        = new HttpMessagePipe();
            var httpSendService = new HttpSendService(httpPipe, forwardRequests: true);
            _mainBus.Subscribe <SystemMessage.StateChangeMessage>(httpSendService);
            _mainBus.Subscribe(new WideningHandler <HttpMessage.SendOverHttp, Message>(_workersHandler));
            SubscribeWorkers(bus =>
            {
                bus.Subscribe <HttpMessage.HttpSend>(httpSendService);
                bus.Subscribe <HttpMessage.HttpSendPart>(httpSendService);
                bus.Subscribe <HttpMessage.HttpBeginSend>(httpSendService);
                bus.Subscribe <HttpMessage.HttpEndSend>(httpSendService);
                bus.Subscribe <HttpMessage.SendOverHttp>(httpSendService);
            });

            var adminController  = new AdminController(_mainQueue);
            var pingController   = new PingController();
            var infoController   = new InfoController();
            var statController   = new StatController(monitoringQueue, _workersHandler);
            var atomController   = new AtomController(httpSendService, _mainQueue, _workersHandler);
            var gossipController = new GossipController(_mainQueue, _workersHandler, vNodeSettings.GossipTimeout);
            var electController  = new ElectController(_mainQueue);

            // HTTP SENDERS
            gossipController.SubscribeSenders(httpPipe);
            electController.SubscribeSenders(httpPipe);

            // EXTERNAL HTTP
            _externalHttpService = new HttpService(ServiceAccessibility.Public, _mainQueue, new TrieUriRouter(),
                                                   _workersHandler, vNodeSettings.HttpPrefixes);
            if (vNodeSettings.AdminOnPublic)
            {
                _externalHttpService.SetupController(adminController);
            }
            _externalHttpService.SetupController(pingController);
            _externalHttpService.SetupController(infoController);
            if (vNodeSettings.StatsOnPublic)
            {
                _externalHttpService.SetupController(statController);
            }
            _externalHttpService.SetupController(atomController);
            if (vNodeSettings.GossipOnPublic)
            {
                _externalHttpService.SetupController(gossipController);
            }

            _mainBus.Subscribe <SystemMessage.SystemInit>(_externalHttpService);
            _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(_externalHttpService);
            _mainBus.Subscribe <HttpMessage.PurgeTimedOutRequests>(_externalHttpService);
            // INTERNAL HTTP
            if (!isSingleNode)
            {
                _internalHttpService = new HttpService(ServiceAccessibility.Private, _mainQueue, new TrieUriRouter(),
                                                       _workersHandler, _nodeInfo.InternalHttp.ToHttpUrl());
                _internalHttpService.SetupController(adminController);
                _internalHttpService.SetupController(pingController);
                _internalHttpService.SetupController(infoController);
                _internalHttpService.SetupController(statController);
                _internalHttpService.SetupController(atomController);
                _internalHttpService.SetupController(gossipController);
                _internalHttpService.SetupController(electController);
            }
            // Authentication plugin HTTP
            vNodeSettings.AuthenticationProviderFactory.RegisterHttpControllers(_externalHttpService, _internalHttpService, httpSendService, _mainQueue, _workersHandler);
            if (_internalHttpService != null)
            {
                _mainBus.Subscribe <SystemMessage.SystemInit>(_internalHttpService);
                _mainBus.Subscribe <SystemMessage.BecomeShuttingDown>(_internalHttpService);
                _mainBus.Subscribe <HttpMessage.PurgeTimedOutRequests>(_internalHttpService);
            }

            SubscribeWorkers(bus =>
            {
                HttpService.CreateAndSubscribePipeline(bus, httpAuthenticationProviders.ToArray());
            });

            // REQUEST FORWARDING
            var forwardingService = new RequestForwardingService(_mainQueue, forwardingProxy, TimeSpan.FromSeconds(1));
            _mainBus.Subscribe <SystemMessage.SystemStart>(forwardingService);
            _mainBus.Subscribe <SystemMessage.RequestForwardingTimerTick>(forwardingService);
            _mainBus.Subscribe <ClientMessage.NotHandled>(forwardingService);
            _mainBus.Subscribe <ClientMessage.WriteEventsCompleted>(forwardingService);
            _mainBus.Subscribe <ClientMessage.TransactionStartCompleted>(forwardingService);
            _mainBus.Subscribe <ClientMessage.TransactionWriteCompleted>(forwardingService);
            _mainBus.Subscribe <ClientMessage.TransactionCommitCompleted>(forwardingService);
            _mainBus.Subscribe <ClientMessage.DeleteStreamCompleted>(forwardingService);

            // REQUEST MANAGEMENT
            var requestManagement = new RequestManagementService(_mainQueue,
                                                                 vNodeSettings.PrepareAckCount,
                                                                 vNodeSettings.CommitAckCount,
                                                                 vNodeSettings.PrepareTimeout,
                                                                 vNodeSettings.CommitTimeout);
            _mainBus.Subscribe <SystemMessage.SystemInit>(requestManagement);
            _mainBus.Subscribe <ClientMessage.WriteEvents>(requestManagement);
            _mainBus.Subscribe <ClientMessage.TransactionStart>(requestManagement);
            _mainBus.Subscribe <ClientMessage.TransactionWrite>(requestManagement);
            _mainBus.Subscribe <ClientMessage.TransactionCommit>(requestManagement);
            _mainBus.Subscribe <ClientMessage.DeleteStream>(requestManagement);
            _mainBus.Subscribe <StorageMessage.RequestCompleted>(requestManagement);
            _mainBus.Subscribe <StorageMessage.CheckStreamAccessCompleted>(requestManagement);
            _mainBus.Subscribe <StorageMessage.AlreadyCommitted>(requestManagement);
            _mainBus.Subscribe <StorageMessage.CommitAck>(requestManagement);
            _mainBus.Subscribe <StorageMessage.PrepareAck>(requestManagement);
            _mainBus.Subscribe <StorageMessage.WrongExpectedVersion>(requestManagement);
            _mainBus.Subscribe <StorageMessage.InvalidTransaction>(requestManagement);
            _mainBus.Subscribe <StorageMessage.StreamDeleted>(requestManagement);
            _mainBus.Subscribe <StorageMessage.RequestManagerTimerTick>(requestManagement);

            // SUBSCRIPTIONS
            var subscrBus   = new InMemoryBus("SubscriptionsBus", true, TimeSpan.FromMilliseconds(50));
            var subscrQueue = new QueuedHandlerThreadPool(subscrBus, "Subscriptions", false);
            _mainBus.Subscribe(subscrQueue.WidenFrom <SystemMessage.SystemStart, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <SystemMessage.BecomeShuttingDown, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <TcpMessage.ConnectionClosed, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <ClientMessage.SubscribeToStream, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <ClientMessage.UnsubscribeFromStream, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <SubscriptionMessage.PollStream, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <SubscriptionMessage.CheckPollTimeout, Message>());
            _mainBus.Subscribe(subscrQueue.WidenFrom <StorageMessage.EventCommitted, Message>());

            var subscription = new SubscriptionsService(_mainQueue, subscrQueue, readIndex);
            subscrBus.Subscribe <SystemMessage.SystemStart>(subscription);
            subscrBus.Subscribe <SystemMessage.BecomeShuttingDown>(subscription);
            subscrBus.Subscribe <TcpMessage.ConnectionClosed>(subscription);
            subscrBus.Subscribe <ClientMessage.SubscribeToStream>(subscription);
            subscrBus.Subscribe <ClientMessage.UnsubscribeFromStream>(subscription);
            subscrBus.Subscribe <SubscriptionMessage.PollStream>(subscription);
            subscrBus.Subscribe <SubscriptionMessage.CheckPollTimeout>(subscription);
            subscrBus.Subscribe <StorageMessage.EventCommitted>(subscription);

            // TIMER
            _timeProvider = new RealTimeProvider();
            _timerService = new TimerService(new ThreadBasedScheduler(_timeProvider));
            _mainBus.Subscribe <SystemMessage.BecomeShutdown>(_timerService);
            _mainBus.Subscribe <TimerMessage.Schedule>(_timerService);
            if (!isSingleNode)
            {
                // MASTER REPLICATION
                var masterReplicationService = new MasterReplicationService(_mainQueue, _nodeInfo.InstanceId, db, _workersHandler,
                                                                            epochManager, vNodeSettings.ClusterNodeCount);
                _mainBus.Subscribe <SystemMessage.SystemStart>(masterReplicationService);
                _mainBus.Subscribe <SystemMessage.StateChangeMessage>(masterReplicationService);
                _mainBus.Subscribe <ReplicationMessage.ReplicaSubscriptionRequest>(masterReplicationService);
                _mainBus.Subscribe <ReplicationMessage.ReplicaLogPositionAck>(masterReplicationService);

                // REPLICA REPLICATION
                var replicaService = new ReplicaService(_mainQueue, db, epochManager, _workersHandler, authenticationProvider,
                                                        _nodeInfo, vNodeSettings.UseSsl, vNodeSettings.SslTargetHost, vNodeSettings.SslValidateServer,
                                                        vNodeSettings.IntTcpHeartbeatTimeout, vNodeSettings.ExtTcpHeartbeatInterval);
                _mainBus.Subscribe <SystemMessage.StateChangeMessage>(replicaService);
                _mainBus.Subscribe <ReplicationMessage.ReconnectToMaster>(replicaService);
                _mainBus.Subscribe <ReplicationMessage.SubscribeToMaster>(replicaService);
                _mainBus.Subscribe <ReplicationMessage.AckLogPosition>(replicaService);
                _mainBus.Subscribe <StorageMessage.PrepareAck>(replicaService);
                _mainBus.Subscribe <StorageMessage.CommitAck>(replicaService);
                _mainBus.Subscribe <ClientMessage.TcpForwardMessage>(replicaService);
            }

            // ELECTIONS
            var electionsService = new ElectionsService(_mainQueue, _nodeInfo, vNodeSettings.ClusterNodeCount,
                                                        db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint,
                                                        epochManager, () => readIndex.LastCommitPosition, vNodeSettings.NodePriority);
            electionsService.SubscribeMessages(_mainBus);
            if (!isSingleNode)
            {
                // GOSSIP
                var gossip = new NodeGossipService(_mainQueue, gossipSeedSource, _nodeInfo, db.Config.WriterCheckpoint,
                                                   db.Config.ChaserCheckpoint, epochManager, () => readIndex.LastCommitPosition,
                                                   vNodeSettings.NodePriority, vNodeSettings.GossipInterval, vNodeSettings.GossipAllowedTimeDifference);
                _mainBus.Subscribe <SystemMessage.SystemInit>(gossip);
                _mainBus.Subscribe <GossipMessage.RetrieveGossipSeedSources>(gossip);
                _mainBus.Subscribe <GossipMessage.GotGossipSeedSources>(gossip);
                _mainBus.Subscribe <GossipMessage.Gossip>(gossip);
                _mainBus.Subscribe <GossipMessage.GossipReceived>(gossip);
                _mainBus.Subscribe <SystemMessage.StateChangeMessage>(gossip);
                _mainBus.Subscribe <GossipMessage.GossipSendFailed>(gossip);
                _mainBus.Subscribe <SystemMessage.VNodeConnectionEstablished>(gossip);
                _mainBus.Subscribe <SystemMessage.VNodeConnectionLost>(gossip);
            }
            _workersHandler.Start();
            _mainQueue.Start();
            monitoringQueue.Start();
            subscrQueue.Start();

            if (subsystems != null)
            {
                foreach (var subsystem in subsystems)
                {
                    var http = isSingleNode ? new [] { _externalHttpService } : new [] { _internalHttpService, _externalHttpService };
                    subsystem.Register(new StandardComponents(db, _mainQueue, _mainBus, _timerService, _timeProvider, httpSendService, http, _workersHandler));
                }
            }
        }
Example #40
0
 public Task <OnlineMeetingExtensions> GetOnlineMeetingExtensions()
 {
     return(GetOnlineMeetingExtensions(HttpService.GetNewCancellationToken()));
 }
Example #41
0
        public async Task ChangeVisibility(bool includeInContactCard, CancellationToken cancellationToken)
        {
            var uri = includeInContactCard ? Links.changeVisibility.Href + "?includeInContactCard" : Links.changeVisibility.Href;

            await HttpService.Post(uri, "", cancellationToken);
        }
Example #42
0
		void IModule.Install(ModuleManager manager)
		{
			_manager = manager;
			_client = manager.Client;
			_http = _client.Services.Get<HttpService>();
			_settings = _client.Services.Get<SettingsService>()
				.AddModule<GithubModule, Settings>(manager);

			manager.CreateCommands("repos", group =>
			{
				group.MinPermissions((int)PermissionLevel.BotOwner);

				group.CreateCommand("list")
					.Do(async e =>
					{
						StringBuilder builder = new StringBuilder();
						var settings = _settings.Load(e.Server);
						foreach (var repo in settings.Repos.OrderBy(x => x.Key))
							builder.AppendLine($"{repo.Key} [{string.Join(",", repo.Value.Branches)}] => {_client.GetChannel(repo.Value.ChannelId)?.Name ?? "Unknown"}");
						await _client.Reply(e, "Linked Repos", builder.ToString());
					});

				group.CreateCommand("add")
					.Parameter("githubrepo")
					.Parameter("channel", ParameterType.Optional)
					.Do(async e =>
					{
						var settings = _settings.Load(e.Server);
						Channel channel;
						if (e.Args[1] != "")
							channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text);
						else
							channel = e.Channel;
						if (channel == null) return;

						string url = FilterUrl(e.Args[0]);
						if (settings.AddRepo(url, channel.Id))
						{
							await _settings.Save(e.Server.Id, settings);
							await _client.Reply(e, $"Linked repo {url} to {channel.Name}.");
						}
						else
							await _client.Reply(e, $"Error: Repo {url} is already being watched.");
					});

				group.CreateCommand("remove")
					.Parameter("githubrepo")
					.Do(async e =>
					{
						var settings = _settings.Load(e.Server);
						string url = FilterUrl(e.Args[0]);
						if (settings.RemoveRepo(url))
						{
							await _settings.Save(e.Server.Id, settings);
							await _client.Reply(e, $"Unlinked repo {url}.");
						}
						else
							await _client.Reply(e, $"Error: Repo {url} is not currently being watched.");
					});

				group.CreateCommand("addbranch")
					.Parameter("githubrepo")
					.Parameter("branch")
					.Do(async e =>
					{
						var settings = _settings.Load(e.Server);
						string url = FilterUrl(e.Args[0]);
						var repo = settings.Repos[url];
						if (repo != null)
						{
							if (repo.AddBranch(e.Args[1]))
							{
								await _settings.Save(e.Server.Id, settings);
								await _client.Reply(e, $"Added branch {url}/{e.Args[1]}.");
							}
							else
								await _client.Reply(e, $"Error: Branch {url}/{e.Args[1]} is already being watched.");
						}
						else
							await _client.Reply(e, $"Error: Repo {url} is not currently being watched.");
					});

				group.CreateCommand("removebranch")
					.Parameter("githubrepo")
					.Parameter("branch")
					.Do(async e =>
					{
						var settings = _settings.Load(e.Server);
						string url = FilterUrl(e.Args[0]);
						var repo = settings.Repos[url];
						if (repo != null)
						{
							if (repo.RemoveBranch(e.Args[1]))
							{
								await _settings.Save(e.Server.Id, settings);
								await _client.Reply(e, $"Removed branch {url}/{e.Args[1]}.");
							}
							else
								await _client.Reply(e, $"Error: Branch {url}/{e.Args[1]} is not being watched.");
						}
						else
							await _client.Reply(e, $"Error: Repo {url} is not currently being watched.");
					});
			});

			_client.Connected += (s, e) =>
			{
				if (!_isRunning)
				{
					Task.Run(Run);
					_isRunning = true;
				}
			};
		}
Example #43
0
 public async Task <ContactPresence> GetContactPresence(CancellationToken cancellationToken)
 {
     return(await HttpService.Get <ContactPresence>(Links.contactPresence, cancellationToken));
 }
Example #44
0
 public async Task <MyOnlineMeeting> Get(CancellationToken cancellationToken)
 {
     return(await HttpService.Get <MyOnlineMeeting>(Self, cancellationToken));
 }
Example #45
0
        public static List<SingleInfo> StockTrace(List<string> stockCode)
        {
            List<SingleInfo> infos = new List<SingleInfo>();
            Regex matchSH = new Regex(@"sh\d{6}");
            Regex matchSZ = new Regex(@"sz\d{6}");
            lock (obj)
            {

                string xmlString = string.Empty;
                string stockCodeString = string.Empty;
                foreach (string code in stockCode)
                {
                    //stockCodeString += code.StartsWith("6") ?
                    //    string.Concat("sh", code) : string.Concat("sz", code);
                    stockCodeString += code;
                    stockCodeString += ",";
                }
                if (stockCodeString.Length > 0)
                {
                    HttpService web = new HttpService();
                    web.TargetUrl = "http://hq.sinajs.cn/list=" + stockCodeString;
                    web.RefererUrl = "http://hq.sinajs.cn/";
                    web.UserAgent = "StockTrace";
                    string htmlContent = web.GetHttp(true, false);

                    string[] stockInfo = htmlContent.Trim().Split(
                        new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                    #region 字符串说明
                    /*
                    00 var hq_str_sh600054="黄山旅游
                    01 15.19  昨开
                    02 15.19  今开
                    03 15.38  当前价格
                    04 15.65  最高
                    05 15.10  最低
                    06 15.38  委买
                    07 15.40  委卖
                    08 1498067   成交量
                    09 23140724  成交额
                    10 4500      买1
                    11 15.38
                    12 5862      买2
                    13 15.36
                    14 18700      买3
                    15 15.35
                    16 5000       买4
                    17 15.34
                    18 7300      买5
                    19 15.33
                    20 52100      卖1
                    21 15.40
                    22 900       卖2
                    23 15.41
                    24 3000         卖3
                    25 15.44
                    26 2800         卖4
                    27 15.45
                    28 500           买5
                    29 15.48
                    30 2009-03-12  日期
                    31 11:35:41"   时间
                     */
                    #endregion

                    foreach (string item in stockInfo)
                    {
                        int index = item.IndexOf('=');
                        if (index == -1)
                            continue;
                        string itemTemp = item.Substring(item.IndexOf('=') + 1).Replace("\"", "");
                        string[] OneStockInfo = itemTemp.Split(',');
                        //代码
                        string code = matchSH.Match(item).Value;
                        if (string.IsNullOrEmpty(code))
                        {
                            code = matchSZ.Match(item).Value;
                        }
                        //明细
                        if (OneStockInfo.Length == 32)
                        {
                            SingleInfo singleItem = new SingleInfo();
                            singleItem.StockCode = code;
                            singleItem.Name = OneStockInfo[0];
                            singleItem.YesterdayPrice = OneStockInfo[1];
                            singleItem.TodayPrice = OneStockInfo[2];
                            singleItem.PriceNow = OneStockInfo[3];
                            singleItem.HighPrice = OneStockInfo[4];
                            singleItem.LowPrice = OneStockInfo[5];
                            singleItem.ConsignBuyPrice = OneStockInfo[6];
                            singleItem.ConsignSellPrice = OneStockInfo[7];
                            singleItem.Turnover = OneStockInfo[8];
                            singleItem.TradingVolume = OneStockInfo[9];
                            singleItem.Buy1 = OneStockInfo[10];
                            singleItem.Buy1Price = OneStockInfo[11];
                            singleItem.Buy2 = OneStockInfo[12];
                            singleItem.Buy2Price = OneStockInfo[13];
                            singleItem.Buy3 = OneStockInfo[14];
                            singleItem.Buy3Price = OneStockInfo[15];
                            singleItem.Buy4 = OneStockInfo[16];
                            singleItem.Buy4Price = OneStockInfo[17];
                            singleItem.Buy5 = OneStockInfo[18];
                            singleItem.Buy5Price = OneStockInfo[19];
                            singleItem.Sell1 = OneStockInfo[20];
                            singleItem.Sell1Price = OneStockInfo[21];
                            singleItem.Sell2 = OneStockInfo[22];
                            singleItem.Sell2Price = OneStockInfo[23];
                            singleItem.Sell3 = OneStockInfo[24];
                            singleItem.Sell3Price = OneStockInfo[25];
                            singleItem.Sell4 = OneStockInfo[26];
                            singleItem.Sell4Price = OneStockInfo[27];
                            singleItem.Sell5 = OneStockInfo[28];
                            singleItem.Sell5Price = OneStockInfo[29];
                            singleItem.DataDate = OneStockInfo[30];
                            singleItem.DataTime = OneStockInfo[31];
                            infos.Add(singleItem);
                        }
                    }
                }
            }
            return infos;
        }
Example #46
0
 public Task <Conversation> GetConversation()
 {
     return(GetConversation(HttpService.GetNewCancellationToken()));
 }
Example #47
0
 public async Task <Conversation> GetConversation(CancellationToken cancellationToken)
 {
     return(await HttpService.Get <Conversation>(Links.conversation, cancellationToken));
 }
 public GetDomainsVideoService(HttpService httpService, ILogger <GetDomainsVideoService> logger)
 {
     _httpService = httpService;
     _logger      = logger;
 }
Example #49
0
        void IModule.Install(ModuleManager manager)
        {
            _manager = manager;
            _client = manager.Client;
            _http = _client.Services.Get<HttpService>();
            _settings = _client.Services.Get<SettingsService>()
                .AddModule<FeedModule, Settings>(manager);

            manager.CreateCommands("feeds", group =>
            {
                group.MinPermissions((int)PermissionLevel.BotOwner);

                group.CreateCommand("list")
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);
                        var response = settings.Feeds
                            .OrderBy(x => x.Key)
                            .Select(x => $"{x.Key} => {_client.GetChannel(x.Value.ChannelId)?.Name ?? "Unknown"}");
                        await _client.Reply(e, "Linked Feeds", response);
                    });

                group.CreateCommand("add")
                    .Parameter("url")
                    .Parameter("channel", ParameterType.Optional)
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);
                        Channel channel;
                        if (e.Args[1] != "")
                            channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text);
                        else
                            channel = e.Channel;
                        if (channel == null) return;

                        if (settings.AddFeed(e.Args[0], channel.Id))
                        {
                            await _settings.Save(e.Server, settings);
                            await _client.Reply(e, $"Linked feed {e.Args[0]} to {channel.Name}");
                        }
                        else
                            await _client.Reply(e, $"Feed {e.Args[0]} is already linked to a channel.");
                    });

                group.CreateCommand("remove")
                    .Parameter("url")
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);
                        if (settings.RemoveFeed(e.Args[0]))
                        {
                            await _settings.Save(e.Server, settings);
                            await _client.Reply(e, $"Unlinked feed {e.Args[0]}.");
                        }
                        else
                            await _client.Reply(e, $"Feed {e.Args[0]} is not currently linked to a channel.");
                    });
            });

            _client.Connected += (s, e) =>
            {
                if (!_isRunning)
                {
                    Task.Run(Run);
                    _isRunning = true;
                }
            };
        }
Example #50
0
 public async Task Eject(CancellationToken cancellationToken)
 {
     await HttpService.Post(Links.eject, "", cancellationToken);
 }
		/// <summary>
		/// Performs get as a post action.
		/// </summary>
		/// <exception cref="RallyUnavailableException">Rally returned an HTML page. This usually occurs when Rally is off-line. Please check the ErrorMessage property for more information.</exception>
		/// <exception cref="RallyFailedToDeserializeJson">The JSON returned by Rally was not able to be deserialized. Please check the JsonData property for what was returned by Rally.</exception>
		private DynamicJsonObject DoGetAsPost(Request request, bool retry = true, int retryCounter = 1)
		{
			int retrySleepTime = 1000;
			try
			{
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11
																							 | SecurityProtocolType.Tls12;
				ServicePointManager.Expect100Continue = true;
				Dictionary<string, string> data = request.GetDataToSend();
				Uri uri = GetFullyQualifiedUri(request.ShortRequestUrl);
				Dictionary<string, string> processedHeaders = GetProcessedHeaders();
				DynamicJsonObject response = serializer.Deserialize(httpService.GetAsPost(GetSecuredUri(uri), data, processedHeaders));

				if (retry && response[response.Fields.First()].Errors.Count > 0 && retryCounter < 10)
				{
					ConnectionInfo.SecurityToken = GetSecurityToken();
					httpService = new HttpService(authManger, ConnectionInfo);
					Thread.Sleep(retrySleepTime * retryCounter);
					return DoGetAsPost(request, true, retryCounter++);
				}

				return response;
			}
			catch (Exception)
			{
				if (retryCounter < 10)
				{
					Thread.Sleep(retrySleepTime * retryCounter);
					return DoGetAsPost(request, true, retryCounter++);
				}
				throw;
			}
		}
Example #52
0
 public Task <Me> GetMe()
 {
     return(GetMe(HttpService.GetNewCancellationToken()));
 }
		private AuthenticationResult AuthenticateWithConnectionInfoBaseMethod(ConnectionInfo connectionInfo, bool allowSSO,
				out string exceptionMessage)
		{
			exceptionMessage = "";

			this.ConnectionInfo = connectionInfo;
			httpService = new HttpService(authManger, connectionInfo);

			Headers = new Dictionary<HeaderType, string>();
			Assembly assembly = typeof(RallyRestApi).Assembly;
			Headers.Add(HeaderType.Library, String.Format("{0} v{1}",
					((AssemblyTitleAttribute)Attribute.GetCustomAttribute(assembly,
					typeof(AssemblyTitleAttribute), false)).Title, assembly.GetName().Version.ToString()));
			Headers.Add(HeaderType.Vendor,
					((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(assembly,
					typeof(AssemblyCompanyAttribute), false)).Company);
			Headers.Add(HeaderType.Name, ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(assembly,
					typeof(AssemblyTitleAttribute), false)).Title);
			Headers.Add(HeaderType.Version, assembly.GetName().Version.ToString());
			Headers.Add(HeaderType.Guid, Guid.NewGuid().ToString());

			try
			{
				dynamic userObject = GetCurrentUser("UserName");
				ConnectionInfo.UserName = userObject["UserName"];
				AuthenticationState = AuthenticationResult.Authenticated;
			}
			catch (Exception e)
			{
				if ((e is WebException) && (((WebException)e).Status == WebExceptionStatus.ConnectFailure))
				{
					throw;
				}

				if ((allowSSO) && (!httpService.PerformSsoAuthentication()))
				{
					Logout();
					throw;
				}

				AuthenticationState = AuthenticationResult.NotAuthorized;
				exceptionMessage = e.Message;
			}

			return AuthenticationState;
		}
Example #54
0
 public async Task <Me> GetMe(CancellationToken cancellationToken)
 {
     return(await HttpService.Get <Me>(Links.me, cancellationToken));
 }
Example #55
0
        void IModule.Install(ModuleManager manager)
        {
            _manager = manager;
            _client = manager.Client;
            _http = _client.Services.Get<HttpService>();
            _settings = _client.Services.Get<SettingsService>()
                .AddModule<TwitchModule, Settings>(manager);

            manager.CreateCommands("streams", group =>
            {
                group.MinPermissions((int)PermissionLevel.BotOwner);

                group.CreateCommand("list")
                    .Do(async e =>
                    {
                        StringBuilder builder = new StringBuilder();
                        var settings = _settings.Load(e.Server);
                        foreach (var channel in settings.Channels)
                            builder.AppendLine($"{_client.GetChannel(channel.Key)}:\n   {string.Join(", ", channel.Value.Streams.Select(x => x.Key))}");
                        await _client.Reply(e, "Linked Streams", builder.ToString());
                    });

                group.CreateCommand("add")
                    .Parameter("twitchuser")
                    .Parameter("channel", ParameterType.Optional)
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);

                        Channel channel;
                        if (e.Args[1] != "")
                            channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text);
                        else
                            channel = e.Channel;
                        if (channel == null) return;

                        var channelSettings = settings.GetOrAddChannel(channel.Id);
                        if (channelSettings.AddStream(e.Args[0]))
                        {
                            await _settings.Save(e.Server, settings);
                            await _client.Reply(e, $"Linked stream {e.Args[0]} to {channel.Name}.");
                        }
                        else
                            await _client.Reply(e, $"Stream {e.Args[0]} is already linked to {channel.Name}.");
                    });

                group.CreateCommand("remove")
                    .Parameter("twitchuser")
                    .Parameter("channel", ParameterType.Optional)
                    .Do(async e =>
                    {
                        var settings = _settings.Load(e.Server);
                        Channel channel;
                        if (e.Args[1] != "")
                            channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text);
                        else
                            channel = e.Channel;
                        if (channel == null) return;

                        var channelSettings = settings.GetOrAddChannel(channel.Id);
                        if (channelSettings.RemoveStream(e.Args[0]))
                        {
                            await _settings.Save(e.Server.Id, settings);
                            await _client.Reply(e, $"Unlinked stream {e.Args[0]} from {channel.Name}.");
                        }
                        else
                            await _client.Reply(e, $"Stream {e.Args[0]} is not currently linked to {channel.Name}.");
                    });

                group.CreateGroup("set", set =>
                {
                    set.CreateCommand("sticky")
                        .Parameter("value")
                        .Parameter("channel", ParameterType.Optional)
                        .Do(async e =>
                        {
                            bool value = false;
                            bool.TryParse(e.Args[0], out value);

                            Channel channel;
                            if (e.Args[1] != "")
                                channel = await _client.FindChannel(e, e.Args[1], ChannelType.Text);
                            else
                                channel = e.Channel;
                            if (channel == null) return;

                            var settings = _settings.Load(e.Server);
                            var channelSettings = settings.GetOrAddChannel(channel.Id);
                            if (channelSettings.UseSticky && !value && channelSettings.StickyMessageId != null)
                            {
                                var msg = channel.GetMessage(channelSettings.StickyMessageId.Value);
                                try { await msg.Delete(); }
                                catch (HttpException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
                            }
                            channelSettings.UseSticky = value;
                            await _settings.Save(e.Server, settings);
                            await _client.Reply(e, $"Stream sticky for {channel.Name} set to {value}.");
                        });
                });
            });

            _client.Connected += (s, e) =>
            {
                if (!_isRunning)
                {
                    Task.Run(Run);
                    _isRunning = true;
                }
            };
        }
Example #56
0
 public Task <ParticipantApplicationSharing> GetParticipantApplicationSharing()
 {
     return(GetParticipantApplicationSharing(HttpService.GetNewCancellationToken()));
 }
Example #57
0
        public void of_http_requests_routing()
        {
            const int iterations = 100000;

            IPublisher inputBus = new NoopPublisher();
            var bus = InMemoryBus.CreateTest();
            var queue = new QueuedHandlerThreadPool(bus, "Test", true, TimeSpan.FromMilliseconds(50));
            var multiQueuedHandler = new MultiQueuedHandler(new IQueuedHandler[]{queue}, null);
            var providers = new AuthenticationProvider[] {new AnonymousAuthenticationProvider()};
            var httpService = new HttpService(ServiceAccessibility.Public, inputBus, 
                                              new TrieUriRouter(), multiQueuedHandler, "http://localhost:12345/");
            HttpService.CreateAndSubscribePipeline(bus, providers);

            var fakeController = new FakeController(iterations, null);
            httpService.SetupController(fakeController);

            httpService.Handle(new SystemMessage.SystemInit());

            var rnd = new Random();
            var sw = Stopwatch.StartNew();

            var httpClient = new HttpAsyncClient();
            for (int i = 0; i < iterations; ++i)
            {
                var route = fakeController.BoundRoutes[rnd.Next(0, fakeController.BoundRoutes.Count)];

                switch (route.Item2)
                {
                    case HttpMethod.Get:
                        httpClient.Get(route.Item1,TimeSpan.FromMilliseconds(10000),  x => { }, x => { throw new Exception();});
                        break;
                    case HttpMethod.Post:
                        httpClient.Post(route.Item1, "abracadabra", ContentType.Json, TimeSpan.FromMilliseconds(10000), x => { }, x => { throw new Exception(); });
                        break;
                    case HttpMethod.Delete:
                        httpClient.Delete(route.Item1, TimeSpan.FromMilliseconds(10000), x => { }, x => { throw new Exception(); });
                        break;
                    case HttpMethod.Put:
                        httpClient.Put(route.Item1, "abracadabra", ContentType.Json, TimeSpan.FromMilliseconds(10000), x => { }, x => { throw new Exception(); });
                        break;
                    default:
                        throw new Exception();
                }
            }

            fakeController.CountdownEvent.Wait();
            sw.Stop();

            Console.WriteLine("{0} request done in {1} ({2:0.00} per sec)", iterations, sw.Elapsed, 1000.0 * iterations / sw.ElapsedMilliseconds);

            httpService.Shutdown();
            multiQueuedHandler.Stop();
        }
Example #58
0
 public async Task <ParticipantApplicationSharing> GetParticipantApplicationSharing(CancellationToken cancellationToken)
 {
     return(await HttpService.Get <ParticipantApplicationSharing>(Links.participantApplicationSharing, cancellationToken));
 }
Example #59
0
 public Task Eject()
 {
     return(Eject(HttpService.GetNewCancellationToken()));
 }
Example #60
0
 public async Task ChangeNumber(string number)
 {
     await ChangeNumber(number, HttpService.GetNewCancellationToken());
 }