コード例 #1
0
 /// <summary>
 ///     Executes a packet based on its handler
 /// </summary>
 public void HandlePacket()
 {
     try
     {
         //If no auth client is present we don't need to proceed.
         if (AuthClient == null)
         {
             return;
         }
         //Create an instance of our handler
         dynamic handler = Activator.CreateInstance(_packetHandler);
         //Authentication is needed to run most packets, however some work without being logged in.
         if (AuthClient.Authenticated || !NeedsAuth(EndPoint))
         {
             Task.Run(() => { handler.HandlePacket(this); });
         }
         else
         {
             EndPointName = "noauth";
             EndPoint     = EndPoints.NoAuth;
             handler      = Activator.CreateInstance(typeof(ErrorPacketHandler));
             handler.HandlePacket(this);
         }
     }
     catch (Exception)
     {
         EndPointName = "invalidpacket";
         EndPoint     = EndPoints.InvalidOrEmptyPacket;
         dynamic handler = Activator.CreateInstance(typeof(ErrorPacketHandler));
         handler.HandlePacket(this);
     }
 }
コード例 #2
0
        public void UnSubscribeNode(ApUnSubscribeNodeRequest request)
        {
            Log.Debug(typeof(ApNodeControllerService), "UnSubscribeNode()");

            try
            {
                Node node = Database.GetInstance().Nodes.Find(x => x.IpAddress.Equals(request.IpAddress));
                if (node != null)
                {
                    Database.GetInstance().Nodes.Remove(node);

                    // Update routing mesh in the load balancer
                    LbRemoveApplicationInstanceRequest request_ = new LbRemoveApplicationInstanceRequest(Credentials);
                    request_.NodeId        = node.Id;
                    request_.ApplicationId = -1;
                    request_.InstanceId    = -1;
                    EndPoints.GetLbApplicationGridService().RemoveApplicationInstances(request_);
                }
                Log.Debug(typeof(ApNodeControllerService), "Node " + node.IpAddress + " removed successfully");
            }
            catch (Exception e)
            {
                Log.Error(this, e);
                throw e;
            }
        }
コード例 #3
0
ファイル: RoomFileQuery.cs プロジェクト: Egliss/SharpChatwork
        public async ValueTask <ElementId> UploadAsync(long roomId, Stream stream, string filePath, string message)
        {
            var uri = $"{EndPoints.RoomFiles(roomId)}";

            MultipartFormDataContent multipart = new MultipartFormDataContent();
            var fileContent = new StreamContent(stream);

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name     = "\"file\"",
                FileName = $"\"{Path.GetFileName(filePath)}\"",
            };
            var mimeName = MimeMapping.MimeUtility.GetMimeMapping(filePath);

            fileContent.Headers.ContentType = new MediaTypeHeaderValue(mimeName);
            var messageContent = new StringContent(message);

            messageContent.Headers.ContentDisposition      = new ContentDispositionHeaderValue("form-data");
            messageContent.Headers.ContentDisposition.Name = "\"message\"";
            messageContent.Headers.ContentType             = null;
            multipart.Add(fileContent);
            multipart.Add(messageContent);

            return(await this.chatworkClient.QueryContentAsync <ElementId>(new Uri(uri), HttpMethod.Post, multipart));
        }
コード例 #4
0
    internal void UpdateSentinelAddressList(string serviceName)
    {
        var firstCompleteRequest = GetServerSnapshot()
                                   .ToArray()
                                   .Where(s => s.ServerType == ServerType.Sentinel)
                                   .AsParallel()
                                   .Select(s =>
        {
            try { return(GetServer(s.EndPoint).SentinelGetSentinelAddresses(serviceName)); }
            catch { return(null); }
        })
                                   .FirstOrDefault(r => r != null);

        // Ignore errors, as having an updated sentinel list is not essential
        if (firstCompleteRequest == null)
        {
            return;
        }

        bool hasNew = false;

        foreach (EndPoint newSentinel in firstCompleteRequest.Where(x => !EndPoints.Contains(x)))
        {
            hasNew = true;
            EndPoints.TryAdd(newSentinel);
        }

        if (hasNew)
        {
            // Reconfigure the sentinel multiplexer if we added new endpoints
            ReconfigureAsync(first: false, reconfigureAll: true, null, EndPoints[0], "Updating Sentinel List", false).Wait();
        }
    }
コード例 #5
0
ファイル: TrackingHelper.cs プロジェクト: fwanjohi/Transit
        public async Task <List <GoogleAddress> > GetAddressPosition(string address)
        {
            var url    = EndPoints.GoogleAddressUrl(address);
            var client = new HttpClient();
            var json   = client.GetStringAsync(url).Result;
            var adds   = new List <GoogleAddress>();

            GooglePlaceSearchResponse resp = JsonConvert.DeserializeObject <GooglePlaceSearchResponse>(json);

            try
            {
                foreach (var add in resp.Results)
                {
                    var pos = new GoogleAddress
                    {
                        RequestedAddress = address,
                        FormattedAddress = add.Vicinity,
                        Lat      = add.Geometry.Location.Lat,
                        Lon      = add.Geometry.Location.Lng,
                        Name     = add.Name,
                        Distance = TrackingHelper.Instance.CalculateDistance(add.Geometry.Location.Lat, add.Geometry.Location.Lng),
                    };
                    adds.Add(pos);
                }
            }
            catch (Exception e)
            {
            }
            return(adds.OrderBy(x => x.Distance).ToList());;
        }
コード例 #6
0
 private void UpdateApplications(List <Node> nodes)
 {
     foreach (Node node in nodes)
     {
         try
         {
             NcDescribeApplicationsRequest request = new NcDescribeApplicationsRequest(Settings.Credentials);
             var channel = EndPoints.GetNcApplicationGridService(node);
             NcDescribeApplicationsResponse response = channel.DescribeApplications(request);
             node.Applications = response.Applications;
             foreach (Application application in node.Applications)
             {
                 LbGetApplicationInstancesRequest request1 = new LbGetApplicationInstancesRequest(Settings.Credentials);
                 request1.NodeId        = node.Id;
                 request1.ApplicationId = application.Id;
                 LbGetApplicationInstancesResponse response1 = EndPoints.GetLbApplicationGridService().GetApplicationInstances(request1);
                 application.ApplicationInstances = response1.ApplicationInstances;
             }
             Log.Debug(this, "Updated applications of node " + node.ToString());
         }
         catch (Exception e)
         {
             Log.Error(this, "Could not update applications of node " + node.ToString());
             throw e;
         }
     }
 }
コード例 #7
0
        public void PostTo()
        {
            CoapClient c = new CoapClient(Program.Host)
            {
                UriPath  = "/.well-known/core",
                UriQuery = "ep=node1",
                Timeout  = 5000,
                EndPoint = EndPoints.First()
            };

            Response r = c.Post(new byte[] { }, MediaType.ApplicationLinkFormat);

            if (r == null)
            {
                Console.WriteLine("No response received");
            }
            else
            {
                if (r.StatusCode != StatusCode.Changed)
                {
                    Console.WriteLine("Incorrect response");
                }

                Console.WriteLine(Utils.ToString(r));
            }
        }
コード例 #8
0
        public async Task Services_are_resolved_on_service_manifest()
        {
            // PaymentsService calls AccountsService internally.
            // In this test we mock AccountService so we know it is resolved and accessible from within PaymentsService.

            IEndPointConfiguration ep = EndPoints.First(x => x.ProviderName == CurrentDatabaseProviderName && x.API_Name == API_Name.BackOffice);

            await DropAndRecreate(ep);

            Mock <IAccountsService> fakeMSSQLAccountsService = new Mock <IAccountsService>();

            fakeMSSQLAccountsService.Setup(x => x.GetAccountByID(It.IsAny <int>())).ReturnsAsync(new Account {
                Name = "TEST"
            });

            using (var scope = Container.BeginLifetimeScope(builder =>
            {
                builder.RegisterInstance(fakeMSSQLAccountsService.Object).Keyed <IAccountsService>(EndPointType.DBMS + CurrentDatabaseProviderName);
            }))
            {
                IAdaptiveClient <IBOServiceManifest> client = scope.Resolve <IAdaptiveClient <IBOServiceManifest> >();
                Account account = await client.CallAsync(x => x.PaymentsService.GetAccountForPaymentID(1), ep.Name);

                Assert.AreEqual("TEST", account.Name);
            }
        }
コード例 #9
0
        public void Resolve_DbContext_for_API()
        {
            IEndPointConfiguration storeFrontep     = EndPoints.First(x => x.ProviderName == CurrentDatabaseProviderName && x.API_Name == API_Name.StoreFront);
            IEndPointConfiguration backOfficeep     = EndPoints.First(x => x.ProviderName == CurrentDatabaseProviderName && x.API_Name == API_Name.BackOffice);
            ResolutionHelper       resolutionHelper = Container.Resolve <ResolutionHelper>();
            DbContext storeFrontContext             = resolutionHelper.ResolveDbContext(storeFrontep);
            DbContext backOfficeContext             = resolutionHelper.ResolveDbContext(backOfficeep);

            Assert.IsNotNull(storeFrontContext);
            Assert.IsNotNull(backOfficeContext);
            Assert.IsTrue(storeFrontContext is Artifacts.StoreFront.Db);
            Assert.IsTrue(backOfficeContext is Artifacts.BackOffice.Db);

            if (CurrentDatabaseProviderName == DataBaseProviderName.MSSQL)
            {
                Assert.IsTrue(storeFrontContext.Database.GetDbConnection().ConnectionString == storeFrontep.ConnectionString);
                Assert.IsTrue(backOfficeContext.Database.GetDbConnection().ConnectionString == backOfficeep.ConnectionString);
            }
            else if (CurrentDatabaseProviderName == DataBaseProviderName.MySQL)
            {
                // MySql database connector changes the connection string.
                Assert.IsTrue(storeFrontContext.Database.GetDbConnection().ConnectionString.ToLower().Contains("database=adaptiveclientef_storefront"));
                Assert.IsTrue(backOfficeContext.Database.GetDbConnection().ConnectionString.ToLower().Contains("database=adaptiveclientef_backoffice"));
            }
        }
コード例 #10
0
        private int monitoringInterval = 5000; // Monitoring interval 5 sec

        public void MonitorRequestQueue()
        {
            Log.Info(this, "Scaling Manager started");
            while (Thread.CurrentThread.IsAlive)
            {
                LbGetRequestQueueResponse response = null;
                try
                {
                    Log.Info(this, "Checking request queue status...");
                    LbGetRequestQueueRequest request = new LbGetRequestQueueRequest(Settings.Credentials);
                    response = EndPoints.GetLbApplicationGridService().GetRequestQueue(request);
                }
                catch (Exception e)
                {
                    Log.Error(this, e);
                }

                try
                {
                    if (response != null)
                    {
                        ScaleApplications(response.RequestQueue);
                    }
                    Thread.Sleep(monitoringInterval);
                }
                catch (Exception e)
                {
                    Log.Error(this, e);
                }
            }
            Log.Info(this, "Scaling Manager stopped");
        }
コード例 #11
0
        private ConfigurationOptions BuildConfigurationOptions()
        {
            var result = new ConfigurationOptions();

            if (EndPoints != null)
            {
                foreach (var ep in EndPoints.DefaultIfEmpty())
                {
                    result.EndPoints.Add(ep);
                }
            }

            if (AllowAdmin.HasValue)
            {
                result.AllowAdmin = AllowAdmin.Value;
            }

            if (ConnectRetry.HasValue)
            {
                result.ConnectRetry = ConnectRetry.Value;
            }

            if (ConnectTimeout.HasValue)
            {
                result.ConnectTimeout = ConnectTimeout.Value;
            }

            if (DefaultDatabase.HasValue)
            {
                result.DefaultDatabase = DefaultDatabase.Value;
            }

            return(result);
        }
コード例 #12
0
 public virtual void ClearGraph()
 {
     Graph.Refresh();
     PathFindingStatistics = string.Empty;
     GraphParametres       = Graph.ToString();
     EndPoints.Reset();
 }
コード例 #13
0
        private bool ScaleDown(int applicationId, string tenantName, int scale)
        {
            Log.Info(this, "Scaling down application: " + applicationId);
            LbGetApplicationInstancesRequest request_ = new LbGetApplicationInstancesRequest(Settings.Credentials);

            request_.NodeId        = -1;
            request_.ApplicationId = applicationId;
            LbGetApplicationInstancesResponse response_ = EndPoints.GetLbApplicationGridService().GetApplicationInstances(request_);
            List <ApplicationInstance>        list      = response_.ApplicationInstances.OrderBy(x => x.Id).ToList();

            if ((list != null) && (list.Count >= scale))
            {
                // Stop idling application instances
                List <ApplicationInstance> idlingInstances = list.FindAll(x => x.RequestCount == 0);
                // Keep one instance alive
                if (idlingInstances.Count == list.Count)
                {
                    idlingInstances.Remove(idlingInstances.Last());
                }

                if (idlingInstances.Count > 0)
                {
                    foreach (ApplicationInstance instance in idlingInstances)
                    {
                        ApStopApplicationInstanceRequest request = new ApStopApplicationInstanceRequest(Settings.Credentials);
                        request.NodeId        = instance.NodeId;
                        request.ApplicationId = instance.ApplicationId;
                        request.InstanceId    = instance.Id;
                        GetApDashboardService().StopApplicationInstance(request);
                    }
                    return(true);
                }
            }
            return(false);
        }
コード例 #14
0
ファイル: Services.cs プロジェクト: nagyistge/code-camp-app
        internal static string BuildUrl(EndPoints endPoint)
        {
            string servicePath = "";

            switch (endPoint)
            {
            case EndPoints.ActiveMasterConferences:
                servicePath = "/MasterConference.svc/GetActiveMasterConferences";
                break;

            case EndPoints.SessionsForConferenceId:
                servicePath = "/Session.svc/GetSessionsByConferenceId?conferenceId={0}";
                break;

            case EndPoints.TracksForConferenceId:
                servicePath = "/Track.svc/GetTracksByConferenceId?conferenceId={0}";
                break;

            case EndPoints.SessionForSessionId:
                servicePath = "/Session.svc/GetSession?sessionId={0}";
                break;
            }

            return(RootUrl + servicePath);
        }
コード例 #15
0
ファイル: Requester.cs プロジェクト: xxblancxx/ForecastIt
        /// <summary>
        /// Get request Asynchronously
        /// </summary>
        /// <typeparam name="T"> The class that the Method Should return and Get</typeparam>
        /// <param name="theUri">the specific api Call</param>
        /// <param name="id1">this is the first Id, it can be left as a zero but for some Calls cant be left </param>
        /// <param name="id2">this is the second Id, for specific subjects</param>
        /// <returns>A List of T</returns>
        public T GetRequestByIdAsync <T>(EndPoints theUri, int id1 = 0, int id2 = 0) where T : new()
        {
            using (var handler = new HttpClientHandler())
            {
                handler.Credentials = new NetworkCredential(_username, _password);
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri(_baseAddress);
                    client.DefaultRequestHeaders.Clear();//making sure that there is no old data within headers
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonData = string.Empty;
                    // attempt to download JSON data as a string
                    try
                    {
                        var ext = UriCorrector(theUri, id1, id2);

                        var response = client.GetAsync(ext).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            jsonData = response.Content.ReadAsStringAsync().Result;
                        }
                    }
                    catch (HttpRequestException exception)
                    {
                        //await new MessageDialog(exception.Message).ShowAsync();
                    }
                    // if string with JSON data is not empty, deserialize it to class and return its instance
                    return(!string.IsNullOrEmpty(jsonData) ? JsonConvert.DeserializeObject <T>(jsonData) : new T());
                }
            }
        }
コード例 #16
0
        private void UploadApplicationToNode(int applicationId, Node node)
        {
            Log.Debug(this, "Uploading application " + applicationId + " to node " + node.ToString());

            Application app = FindApplication(applicationId);

            if (app != null)
            {
                string filePath = Path.Combine(Settings.ApplicationStorePath, app.FileName);
                if (File.Exists(filePath))
                {
                    Log.Debug(this, "Transferring application package...");
                    NcFileTransferSocket socket = new NcFileTransferSocket(node.IpAddress_, Settings.NcFileTransferSocketPort);
                    socket.SendFile(filePath);

                    Log.Debug(this, "Transferring application data...");
                    NcAddApplicationRequest request = new NcAddApplicationRequest(Credentials);
                    request.Application = app;
                    EndPoints.GetNcApplicationGridService(node).AddApplication(request);
                }
                else
                {
                    throw new MonoscapeException("File not found: " + app.FileName);
                }
            }
            else
            {
                throw new MonoscapeException("Application not found: " + app.Name);
            }
        }
コード例 #17
0
ファイル: Requester.cs プロジェクト: xxblancxx/ForecastIt
        /// <summary>
        /// Delete Request Asynchronously
        /// </summary>
        /// <param name="theUri">the specific api Call</param>
        /// <param name="id1">this is the first Id, it can be left as a zero but for some Calls it is needed</param>
        /// <param name="id2">this is the second Id, for specific subjects</param>
        public async void DelRequest(EndPoints theUri, int id1 = 0, int id2 = 0)
        {
            using (var handler = new HttpClientHandler())
            {
                handler.Credentials = new NetworkCredential(_username, _password);
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri(_baseAddress);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    try
                    {
                        var ext = UriCorrector(theUri, id1, id2);

                        var response = await client.DeleteAsync(ext);

                        if (response.IsSuccessStatusCode)
                        {
                            //await new MessageDialog("Succesfully Deleted:\n\t").ShowAsync();
                        }
                    }
                    catch (HttpRequestException exception)
                    {
                        //await new MessageDialog(exception.Message).ShowAsync();
                    }
                }
            }
        }
コード例 #18
0
ファイル: Requester.cs プロジェクト: xxblancxx/ForecastIt
        /// <summary>
        /// Change/edit request Asynchronously
        /// </summary>
        /// <typeparam name="T"> The class that the Method Should return and Get</typeparam>
        /// <param name="classToPut"> class wished to retrieve</param>
        /// <param name="theUri">the specific api Call</param>
        /// <param name="id1">this is the first Id, it can be left as a zero but for some Calls cant be left </param>
        /// <param name="id2">this is the second Id, for specific subjects</param>
        /// <returns>returns T that is sent to the API for debugging reasons</returns>
        public async Task <T> PutRequest <T>(T classToPut, EndPoints theUri, int id1 = 0, int id2 = 0)
        {
            using (var handler = new HttpClientHandler())
            {
                handler.Credentials = new NetworkCredential(_username, _password);
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri(_baseAddress);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    try
                    {
                        string serializeObjectToJson = await System.Threading.Tasks.Task.Run(() => JsonConvert.SerializeObject(classToPut));

                        var ext = UriCorrector(theUri, id1, id2);

                        var response = await client.PutAsync(ext, new StringContent(serializeObjectToJson, Encoding.UTF8, "application/json"));

                        if (response.IsSuccessStatusCode)
                        {
                            //await new MessageDialog("Succesfully Changed:\n\t" + classToPut).ShowAsync();
                        }
                    }
                    catch (HttpRequestException exception)
                    {
                        //await new MessageDialog(exception.Message).ShowAsync();
                    }

                    return(classToPut);
                }
            }
        }
コード例 #19
0
 /// <summary>
 ///     Create and return a new packet
 /// </summary>
 /// <returns>Packet</returns>
 public Packet GetPacket()
 {
     if (string.IsNullOrEmpty(_plainText))
     {
         return(null);
     }
     try
     {
         var deserializedPacket = JObject.Parse(_plainText);
         if (deserializedPacket != null)
         {
             _endPointName = deserializedPacket["endpoint"]?.ToString().Trim().ToLower();
             _syncKey      = deserializedPacket["synckey"]?.ToString().Trim();
             if (deserializedPacket["args"] != null)
             {
                 _args.AddRange(JArray.Parse(deserializedPacket["args"]?.ToString()));
             }
             var packetInfo = GetPacketInfo(_endPointName);
             _packetHandler = packetInfo.Handler;
             _endPoints     = packetInfo.EndPoint;
             return(new Packet(_authClient, _client, _endPointName, _syncKey, _args, _endPoints, _packetHandler));
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"Packet failed to deserialize: {e.StackTrace}{e.Message}");
         _endPoints = EndPoints.InvalidOrEmptyPacket;
     }
     return(null);
 }
コード例 #20
0
        public void Sweep()
        {
            EndPoints.Sort(EndPoint.Compare);
            float beginAngle = 0;

            for (int pass = 0; pass < 2; pass++)
            {
                Segment previous = null;
                foreach (EndPoint p in EndPoints)
                {
                    Segment currentOld = Open.FirstOrDefault();
                    InsertPoint(p);
                    Segment currentNew = Open.FirstOrDefault();
                    if (currentOld != currentNew)
                    {
                        if (pass == 1)
                        {
                            AddTriangle(beginAngle, p.Angle, currentOld, previous);
                            previous = currentOld;
                        }
                        beginAngle = p.Angle;
                    }
                }
            }
        }
コード例 #21
0
        private void FormSettings_Load(object sender, EventArgs e)
        {
            var devices = EndPoints.GetAllDeviceList();
            var cnt     = 0;

            foreach (var dev in devices)
            {
                var devID  = dev.Key.ID;
                var lvitem = new ListViewItem {
                    Text = dev.Key.FriendlyName, ImageIndex = cnt, Tag = devID
                };

                var devSettings = Program.settings.Device.Find(x => x.DeviceID == devID);
                if (devSettings != null)
                {
                    lvitem.Font = new Font(lvitem.Font, FontStyle.Bold);

                    if (devSettings.HideFromList)
                    {
                        lvitem.Font = new Font(lvitem.Font, FontStyle.Italic);
                    }
                }

                listDevices.LargeImageList.Images.Add(dev.Value);
                listDevices.Items.Add(lvitem);
                cnt++;
            }
            pictureModded.Image = new Bitmap(Properties.Resources._66_100_highDPI);

            var OSDskins = Directory.GetDirectories(Program.Root + "Skins");

            foreach (var skinDir in OSDskins)
            {
                comboOSDSkin.Items.Add(skinDir.Substring(skinDir.LastIndexOf('\\') + 1));
            }
            comboOSDSkin.Text       = Program.settings.OSD.Skin;
            trackTransparency.Value = Program.settings.OSD.Transparency;

            comboDefMode.Items.Add("Playback");
            comboDefMode.Items.Add("Recording");
            comboDefMode.Text = Program.settings.DefaultDataFlow == EDataFlow.eCapture ? "Recording" : "Playback";
            checkDefaultMultiAndComm.Checked = Program.settings.DefaultMultimediaAndComm;
            checkColorVU.Checked             = Program.settings.ColorVU;
            checkVolScroll.Checked           = Program.settings.VolumeScroll.Enabled;
            comboScrollKey.Text     = Program.settings.VolumeScroll.Key.ToString();
            checkScrShowOSD.Checked = Program.settings.VolumeScroll.ShowOSD;
            checkCustomOSD.Checked  = Program.settings.UseCustomOSD;
            checkShowHWName.Checked = Program.settings.ShowHardwareName;

            radioQuickSwitch.Checked = Program.settings.QuickSwitchEnabled;
            radioAlwaysMenu.Checked  = !radioQuickSwitch.Checked;
            checkQSShowOSD.Enabled   = radioQuickSwitch.Checked;

            checkQSShowOSD.Checked = Program.settings.QuickSwitchShowOSD;

            gridHotkeys.CellEndEdit += gridHotkeys_CellEndEdit;
            gridHotkeys.RowsAdded   += gridHotkeys_RowsAdded;
            gridHotkeys.RowsRemoved += gridHotkeys_RowsRemoved;
        }
コード例 #22
0
 public NetworkHeartbeat(IEnumerable <IPAddress> hosts, int pingTimeout, int heartbeatDelay)
 {
     PingTimeout    = pingTimeout;
     HeartbeatDelay = heartbeatDelay;
     EndPoints      = hosts.ToArray();
     PingResults    = new PingReply[EndPoints.Length];
     Pings          = EndPoints.Select(h => new Ping()).ToArray();
 }
コード例 #23
0
 public Configuration()
 {
     if (!File.Exists(FileName))
     {
         // Discord
         EndPoints.Add(new Endpoint());
     }
 }
コード例 #24
0
        public async ValueTask <IEnumerable <UserMessage> > GetAllAsync(long roomId, bool isForceMode = false)
        {
            // TODO QueryAsync + data is error
            // single arg is invalid ?
            var uri = $"{EndPoints.RoomMessages(roomId)}?force={URLArgEncoder.BoolToInt(isForceMode).ToString()}";

            return(await this.chatworkClient.QueryAsync <List <UserMessage> >(new Uri(uri), HttpMethod.Get, new Dictionary <string, string>()));
        }
コード例 #25
0
        //https://api.happynodes.f27.ventures/redis/endpoints
        public async Task <EndPoints> GetEndPoints()
        {
            var result = await _restClient.GetAsync(Endpoints).ConfigureAwait(false);

            var data = await result.Content.ReadAsStringAsync();

            return(EndPoints.FromJson(data));
        }
コード例 #26
0
        // Add back in when https://github.com/aspnet/Caching updates to new StackExchange
        //public bool HighPrioritySocketThreads { get; set; }
        //public int ResponseTimeout { get; set; }
        //public int? DefaultDatabase { get; set; }

        public override string ToString()
        {
            if (!string.IsNullOrEmpty(ConnectionString))
            {
                return(ConnectionString);
            }

            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrEmpty(this.EndPoints))
            {
                string endpoints = EndPoints.Trim();
                sb.Append(endpoints);
                sb.Append(',');
            }
            else
            {
                sb.Append(this.Host + ":" + this.Port);
                sb.Append(',');
            }

            AddKeyValue(sb, "password", this.Password);
            AddKeyValue(sb, "allowAdmin", this.AllowAdmin);
            AddKeyValue(sb, "name", this.ClientName);

            if (this.ConnectRetry > 0)
            {
                AddKeyValue(sb, "connectRetry", this.ConnectRetry);
            }

            if (this.ConnectTimeout > 0)
            {
                AddKeyValue(sb, "connectTimeout", this.ConnectTimeout);
            }

            AddKeyValue(sb, "abortConnect", this.AbortOnConnectFail);

            if (this.KeepAlive > 0)
            {
                AddKeyValue(sb, "keepAlive", this.KeepAlive);
            }

            AddKeyValue(sb, "resolveDns", this.ResolveDns);
            AddKeyValue(sb, "serviceName", this.ServiceName);
            AddKeyValue(sb, "ssl", this.Ssl);
            AddKeyValue(sb, "sslHost", this.SslHost);
            AddKeyValue(sb, "tiebreaker", this.TieBreaker);

            if (this.WriteBuffer > 0)
            {
                AddKeyValue(sb, "writeBuffer", this.WriteBuffer);
            }


            // Trim ending ','
            sb.Remove(sb.Length - 1, 1);
            return(sb.ToString());
        }
コード例 #27
0
        /// <summary>
        /// Loads the specified settings, overwriting existing settings.
        /// </summary>
        /// <param name="updatedEndPointsResult"></param>
        /// this <see cref="RemoteHostPool"/>.
        /// <exception cref="ArgumentNullException">Thrown when </exception>
        /// <exception cref="EnvironmentException"></exception>
        private void ReloadEndpoints(EndPointsResult updatedEndPointsResult)
        {
            lock (_lock)
            {
                try
                {
                    var updatedEndPoints = updatedEndPointsResult.EndPoints;
                    if (updatedEndPoints.Any() == false)
                    {
                        Health.SetHealthFunction(() =>
                        {
                            var config = GetConfig();
                            if (IsHealthCheckSuppressed(config))
                            {
                                return(HealthCheckResult.Healthy($"No endpoints were discovered from source '{config.Source}' but the remote service was not in use for more than {config.SuppressHealthCheckAfterServiceUnused?.TotalSeconds} seconds."));
                            }
                            else
                            {
                                return(HealthCheckResult.Unhealthy($"No endpoints were discovered from source '{config.Source}'."));
                            }
                        });

                        EndPointsResult = updatedEndPointsResult;

                        ReachableHosts   = new List <RemoteHost>();
                        UnreachableHosts = new List <RemoteHost>();
                    }
                    else
                    {
                        if (EndPoints != null)
                        {
                            foreach (var removedEndPoint in EndPoints.Except(updatedEndPoints))
                            {
                                ReachableHosts.SingleOrDefault(h => h.Equals(removedEndPoint))?.StopMonitoring();
                                ReachableHosts.RemoveAll(h => h.Equals(removedEndPoint));
                                UnreachableHosts.RemoveAll(h => h.Equals(removedEndPoint));
                            }
                        }

                        var newHosts = updatedEndPoints
                                       .Except(EndPoints ?? Enumerable.Empty <EndPoint>())
                                       .Select(ep => new RemoteHost(ep.HostName, this, _lock, ep.Port));

                        ReachableHosts.AddRange(newHosts);

                        EndPointsResult = updatedEndPointsResult;
                        Counter         = (ulong)_random.Next(0, ReachableHosts.Count);

                        Health.SetHealthFunction(CheckHealth);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn("Failed to process newly discovered endpoints", exception: ex);
                    Health.SetHealthFunction(() => HealthCheckResult.Unhealthy("Failed to process newly discovered endpoints: " + HealthMonitor.GetMessages(ex)));
                }
            }
        }
コード例 #28
0
        private void QuickSwitchDevice(bool previous, EDataFlow rType, bool showOSD)
        {
            var devName = previous ? EndPoints.SetPrevDefault(rType) : EndPoints.SetNextDefault(rType);

            if (showOSD)
            {
                Program.frmOSD.ChangeDevice(devName);
            }
        }
コード例 #29
0
 public LightsService(
     IOptions <EndPoints> options,
     INetworkDiscoveryService networkDiscoveryService,
     Helpers.Elgato.IElgatoService elgatoService)
 {
     _endPoints = options.Value;
     _networkDiscoveryService = networkDiscoveryService;
     _elgatoService           = elgatoService;
 }
コード例 #30
0
 public IEnumerator Movement()
 {
     foreach (var obj in endPoints)
     {
         tempEndpoint = obj;
         transform.DOLocalMove(obj.EndPoint, obj.endTime, false).SetEase(Ease.Linear);
         yield return(new WaitForSeconds(obj.endTime));
     }
 }
コード例 #31
0
        public static string Converter(EndPoints endpoint)
        {
            var Url = "";

            switch (endpoint)
            {
                case EndPoints.Users:
                    Url = "users/";
                    break;
                case EndPoints.Roles:
                    Url = "roles/";
                    break;
                case EndPoints.Teams:
                    Url = "teams/";
                    break;
                case EndPoints.Customers:
                    Url = "customers/";
                    break;
                case EndPoints.BusinessUnits:
                    Url = "businessunits/";
                    break;
                case EndPoints.Projects:
                    Url = "projects/";
                    break;
                case EndPoints.ProjectPhase:
                    Url = "projects/{0}/projectPhase/";
                    break;
                case EndPoints.ProjectTypes:
                    Url = "projectTypes/";
                    break;
                case EndPoints.ProjectPeopleResources:
                    Url = "projects/{0}/projectResources/";
                    break;
                case EndPoints.CostTypes:
                    Url = "projects/{0}/costTypes/";
                    break;
                case EndPoints.UserStories:
                    Url = "projects/{0}/userStories/";
                    break;
                case EndPoints.UserStoryTypes:
                    Url = "userStoryTypes/";
                    break;
                case EndPoints.Sprints:
                    Url = "projects/{0}/sprints/";
                    break;
                case EndPoints.Tasks:
                    Url = "projects/{0}/tasks/";
                    break;
                case EndPoints.TimeTrackingRegistration:
                    Url = "projects/{0}/time/";
                    break;
                case EndPoints.ScrumStages:
                    Url = "projects/{0}/scrumStages/";
                    break;
                case EndPoints.Tags:
                    Url = "tags/";
                    break;
                case EndPoints.FileAttachments:
                    throw new NotImplementedException("FileAttachments at this moment isn't implemented for API Calls yet");
                case EndPoints.Milestones:
                    throw new NotImplementedException("Milestones at this moment isn't implemented for API Calls yet");
                case EndPoints.Versions:
                    throw new NotImplementedException("Milestones at this moment isn't implemented for API Calls yet");

                default:
                    throw new ArgumentException("Apicall hasn't been set to anything, this is your Fault");
            }
            return Url;
        }