Ejemplo n.º 1
0
        public void Send(IRemote destination)
        {
            List <byte> rawData = new List <byte>(Size);

            rawData.AddRange(BitConverter.GetBytes((UInt16)Type));
            rawData.Add(MessageIndex);
            rawData.AddRange(BitConverter.GetBytes(GameTime));
            rawData.Add((byte)UserAction);

            if (Parameters != null && Parameters.Length > 0)
            {
                if (Parameters.Length > 255)
                {
                    throw new ArgumentOutOfRangeException("More than 255 parameter bytes are not allowed.");
                }

                rawData.Add((byte)Parameters.Length);
                rawData.AddRange(Parameters);
            }
            else
            {
                rawData.Add(0);
            }

            destination.Send(rawData.ToArray());
        }
        /// <summary>
        /// Deletes a channel by name
        /// </summary>
        /// <returns></returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                // Get the ID of the channel with the specified name.
                Channel existingChannel = (await remote.GetChannelsAsync()).Where(channel => channel.Name.Equals(_options.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                if (existingChannel == null)
                {
                    Logger.LogError($"Could not find channel with name '{_options.Name}'");
                    return(Constants.ErrorCode);
                }

                await remote.DeleteChannelAsync(existingChannel.Id);

                Console.WriteLine($"Successfully deleted channel '{existingChannel.Name}'.");

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to delete channel.");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 3
0
        public async Task <MergePolicyEvaluationResult> EvaluateAsync(
            string prUrl,
            IRemote darc,
            IReadOnlyList <MergePolicyDefinition> policyDefinitions)
        {
            var context = new MergePolicyEvaluationContext(prUrl, darc);

            foreach (MergePolicyDefinition definition in policyDefinitions)
            {
                if (MergePolicies.TryGetValue(definition.Name, out MergePolicy policy))
                {
                    using (Logger.BeginScope("Evaluating Merge Policy {policyName}", policy.Name))
                    {
                        context.CurrentPolicy = policy;
                        await policy.EvaluateAsync(context, new MergePolicyProperties(definition.Properties));
                    }
                }
                else
                {
                    context.CurrentPolicy = null;
                    context.Fail($"Unknown Merge Policy: '{definition.Name}'");
                }
            }

            return(context.Result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Retrieve Goal in minutes for Definition in a Channel.
        /// </summary>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote   = RemoteFactory.GetBarOnlyRemote(_options, Logger);
                Goal    goalInfo = await remote.GetGoalAsync(_options.Channel, _options.DefinitionId);

                Console.Write(goalInfo.Minutes);
                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (RestApiException e) when(e.Response.Status == (int)HttpStatusCode.NotFound)
            {
                Logger.LogError(e, $"Cannot find Channel '{_options.Channel}'.");
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Unable to create goal for Channel : '{_options.Channel}' and DefinitionId : '{_options.DefinitionId}'.");
                return(Constants.ErrorCode);
            }
        }
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                DefaultChannel resolvedChannel = await ResolveSingleChannel();

                if (resolvedChannel == null)
                {
                    return(Constants.ErrorCode);
                }

                await remote.DeleteDefaultChannelAsync(resolvedChannel.Id);

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed remove the default channel association.");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 6
0
 //Dictionary<int,Action<byte[],int, EndPoint>>
 public ServerRoute(IRemote serverPoint, int port)
 {
     this.serverPoint = serverPoint;
     this.port        = port;
     init();
     isRun = true;
 }
Ejemplo n.º 7
0
        public IRemote Connect(ServerDetails sd, RemoteType rt)
        {
            if (sd == null)
            {
                return(null);
            }
            IRemote rem = null;

            switch (rt)
            {
            case RemoteType.SSH:
                rem = new SSHRemote();
                break;

            default:
                break;
            }
            if (rem == null)
            {
                return(null);
            }
            rem.Connect(sd);
            remotes.Add(rem);
            return(rem);
        }
Ejemplo n.º 8
0
 public Television(IAdapter adapter, IRemote remote, string manufacturer, string modelNumber)
 {
     Adapter      = adapter;
     Remote       = remote;
     Manufacturer = manufacturer;
     ModelNumber  = modelNumber;
 }
Ejemplo n.º 9
0
        public async Task <MergePolicyEvaluationResults> EvaluateAsync(
            IPullRequest pr,
            IRemote darc,
            IReadOnlyList <MergePolicyDefinition> policyDefinitions)
        {
            var results = new List <MergePolicyEvaluationResult>();

            foreach (MergePolicyDefinition definition in policyDefinitions)
            {
                if (MergePolicyBuilders.TryGetValue(definition.Name, out IMergePolicyBuilder policyBuilder))
                {
                    using var oDef = _operations.BeginOperation("Evaluating Merge Definition {policyName}", definition.Name);
                    var policies = await policyBuilder.BuildMergePoliciesAsync(new MergePolicyProperties(definition.Properties), pr);

                    foreach (var policy in policies)
                    {
                        using var oPol = _operations.BeginOperation("Evaluating Merge Policy {policyName}", policy.Name);
                        results.Add(await policy.EvaluateAsync(pr, darc));
                    }
                }
                else
                {
                    var notImplemented = new NotImplementedMergePolicy(definition.Name);
                    results.Add(new MergePolicyEvaluationResult(MergePolicyEvaluationStatus.Failure, $"Unknown Merge Policy: '{definition.Name}'", notImplemented));
                }
            }

            return(new MergePolicyEvaluationResults(results));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Retrieve information about channels
        /// </summary>
        /// <param name="options">Command line options</param>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                var allChannels = await remote.GetChannelsAsync();

                switch (_options.OutputFormat)
                {
                case DarcOutputType.json:
                    WriteJsonChannelList(allChannels);
                    break;

                case DarcOutputType.text:
                    WriteYamlChannelList(allChannels);
                    break;

                default:
                    throw new NotImplementedException($"Output format {_options.OutputFormat} not supported for get-channels");
                }

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve channels");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 11
0
        private async Task CoherencyUpdatesAsync(
            IRemote barOnlyRemote,
            IRemoteFactory remoteFactory,
            List <DependencyDetail> currentDependencies,
            List <DependencyDetail> dependenciesToUpdate)
        {
            Console.WriteLine("Checking for coherency updates...");

            // Now run a coherency update based on the current set of dependencies updated
            // from the previous pass.
            List <DependencyUpdate> coherencyUpdates =
                await barOnlyRemote.GetRequiredCoherencyUpdatesAsync(currentDependencies, remoteFactory);

            foreach (DependencyUpdate dependencyUpdate in coherencyUpdates)
            {
                DependencyDetail from            = dependencyUpdate.From;
                DependencyDetail to              = dependencyUpdate.To;
                DependencyDetail coherencyParent = currentDependencies.First(d =>
                                                                             d.Name.Equals(from.CoherentParentDependencyName, StringComparison.OrdinalIgnoreCase));
                // Print out what we are going to do.
                Console.WriteLine($"Updating '{from.Name}': '{from.Version}' => '{to.Version}' " +
                                  $"to ensure coherency with {from.CoherentParentDependencyName}@{coherencyParent.Version}");

                // Final list of dependencies to update
                dependenciesToUpdate.Add(to);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Get a specific build of a repository
        /// </summary>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                Build build = await remote.GetBuildAsync(_options.Id);

                if (build != null)
                {
                    Console.Write(UxHelpers.GetBuildDescription(build));
                }
                else
                {
                    Console.WriteLine($"Could not find build with id '{_options.Id}'");
                    return(Constants.ErrorCode);
                }

                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Error: Failed to retrieve build with id '{_options.Id}'");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 13
0
        private void MakeConnectionToServer(string IP)
        {
            try
            {
                BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
                BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
                serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

                IDictionary props = new Hashtable();
                props["port"] = 0;
                string s = System.Guid.NewGuid().ToString();
                props["name"]            = s;
                props["typeFilterLevel"] = TypeFilterLevel.Full;

                HttpChannel chan = new HttpChannel(props, clientProvider, serverProvider);

                int Port = 9999;
                ChannelServices.RegisterChannel(chan);
                obj = (IRemote)Activator.GetObject(typeof(IRemote), "http://" + IP + ":" + Port + "/RemoteObject.soap", WellKnownObjectMode.SingleCall);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to connect to server");
            }
        }
Ejemplo n.º 14
0
        private async Task <ActionResult <bool?> > SynchronizePullRequestAsync(string prUrl)
        {
            ConditionalValue <InProgressPullRequest> maybePr =
                await StateManager.TryGetStateAsync <InProgressPullRequest>(PullRequest);

            if (!maybePr.HasValue || maybePr.Value.Url != prUrl)
            {
                return(ActionResult.Create(
                           (bool?)null,
                           $"Not Applicable: Pull Request '{prUrl}' is not tracked by maestro anymore."));
            }

            (string targetRepository, string targetBranch) = await GetTargetAsync();

            IRemote darc = await DarcRemoteFactory.GetRemoteAsync(targetRepository, Logger);

            InProgressPullRequest pr = maybePr.Value;
            PrStatus status          = await darc.GetPullRequestStatusAsync(prUrl);

            ActionResult <bool?> checkPolicyResult = null;

            switch (status)
            {
            case PrStatus.Open:
                checkPolicyResult = await CheckMergePolicyAsync(prUrl, darc);

                if (checkPolicyResult.Result == true)
                {
                    goto case PrStatus.Merged;
                }

                if (checkPolicyResult.Result == false)
                {
                    return(ActionResult.Create((bool?)true, checkPolicyResult.Message));
                }

                return(ActionResult.Create((bool?)false, checkPolicyResult.Message));

            case PrStatus.Merged:
                await UpdateSubscriptionsForMergedPRAsync(pr.ContainedSubscriptions);

                goto case PrStatus.Closed;

            case PrStatus.Closed:
                await StateManager.RemoveStateAsync(PullRequest);

                break;

            default:
                Logger.LogError("Unknown pr status '{status}'", status);
                break;
            }

            if (checkPolicyResult != null)
            {
                return(ActionResult.Create((bool?)null, checkPolicyResult.Message));
            }

            return(ActionResult.Create((bool?)null, $"PR Has been manually {status}"));
        }
Ejemplo n.º 15
0
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetRemote(_options, _options.Repository, Logger);

                // Users can ignore the flag and pass in -regex: but to prevent typos we'll avoid that.
                _options.Branch = _options.UseBranchAsRegex ? $"-regex:{_options.Branch}" : GitHelpers.NormalizeBranchName(_options.Branch);

                if (!(await UxHelpers.VerifyAndConfirmBranchExistsAsync(remote, _options.Repository, _options.Branch, !_options.NoConfirmation)))
                {
                    Console.WriteLine("Aborting default channel creation.");
                    return(Constants.ErrorCode);
                }

                await remote.AddDefaultChannelAsync(_options.Repository, _options.Branch, _options.Channel);

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to add a new default channel association.");
                return(Constants.ErrorCode);
            }
        }
        public static async Task <DependencyFlowGraph> BuildAsync(
            List <DefaultChannel> defaultChannels,
            List <Subscription> subscriptions,
            IRemote barOnlyRemote,
            int days)
        {
            // Dictionary of nodes. Key is the repo+branch
            Dictionary <string, DependencyFlowNode> nodes = new Dictionary <string, DependencyFlowNode>(
                StringComparer.OrdinalIgnoreCase);
            List <DependencyFlowEdge> edges = new List <DependencyFlowEdge>();

            // First create all the channel nodes. There may be disconnected
            // nodes in the graph, so we must process all channels and all subscriptions
            foreach (DefaultChannel channel in defaultChannels)
            {
                DependencyFlowNode flowNode = GetOrCreateNode(channel.Repository, channel.Branch, nodes);

                // Add the build times
                if (channel.Id != default(int))
                {
                    BuildTime buildTime = await barOnlyRemote.GetBuildTimeAsync(channel.Id, days);

                    flowNode.OfficialBuildTime = buildTime.OfficialBuildTime ?? 0;
                    flowNode.PrBuildTime       = buildTime.PrBuildTime ?? 0;
                    flowNode.GoalTimeInMinutes = buildTime.GoalTimeInMinutes ?? 0;
                }
                else
                {
                    flowNode.OfficialBuildTime = 0;
                    flowNode.PrBuildTime       = 0;
                }

                // Add a the output mapping.
                flowNode.OutputChannels.Add(channel.Channel.Name);
            }

            // Process all subscriptions (edges)
            foreach (Subscription subscription in subscriptions)
            {
                // Get the target of the subscription
                DependencyFlowNode destinationNode = GetOrCreateNode(subscription.TargetRepository, subscription.TargetBranch, nodes);
                // Add the input channel for the node
                destinationNode.InputChannels.Add(subscription.Channel.Name);
                // Find all input nodes by looking up the default channels of the subscription input channel and repository.
                // This may return no nodes if there is no default channel for the inputs.
                IEnumerable <DefaultChannel> inputDefaultChannels = defaultChannels.Where(d => d.Channel.Name == subscription.Channel.Name &&
                                                                                          d.Repository.Equals(subscription.SourceRepository, StringComparison.OrdinalIgnoreCase));
                foreach (DefaultChannel defaultChannel in inputDefaultChannels)
                {
                    DependencyFlowNode sourceNode = GetOrCreateNode(defaultChannel.Repository, defaultChannel.Branch, nodes);

                    DependencyFlowEdge newEdge = new DependencyFlowEdge(sourceNode, destinationNode, subscription);
                    destinationNode.IncomingEdges.Add(newEdge);
                    sourceNode.OutgoingEdges.Add(newEdge);
                    edges.Add(newEdge);
                }
            }

            return(new DependencyFlowGraph(nodes.Select(kv => kv.Value).ToList(), edges));
        }
Ejemplo n.º 17
0
        public async Task SubscriptionDeletedAsync(string user)
        {
            ConditionalValue <InProgressPullRequest> maybePr =
                await StateManager.TryGetStateAsync <InProgressPullRequest>(PullRequest);

            if (maybePr.HasValue)
            {
                InProgressPullRequest pr = maybePr.Value;
                if (string.IsNullOrEmpty(pr.Url))
                {
                    // somehow a bad PR got in the collection, remove it
                    await StateManager.RemoveStateAsync(PullRequest);

                    return;
                }

                long installationId = 0;
                if (pr.Url.Contains("github.com"))
                {
                    (string owner, string repo, int id) = GitHubClient.ParsePullRequestUri(pr.Url);
                    installationId = await Context.GetInstallationId($"https://github.com/{owner}/{repo}");
                }

                IRemote darc = await DarcFactory.CreateAsync(pr.Url, installationId);

                await darc.CreatePullRequestCommentAsync(
                    pr.Url,
                    $@"The subscription that generated this pull request has been deleted by @{user}.
This pull request will no longer be tracked by maestro.");

                await StateManager.RemoveStateAsync(PullRequest);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Retrieve information about channels
        /// </summary>
        /// <param name="options">Command line options</param>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                var allChannels = await remote.GetChannelsAsync();

                // Write out a simple list of each channel's name
                foreach (var channel in allChannels.OrderBy(c => c.Name))
                {
                    // Pad so that id's up to 9999 will result in consistent
                    // listing
                    string idPrefix = $"({channel.Id})".PadRight(7);
                    Console.WriteLine($"{idPrefix}{channel.Name}");
                }

                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve channels");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 19
0
        // =================================================================
        //              UI Events
        // =================================================================

        private void ButtonConnect_Click(object sender, EventArgs e)
        {
            var sd = ServersConfig.GetInstance().GetSelected();

            if (sd == null)
            {
                return;
            }
            if (rm == null)
            {
                RemoteManager rmm = RemoteManager.GetInstance();
                rm = rmm.Connect(sd);

                if (rm.IsConnected())
                {
                    st = rm.GetStream();
                    ButtonConnect.Text = "Disconnect";
                }
                return;
            }

            if (rm.IsConnected())
            {
                rm.Disconnect();
                rm = null;
                st = null;
                ButtonConnect.Text = "Connect";
            }
        }
 public NetworkTableConnectionListenerAdapter(IRemote ir, IRemoteConnectionListener ircl)
 {
   base.\u002Ector();
   NetworkTableConnectionListenerAdapter connectionListenerAdapter = this;
   this.targetSource = ir;
   this.targetListener = ircl;
 }
Ejemplo n.º 21
0
 public void Connected(IRemote remote, ConnectionInfo info)
 {
     ConsoleManager.Instance.AppendInfo(
         $"Network tables connected at {info.RemoteIp}. Protocol version: {info.ProtocolVersion}.",
         Color.Green);
     parent.SetRioStatusLight(true);
 }
Ejemplo n.º 22
0
        public StatusCommand(
            ICacheManager cacheManager,
            IRemote remote,
            string[] args)
        {
            if (args.Length > 1)
                throw new ArgumentException();

            if (args.Length == 1)
            {
                if (args[0] == ShowRemoteArgument)
                {
                    _shouldShowRemote = true;
                }
                else
                {
                    throw new ArgumentException("status command only has one valid option: " + ShowRemoteArgument);
                }
            }

            _cacheManager = cacheManager;
            _remote = remote;

            _filesInLocalCache = _cacheManager.ListFiles();
        }
Ejemplo n.º 23
0
        /// <summary>
        ///     Resolve a channel substring to an exact channel, or print out potential names if more than one, or none, match.
        /// </summary>
        /// <param name="remote">Remote for retrieving channels</param>
        /// <param name="desiredChannel">Desired channel</param>
        /// <returns>Channel, or null if no channel was matched.</returns>
        public static async Task <Channel> ResolveSingleChannel(IRemote remote, string desiredChannel)
        {
            // Retrieve the channel by name, matching substring. If more than one channel
            // matches, then let the user know they need to be more specific
            IEnumerable <Channel> channels         = (await remote.GetChannelsAsync());
            IEnumerable <Channel> matchingChannels = channels.Where(c => c.Name.Contains(desiredChannel, StringComparison.OrdinalIgnoreCase));

            if (!matchingChannels.Any())
            {
                Console.WriteLine($"No channels found with name containing '{desiredChannel}'");
                Console.WriteLine("Available channels:");
                foreach (Channel channel in channels)
                {
                    Console.WriteLine($"  {channel.Name}");
                }
                return(null);
            }
            else if (matchingChannels.Count() != 1)
            {
                Console.WriteLine($"Multiple channels found with name containing '{desiredChannel}', please select one");
                foreach (Channel channel in matchingChannels)
                {
                    Console.WriteLine($"  {channel.Name}");
                }
                return(null);
            }
            else
            {
                return(matchingChannels.Single());
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        ///     Verify that a branch exists in the specified repo and contains a version details file.
        ///     If it does not, optionally prompt the user to confirm that they wish to continue.
        /// </summary>
        /// <param name="remote">Remote</param>
        /// <param name="repo">Repository that the branch should be in</param>
        /// <param name="branch">Branch to check the existence of</param>
        /// <param name="prompt">Prompt the user to verify that they want to continue</param>
        /// <returns>True if the branch exists, prompting is not desired, or if the user confirms that they want to continue. False otherwise.</returns>
        public static async Task <bool> VerifyAndConfirmBranchExistsAsync(IRemote remote, string repo, string branch, bool prompt)
        {
            const string regexPrefix = "-regex:";

            // IRemote doesn't currently provide a way for enumerating all branches in a repo, and the purpose of supporting regex is to allow new ones to match
            // So in this case we'll just prompt
            if (branch.StartsWith(regexPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                Console.WriteLine($"Warning: Regular expression '{branch.Substring(regexPrefix.Length)}' will be used to match on branches in '{repo}'.");
                Console.WriteLine("To ensure dependency updates (where desired), please verify all branches matching this pattern contain an eng/Version.Details.xml file.");
                return(!prompt || PromptForYesNo("Continue?"));
            }

            try
            {
                branch = GitHelpers.NormalizeBranchName(branch);

                await remote.GetDependenciesAsync(repo, branch);
            }
            catch (DependencyFileNotFoundException)
            {
                Console.WriteLine($"Warning: Could not find an eng/Version.Details.xml at '{repo}@{branch}'. Dependency updates may not happen as expected.");
                if (prompt)
                {
                    return(PromptForYesNo("Continue?"));
                }
            }

            return(true);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Adds a new channel with the specified name.
        /// </summary>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                // If the user tried to mark as internal, indicate that this is currently
                // unsupported.
                if (_options.Internal)
                {
                    Logger.LogError("Cannot currently mark channels as internal.");
                    return(Constants.ErrorCode);
                }

                Channel newChannelInfo = await remote.CreateChannelAsync(_options.Name, _options.Classification);

                Console.WriteLine($"Successfully created new channel with name '{_options.Name}'.");

                return(Constants.SuccessCode);
            }
            catch (RestApiException e) when(e.Response.StatusCode == HttpStatusCode.Conflict)
            {
                Logger.LogError($"An existing channel with name '{_options.Name}' already exists");
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to create new channel.");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 26
0
        public StatusCommand(
            ICacheManager cacheManager,
            IRemote remote,
            string[] args)
        {
            if (args.Length > 1)
            {
                throw new ArgumentException();
            }

            if (args.Length == 1)
            {
                if (args[0] == ShowRemoteArgument)
                {
                    _shouldShowRemote = true;
                }
                else
                {
                    throw new ArgumentException("status command only has one valid option: " + ShowRemoteArgument);
                }
            }

            _cacheManager = cacheManager;
            _remote       = remote;

            _filesInLocalCache = _cacheManager.ListFiles();
        }
        public async override Task <int> ExecuteAsync()
        {
            if (!(_options.Released ^ _options.NotReleased))
            {
                Console.WriteLine("Please specify either --released or --not-released.");
                return(Constants.ErrorCode);
            }

            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                Build updatedBuild = await remote.UpdateBuildAsync(_options.Id, new BuildUpdate { Released = _options.Released });

                Console.WriteLine($"Updated build {_options.Id} with new information.");
                Console.WriteLine(UxHelpers.GetTextBuildDescription(updatedBuild));
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Error: Failed to update build with id '{_options.Id}'");
                return(Constants.ErrorCode);
            }

            return(Constants.SuccessCode);
        }
Ejemplo n.º 28
0
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetRemote(_options, _options.Repository, Logger);

                _options.Branch = GitHelpers.NormalizeBranchName(_options.Branch);

                if (!(await UxHelpers.VerifyAndConfirmBranchExistsAsync(remote, _options.Repository, _options.Branch, !_options.NoConfirmation)))
                {
                    Console.WriteLine("Aborting default channel creation.");
                    return(Constants.ErrorCode);
                }

                await remote.AddDefaultChannelAsync(_options.Repository, _options.Branch, _options.Channel);

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to add a new default channel association.");
                return(Constants.ErrorCode);
            }
        }
        /// <summary>
        /// Retrieve information about the default association between builds of a specific branch/repo
        /// and a channel.
        /// </summary>
        /// <returns></returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                IEnumerable <DefaultChannel> defaultChannels = (await remote.GetDefaultChannelsAsync()).Where(defaultChannel =>
                {
                    return((string.IsNullOrEmpty(_options.SourceRepository) ||
                            defaultChannel.Repository.Contains(_options.SourceRepository, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.Branch) ||
                            defaultChannel.Branch.Contains(_options.Branch, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.Channel) ||
                            defaultChannel.Channel.Name.Contains(_options.Channel, StringComparison.OrdinalIgnoreCase)));
                });

                if (defaultChannels.Count() == 0)
                {
                    Console.WriteLine("No matching channels were found.");
                }

                // Write out a simple list of each channel's name
                foreach (DefaultChannel defaultChannel in defaultChannels)
                {
                    Console.WriteLine(OutputHelpers.GetDefaultChannelDescriptionString(defaultChannel));
                }

                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve default channel information.");
                return(Constants.ErrorCode);
            }
        }
Ejemplo n.º 30
0
 public void Disconnected(IRemote remote, ConnectionInfo info)
 {
     ConsoleManager.Instance.AppendError(
         $"Network tables disconnected from {info.RemoteIp}. Protocol version: {info.ProtocolVersion}.");
     parent.SetRioStatusLight(false);
     parent.SetNtRelayStatusLight(false);
 }
Ejemplo n.º 31
0
 private static void TestConnect(IRemote re)
 {
     re.UID           = connectCount;
     re.OnDisConnect += (er) =>
     {
         Console.WriteLine($"连接断开{re.UID}");
     };
 }
Ejemplo n.º 32
0
        private static async Task TestLazySendAsync(IRemote remote)
        {
            await SafeRpcSendAsync(remote);
            await SafeRpcSendAsyncTimeOut(remote);
            await SafeRpcSendAsyncTypeError(remote);

            //await Task.Delay(-1);
        }
Ejemplo n.º 33
0
        public void AddRouting(int key, Guid srcUuid, IRemote routeTo)
        {
            Dictionary<Guid, IRemote> subcriptions = null;
            if (!keyTobackendSubcriptions.TryGetValue(key, out subcriptions))
            {
                subcriptions = keyTobackendSubcriptions[key] = new Dictionary<Guid, IRemote>();
            }

            subcriptions[srcUuid] = routeTo;
        }
Ejemplo n.º 34
0
        public SmudgeCommand(
            ICacheManager cacheManager,
            IRemote remote,
            string[] args)
        {
            if (args.Length != 0)
                throw new ArgumentException();

            _cacheManager = cacheManager;
            _remote = remote;
        }
Ejemplo n.º 35
0
 public object Invoke(IRemote remoteObject, string methodName, object[] methodParameters)
 {
     try
     {
         //Indirectly call the remote interface
         return remoteObject.Invoke(methodName, methodParameters);
     }
     catch (Exception ex)
     {
         throw new Exception("(InvocationManager.Invoke) Couldn't invoke '" + methodName + "' method:" + Environment.NewLine + ex.ToString());
     }
 }
Ejemplo n.º 36
0
 public object Invoke(IRemote remoteObject, string methodName, object[] methodParameters)
 {
     try
     {
         //Indirectly call the remote interface
         //return remoteObject.Invoke(methodName, methodParameters);
         return remoteContainer.Invoke(methodName, methodParameters);
     }
     catch (Exception ex)
     {
         throw new Exception("Couldn't invoke " + methodName + " because:" + Environment.NewLine + ex.ToString());
     }
 }
Ejemplo n.º 37
0
        private void OnFrontendMessageReceived(IRemote conn, Message msg)
        {
            Console.WriteLine("OnFrontendMessageReceived id:{0} ip:{1} port:{2}", conn.Id, conn.RemoteIp, conn.RemotePort);
            Console.WriteLine("OnFrontendMessageReceived msgLen:{0}", msg.Buffer.Length);

            // forward frontend msg to backend, 
            // which is based on uuid associated with the msg

            var stream = new MemoryStream(msg.Buffer);
            var br = new BinaryReader(stream);
            var msgType = (GateMessage)br.ReadByte();

            Console.WriteLine("OnFrontendMessageReceived msgType:{0}", msgType);

            switch (msgType)
            {
                case GateMessage.Send:
                    {
                        var uuid = new Guid(br.ReadBytes(UuidLen));
                        var key = br.ReadInt32();

                        Console.WriteLine("OnFrontendMessageReceived key:{0} uuid:{1}", key, uuid);
                        broker.RouteData(key, uuid, msg.Buffer, msg.Buffer.Length - 17, 17);
                    }
                    break;
                case GateMessage.Handshake:
                    {
                        var uuid = new Guid(br.ReadBytes(UuidLen));

                        Console.WriteLine("OnFrontendMessageReceived uuid:{0}", uuid);

                        uuidToClients[uuid] = conn;

                        // send back a ack
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 38
0
 public static void PushReceivedMessage(IRemote remote, byte[] data, int len, int offset)
 {
     if (!remote.Connected)
     {
         return;
     }
     remote.PushBegin(receivedBuffer.Length + len);
     remote.PushMore(receivedBuffer, receivedBuffer.Length, 0);
     remote.PushMore(data, len, offset);
 }
Ejemplo n.º 39
0
        private void OnBackendMessageReceived(IRemote conn, Message msg)
        {
            Console.WriteLine("OnBackendMessageReceived id:{0} ip:{1} port:{2}", conn.Id, conn.RemoteIp, conn.RemotePort);
            Console.WriteLine("OnBackendMessageReceived msgLen:{0}", msg.Buffer.Length);

            // forward backend msg to frontend, 
            // which is based on forwardId associated with the msg

            var stream = new MemoryStream(msg.Buffer);
            var br = new BinaryReader(stream);
            var msgType = (GateMessage)br.ReadByte();

            Console.WriteLine("OnBackendMessageReceived msgType:{0}", msgType);

            switch (msgType)
            {
                #region Broker Component
                case GateMessage.Subscribe:
                    {
                        var key = br.ReadInt32();
                        var uuid = new Guid(br.ReadBytes(UuidLen));

                        Console.WriteLine("OnBackendMessageReceived key:{0} uuid:{1}", key, uuid);
                        broker.AddRouting(key, uuid, conn);
                    }
                    break;
                case GateMessage.Unicast:
                    {
                        var uuid = new Guid(br.ReadBytes(UuidLen));

                        Console.WriteLine("OnBackendMessageReceived uuid:{0}", uuid);
                        // uuid to client IRemote
                        IRemote remote = null;
                        if (!uuidToClients.TryGetValue(uuid, out remote))
                        {
                            return;
                        }

                        PushReceivedMessage(remote, msg.Buffer, msg.Buffer.Length - UuidLen - 1, UuidLen + 1);
                    }
                    break;
                #endregion

                #region Forward Component
                case GateMessage.AddForward:
                case GateMessage.RemoveForward:
                    {
                        var uuid = new Guid(br.ReadBytes(UuidLen));
                        var forwardId = br.ReadInt32();

                        Console.WriteLine("OnBackendMessageReceived uuid:{0} forwardId:{1}", uuid, forwardId);
                        // todo 
                        // what if backend control forward first,
                        // then client handshake?
                        switch (msgType)
                        {
                            case GateMessage.AddForward:
                                forwardManager.AddForward(uuid, forwardId);
                                break;
                            case GateMessage.RemoveForward:
                                forwardManager.RemoveForward(uuid, forwardId);
                                break;
                        }
                    }
                    break;
                case GateMessage.Multicast:
                    {
                        var forwardId = br.ReadInt32();

                        Console.WriteLine("OnBackendMessageReceived forwardId:{0}", forwardId);
                        // forwardId to client IRemotes
                        foreach (var uuid in forwardManager.GetForwardGroup(forwardId))
                        {
                            IRemote remote = null;
                            if (uuidToClients.TryGetValue(uuid, out remote))
                            {
                                PushReceivedMessage(remote, msg.Buffer, msg.Buffer.Length - 4 - 1, 4 + 1);
                            }
                        }
                    }
                    break;
                #endregion
            }
        }
 public virtual void disconnected(IRemote ir)
 {
   this.targetListener.disconnected(this.targetSource);
 }
Ejemplo n.º 41
0
 public PacketDisconnect(IRemote remote) :base(remote) {
 }
 public void Disconnected(IRemote remote, ConnectionInfo info)
 {
     DisconnectedRemote = remote;
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PacketReader"/> class.
 /// </summary>
 /// <param name="c">The remote.</param>
 public PacketReader ( IRemote  c ) {
     mReader = new BinaryReader( c.NetworkStream );
     this.remote = c;
     options = c.PacketOptions;
 }
Ejemplo n.º 44
0
 protected override void OnClientDisconnected(IRemote client, string message)
 {
     ((Client) client).OnDisconnect(message);
 }
Ejemplo n.º 45
0
 public PacketLogin(IRemote remote)
     : base(remote) {
 }
Ejemplo n.º 46
0
 public PacketPing(IRemote remote) :base(remote) {
 }
Ejemplo n.º 47
0
 public Packet(IRemote remote)
 {
     this.remote = remote;
 }
Ejemplo n.º 48
0
 public PacketInvalid(IRemote remote) :base(remote) {
 }
Ejemplo n.º 49
0
 public PacketHandShake(IRemote remote) :base(remote) {
 }
Ejemplo n.º 50
0
        private void OnBackendDisconnected(IRemote conn)
        {
            Console.WriteLine("OnBackendDisconnected id:{0} ip:{1} port:{2}", conn.Id, conn.RemoteIp, conn.RemotePort);


        }
Ejemplo n.º 51
0
 public PacketMessage(IRemote remote) :base(remote) {
 }
Ejemplo n.º 52
0
        protected override void ProcessCommand(System.Net.Sockets.NetworkStream nstm, char tag)
        {
            int len;

            switch (tag)
            {
                case 'R': // Remote!
                    {
                        string classname = XContent.ReceiveXString(nstm, buf);

                        string xlibfn = CreateXlibFileName("remote");
                        {
                            buf = XContent.ReceiveXBytes(nstm, out len, buf);
                            if (0 != len)
                            {
                                System.IO.FileStream stm = System.IO.File.Create(xlibfn);
                                stm.Write(buf, 0, len);
                                stm.Close();
                            }
                        }

                        string dllfn = CreateDllFileName("remote");
                        {
                            buf = XContent.ReceiveXBytes(nstm, out len, buf);
                            System.IO.FileStream stm = System.IO.File.Create(dllfn);
                            stm.Write(buf, 0, len);
                            stm.Close();
                        }

                        if (XLog.logging)
                        {
                            string xclassname = classname;
                            if (null == xclassname)
                            {
                                xclassname = "<null>";
                            }
                            XLog.log("Loading IRemote plugin named " + xclassname + " for remote: " + dllfn);
                        }

                        rem = LoadRemotePlugin(dllfn, classname);
#if DEBUG
                        try
                        {
                            rem.OnRemote();
                        }
                        catch (Exception e)
                        {
                            throw new UserException(e);
                        }
#else
                        rem.OnRemote();
#endif
                    }
                    break;

                case 'O': //Query DGlobals
                    {
                        int byteCount = DGlobalsM.ToBytes(ref buf);
                        XContent.SendXContent(nstm, buf, byteCount);
                    }
                    break;

                case 'r':
                    {                      
                        buf = XContent.ReceiveXBytes(nstm, out len, buf);
                        int n = Entry.BytesToInt(buf);
                        int count = 0;
                        if (null != rem)
                        {
                            List<long> appendsizes = new List<long>();
                            try
                            {
                                count = rem.GetOutputFileCount(n, appendsizes);
                            }
                            catch(Exception e)
                            {
                                throw new DistributedObjectsSlave.DistObjectAbortException(e);
                            }
                            
                            if (buf.Length < 4 + 8 * appendsizes.Count)
                            {
                                buf = new byte[Entry.Round2Power(4 + 8 * appendsizes.Count)];
                            }
                            Entry.ToBytes(count, buf, 0);
                            int offset = 4;
                            for (int i = 0; i < appendsizes.Count; i++, offset += 8)
                            {
                                Entry.LongToBytes(appendsizes[i], buf, offset);
                            }
                            XContent.SendXContent(nstm, buf, 4 + 8 * appendsizes.Count);
                            break; // !
                        }
                        Entry.ToBytes(count, buf, 0);
                        XContent.SendXContent(nstm, buf, 4);
                    }
                    break;

                default:
                    base.ProcessCommand(nstm, tag);
                    break;
            }
        }
Ejemplo n.º 53
0
 public virtual void disconnected(IRemote remote)
 {
   if (this.connected)
   {
     this.connected = false;
     if (!this.firstRun)
       SwingUtilities.invokeLater(this.repainter);
   }
   this.firstRun = false;
 }
Ejemplo n.º 54
0
        public override void SendMessage(INetworkMessage message, IRemote recipient, DeliveryMethod method, int sequenceChannel)
        {
            var client = ((Client) recipient).Connection;

            Peer.SendMessage(PrepareMessage(message), client, (NetDeliveryMethod) method, sequenceChannel);
        }