public BuiltUpService BuildUp(ServiceName name, object target)
 {
     var dependencies = GetInjections(name);
     foreach (var dependency in dependencies)
         dependency.setter(target, dependency.value.Single());
     return new BuiltUpService(dependencies);
 }
예제 #2
0
 public void EnsureInitialized(ContainerService service, ContainerContext containerContext, ContainerService root)
 {
     if (!Owned)
         return;
     var componentInstance = Instance as IInitializable;
     if (componentInstance == null)
         return;
     if (!initialized)
         lock (this)
             if (!initialized)
             {
                 var name = new ServiceName(Instance.GetType(), service.UsedContracts);
                 if (containerContext.infoLogger != null)
                     containerContext.infoLogger(name, "initialize started");
                 try
                 {
                     componentInstance.Initialize();
                 }
                 catch (Exception e)
                 {
                     throw new SimpleContainerException(string.Format("exception initializing {0}\r\n\r\n{1}", name, root.GetConstructionLog(containerContext)), e);
                 }
                 if (containerContext.infoLogger != null)
                     containerContext.infoLogger(name, "initialize finished");
                 initialized = true;
             }
 }
예제 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessage"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="methodName">The name of the authentication method.</param>
 protected RequestMessage(ServiceName serviceName, string username, string methodName)
 {
     _serviceName = serviceName.ToArray();
     _userName = Utf8.GetBytes(username);
     _methodNameBytes = Ascii.GetBytes(methodName);
     _methodName = methodName;
 }
        protected NuGetService(ServiceName serviceName, ServiceHost host)
        {
            Host = host;
            ServiceName = serviceName;

            TempDirectory = Path.Combine(Path.GetTempPath(), "NuGetServices", serviceName.Name);
        }
예제 #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceRequestMessage"/> class.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        public ServiceRequestMessage(ServiceName serviceName)
        {
#if TUNING
            _serviceName = serviceName.ToArray();
#else
            ServiceName = serviceName;
#endif
        }
예제 #6
0
        public WorkService(ServiceName name, ServiceHost host)
            : base(name, host)
        {
            var workConfig = host.Config.GetSection<WorkConfiguration>();

            MaxWorkers = MaxWorkers ?? workConfig.MaxWorkers;
            WorkersPerCore = WorkersPerCore ?? (workConfig.WorkersPerCore ?? DefaultWorkersPerCore);
        }
예제 #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessageHost"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="publicKeyAlgorithm">The public key algorithm.</param>
 /// <param name="publicHostKey">The public host key.</param>
 /// <param name="clientHostName">Name of the client host.</param>
 /// <param name="clientUsername">The client username.</param>
 public RequestMessageHost(ServiceName serviceName, string username, string publicKeyAlgorithm, byte[] publicHostKey, string clientHostName, string clientUsername)
     : base(serviceName, username)
 {
     this.PublicKeyAlgorithm = publicKeyAlgorithm;
     this.PublicHostKey = publicHostKey;
     this.ClientHostName = clientHostName;
     this.ClientUsername = clientUsername;
 }
예제 #8
0
 public void MethodNameTest()
 {
     ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     RequestMessage target = new RequestMessage(serviceName, username); // TODO: Initialize to an appropriate value
     string actual;
     actual = target.MethodName;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
예제 #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessageHost"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="publicKeyAlgorithm">The public key algorithm.</param>
 /// <param name="publicHostKey">The public host key.</param>
 /// <param name="clientHostName">Name of the client host.</param>
 /// <param name="clientUsername">The client username.</param>
 /// <param name="signature">The signature.</param>
 public RequestMessageHost(ServiceName serviceName, string username, string publicKeyAlgorithm, byte[] publicHostKey, string clientHostName, string clientUsername, byte[] signature)
     : base(serviceName, username, "hostbased")
 {
     PublicKeyAlgorithm = Ascii.GetBytes(publicKeyAlgorithm);
     PublicHostKey = publicHostKey;
     ClientHostName = Ascii.GetBytes(clientHostName);
     ClientUsername = Utf8.GetBytes(clientUsername);
     Signature = signature;
 }
 public void RequestMessagePublicKeyConstructorTest()
 {
     ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
     byte[] keyData = null; // TODO: Initialize to an appropriate value
     RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
 public void MethodNameTest()
 {
     ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
     byte[] keyData = null; // TODO: Initialize to an appropriate value
     RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value
     string actual;
     actual = target.MethodName;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
예제 #12
0
 /// <summary>
 /// Called when type specific data need to be loaded.
 /// </summary>
 protected override void LoadData()
 {
     var serviceName = this.ReadAsciiString();
     switch (serviceName)
     {
         case "ssh-userauth":
             this.ServiceName = ServiceName.UserAuthentication;
             break;
         case "ssh-connection":
             this.ServiceName = ServiceName.Connection;
             break;
     }
 }
예제 #13
0
 [Ignore] // placeholder
 public void SignatureTest()
 {
     ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
     byte[] keyData = null; // TODO: Initialize to an appropriate value
     RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value
     byte[] expected = null; // TODO: Initialize to an appropriate value
     target.Signature = expected;
     var actual = target.Signature;
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
예제 #14
0
        /// <summary>
        /// Called when type specific data need to be loaded.
        /// </summary>
        protected override void LoadData()
        {
#if TUNING
            ServiceName = ReadBinary().ToServiceName();
#else
            var serviceName = ReadAsciiString();
            switch (serviceName)
            {
                case "ssh-userauth":
                    ServiceName = ServiceName.UserAuthentication;
                    break;
                case "ssh-connection":
                    ServiceName = ServiceName.Connection;
                    break;
            }
#endif
        }
    public void CreatesService()
    {
        // Setup namespace for the test.
        var namespaceId = _fixture.RandomResourceId;

        _fixture.CreateNamespace(namespaceId);

        var serviceId = _fixture.RandomResourceId;
        // Run the sample code.
        var createServiceSample = new CreateServiceSample();
        var result = createServiceSample.CreateService(_fixture.ProjectId, _fixture.LocationId, namespaceId, serviceId);

        // Get the service.
        var serviceName = ServiceName.FromProjectLocationNamespaceService(_fixture.ProjectId, _fixture.LocationId, namespaceId, serviceId);
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        var service = registrationServiceClient.GetService(serviceName);

        Assert.Contains(serviceId, service.Name);
    }
예제 #16
0
        public void GetServiceRequestObject()
        {
            moq::Mock <DataprocMetastore.DataprocMetastoreClient> mockGrpcClient = new moq::Mock <DataprocMetastore.DataprocMetastoreClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetServiceRequest request = new GetServiceRequest
            {
                ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"),
            };
            Service expectedResponse = new Service
            {
                ServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"),
                CreateTime  = new wkt::Timestamp(),
                UpdateTime  = new wkt::Timestamp(),
                Labels      =
                {
                    {
                        "key8a0b6e3c",
                        "value60c16320"
                    },
                },
                HiveMetastoreConfig  = new HiveMetastoreConfig(),
                NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
                EndpointUri          = "endpoint_uri59c03c94",
                Port                = -78310000,
                State               = Service.Types.State.Deleting,
                StateMessage        = "state_message46cf28c0",
                ArtifactGcsUri      = "artifact_gcs_uri4d2b3985",
                Tier                = Service.Types.Tier.Developer,
                MetadataIntegration = new MetadataIntegration(),
                MaintenanceWindow   = new MaintenanceWindow(),
                Uid = "uida2d37198",
                MetadataManagementActivity = new MetadataManagementActivity(),
                ReleaseChannel             = Service.Types.ReleaseChannel.Stable,
            };

            mockGrpcClient.Setup(x => x.GetService(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            DataprocMetastoreClient client = new DataprocMetastoreClientImpl(mockGrpcClient.Object, null);
            Service response = client.GetService(request);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
예제 #17
0
        /// <summary>Snippet for ResolveServiceAsync</summary>
        public async Task ResolveServiceRequestObjectAsync()
        {
            // Snippet: ResolveServiceAsync(ResolveServiceRequest, CallSettings)
            // Additional: ResolveServiceAsync(ResolveServiceRequest, CancellationToken)
            // Create client
            LookupServiceClient lookupServiceClient = await LookupServiceClient.CreateAsync();

            // Initialize request argument(s)
            ResolveServiceRequest request = new ResolveServiceRequest
            {
                ServiceName    = ServiceName.FromProjectLocationNamespaceService("[PROJECT]", "[LOCATION]", "[NAMESPACE]", "[SERVICE]"),
                MaxEndpoints   = 0,
                EndpointFilter = "",
            };
            // Make the request
            ResolveServiceResponse response = await lookupServiceClient.ResolveServiceAsync(request);

            // End snippet
        }
예제 #18
0
        private SMB1FileStore TreeConnect(string shareName, ServiceName serviceName)
        {
            if (!IsConnected || !m_isLoggedIn)
            {
                throw new InvalidOperationException("A login session must be successfully established before connecting to a share");
            }

            TreeConnectAndXRequest request = new TreeConnectAndXRequest
            {
                Path    = shareName,
                Service = serviceName
            };

            SendMessage(request);
            SMB1Message reply = WaitForMessage(CommandName.SMB_COM_TREE_CONNECT_ANDX);

            reply.IsSuccessElseThrow();
            return(new SMB1FileStore(this, reply.Header.TID));
        }
        /// <summary>Snippet for ListServiceLevelObjectives</summary>
        public void ListServiceLevelObjectives()
        {
            // Snippet: ListServiceLevelObjectives(ServiceName,string,int?,CallSettings)
            // Create client
            ServiceMonitoringServiceClient serviceMonitoringServiceClient = ServiceMonitoringServiceClient.Create();
            // Initialize request argument(s)
            ServiceName parent = new ServiceName("[PROJECT]", "[SERVICE]");
            // Make the request
            PagedEnumerable <ListServiceLevelObjectivesResponse, ServiceLevelObjective> response =
                serviceMonitoringServiceClient.ListServiceLevelObjectives(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (ServiceLevelObjective item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListServiceLevelObjectivesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (ServiceLevelObjective item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <ServiceLevelObjective> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (ServiceLevelObjective item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
예제 #20
0
        /// <summary>Snippet for ListSkus</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListSkusResourceNames()
        {
            // Create client
            CloudCatalogClient cloudCatalogClient = CloudCatalogClient.Create();
            // Initialize request argument(s)
            ServiceName parent = ServiceName.FromService("[SERVICE]");
            // Make the request
            PagedEnumerable <ListSkusResponse, Sku> response = cloudCatalogClient.ListSkus(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Sku item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListSkusResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Sku item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int        pageSize   = 10;
            Page <Sku> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Sku item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
예제 #21
0
        internal object Create(ServiceName name, bool isEnumerable, object arguments)
        {
            Func <object> compiledFactory;
            var           hasPendingResolutionContext = ResolutionContext.HasPendingResolutionContext;

            if (arguments == null && factoryCache.TryGetValue(name, out compiledFactory) && !hasPendingResolutionContext)
            {
                return(compiledFactory());
            }
            var activation                = ResolutionContext.Push(this);
            ContainerService result       = null;
            List <string>    oldContracts = null;

            try
            {
                if (hasPendingResolutionContext)
                {
                    oldContracts = activation.activated.Contracts.Replace(name.Contracts);
                    name         = new ServiceName(name.Type);
                }
                result = ResolveCore(name, true, ObjectAccessor.Get(arguments), activation.activated);
            }
            finally
            {
                if (oldContracts != null)
                {
                    activation.activated.Contracts.Restore(oldContracts);
                }
                PopResolutionContext(activation, result, isEnumerable);
            }
            if (!hasPendingResolutionContext)
            {
                result.EnsureInitialized(containerContext, result);
            }
            result.CheckStatusIsGood(containerContext);
            if (isEnumerable)
            {
                return(result.GetAllValues());
            }
            result.CheckSingleValue(containerContext);
            return(result.Instances[0].Instance);
        }
예제 #22
0
        public void LoadConfiguration(string filepath)
        {
            var    dictionary = new Dictionary <string, ServiceName>();
            Stream resource   = null;

            if (filepath == null)
            {
                var assembly = Assembly.GetExecutingAssembly();
                resource = assembly.GetManifestResourceStream("Tarzan.Nfx.ProtocolClassifiers.PortBased.Resources.service-names-port-numbers.csv");
            }
            else
            {
                resource = File.Open(filepath, FileMode.Open);
            }
            using (var tr = new StreamReader(resource))
            {
                for (var line = tr.ReadLine(); line != null; line = tr.ReadLine())
                {
                    var components = line.Split(',');
                    if (components.Length < 4)
                    {
                        continue;
                    }
                    var name        = components[0];
                    var port        = components[1];
                    var protocol    = components[2];
                    var description = components[3];
                    if (!String.IsNullOrWhiteSpace(port) && Int32.TryParse(port, out int protocolNumber))
                    {
                        var key = $"{protocol.ToLowerInvariant()}/{port}";
                        dictionary[key] = new ServiceName
                        {
                            Name        = String.IsNullOrWhiteSpace(name) ? key : name,
                            Port        = protocolNumber,
                            Protocol    = protocol,
                            Description = description
                        };
                    }
                }
                m_serviceDictionary = dictionary;
            }
        }
    public void DeletesService()
    {
        // Setup namespace and service for the test.
        var namespaceId = _fixture.RandomResourceId;
        var serviceId   = _fixture.RandomResourceId;

        _fixture.CreateNamespace(namespaceId);
        _fixture.CreateService(namespaceId, serviceId);
        // Run the sample code.
        var deleteServiceSample = new DeleteServiceSample();

        deleteServiceSample.DeleteService(_fixture.ProjectId, _fixture.LocationId, namespaceId, serviceId);

        // Try to get the service.
        RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
        var serviceName = ServiceName.FromProjectLocationNamespaceService(_fixture.ProjectId, _fixture.LocationId, namespaceId, serviceId);
        var exception   = Assert.Throws <RpcException>(() => registrationServiceClient.GetService(serviceName));

        Assert.Equal(StatusCode.NotFound, exception.StatusCode);
    }
예제 #24
0
        public override bool Equals(object o)
        {
            if (o == this)
            {
                return(true);
            }

            if (!(o is ZipkinEndpoint))
            {
                return(false);
            }

            ZipkinEndpoint that = (ZipkinEndpoint)o;

            return(((ServiceName == null)
              ? (that.ServiceName == null) : ServiceName.Equals(that.ServiceName)) &&
                   ((Ipv4 == null) ? (that.Ipv4 == null) : Ipv4.Equals(that.Ipv4)) &&
                   ((Ipv6 == null) ? (that.Ipv6 == null) : Ipv6.Equals(that.Ipv6)) &&
                   Port.Equals(that.Port));
        }
예제 #25
0
        public static string GetServiceString(ServiceName serviceName)
        {
            switch (serviceName)
            {
            case ServiceName.DiskShare:
                return("A:");

            case ServiceName.PrinterShare:
                return("LPT1:");

            case ServiceName.NamedPipe:
                return("IPC");

            case ServiceName.SerialCommunicationsDevice:
                return("COMM");

            default:
                return("?????");
            }
        }
예제 #26
0
        protected internal virtual void createJndiBindings()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.camunda.bpm.container.impl.jboss.util.PlatformServiceReferenceFactory managedReferenceFactory = new org.camunda.bpm.container.impl.jboss.util.PlatformServiceReferenceFactory(this);
            PlatformServiceReferenceFactory managedReferenceFactory = new PlatformServiceReferenceFactory(this);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.jboss.msc.service.ServiceName processEngineServiceBindingServiceName = org.jboss.as.naming.deployment.ContextNames.GLOBAL_CONTEXT_SERVICE_NAME.append(org.camunda.bpm.BpmPlatform.APP_JNDI_NAME).append(org.camunda.bpm.BpmPlatform.MODULE_JNDI_NAME).append(org.camunda.bpm.BpmPlatform.PROCESS_ENGINE_SERVICE_NAME);
            ServiceName processEngineServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME.append(BpmPlatform.APP_JNDI_NAME).append(BpmPlatform.MODULE_JNDI_NAME).append(BpmPlatform.PROCESS_ENGINE_SERVICE_NAME);

            // bind process engine service
            BindingUtil.createJndiBindings(childTarget, processEngineServiceBindingServiceName, BpmPlatform.PROCESS_ENGINE_SERVICE_JNDI_NAME, managedReferenceFactory);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.jboss.msc.service.ServiceName processApplicationServiceBindingServiceName = org.jboss.as.naming.deployment.ContextNames.GLOBAL_CONTEXT_SERVICE_NAME.append(org.camunda.bpm.BpmPlatform.APP_JNDI_NAME).append(org.camunda.bpm.BpmPlatform.MODULE_JNDI_NAME).append(org.camunda.bpm.BpmPlatform.PROCESS_APPLICATION_SERVICE_NAME);
            ServiceName processApplicationServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME.append(BpmPlatform.APP_JNDI_NAME).append(BpmPlatform.MODULE_JNDI_NAME).append(BpmPlatform.PROCESS_APPLICATION_SERVICE_NAME);

            // bind process application service
            BindingUtil.createJndiBindings(childTarget, processApplicationServiceBindingServiceName, BpmPlatform.PROCESS_APPLICATION_SERVICE_JNDI_NAME, managedReferenceFactory);
        }
예제 #27
0
파일: Socket.cs 프로젝트: yyyyj/ironruby
        public static RubyArray /*!*/ GetNameInfo(RubyClass /*!*/ self,
                                                  [DefaultProtocol, NotNull] MutableString /*!*/ address, [Optional] object flags)
        {
            IPEndPoint  ep      = UnpackSockAddr(address);
            IPHostEntry entry   = GetHostEntry(ep.Address, false);
            ServiceName service = SearchForService(ep.Port);

            RubyArray result = new RubyArray(2);

            result.Add(HostNameToMutableString(self.Context, entry.HostName));
            if (service != null)
            {
                result.Add(MutableString.Create(service.Name));
            }
            else
            {
                result.Add(ep.Port);
            }
            return(result);
        }
예제 #28
0
파일: Socket.cs 프로젝트: yyyyj/ironruby
        public static RubyArray /*!*/ GetNameInfo(ConversionStorage <MutableString> /*!*/ stringCast, ConversionStorage <int> /*!*/ fixnumCast,
                                                  RubyClass /*!*/ self, [NotNull] RubyArray /*!*/ hostInfo, [Optional] object flags)
        {
            if (hostInfo.Count < 3 || hostInfo.Count > 4)
            {
                throw RubyExceptions.CreateArgumentError("First parameter must be a 3 or 4 element array");
            }

            RubyContext context = self.Context;

            // We only support AF_INET (IP V4) family
            AddressFamily addressFamily = ConvertToAddressFamily(stringCast, fixnumCast, hostInfo[0]);

            if (addressFamily != AddressFamily.InterNetwork)
            {
                throw new SocketException((int)SocketError.AddressFamilyNotSupported);
            }

            // Lookup the service name for the given port.
            int         port    = ConvertToPortNum(stringCast, fixnumCast, hostInfo[1]);
            ServiceName service = SearchForService(port);

            // hostInfo[2] should have a host name
            // if it exists and is not null hostInfo[3] should have an IP address
            // in that case we use that rather than the host name.
            object      hostName = (hostInfo.Count > 3 && hostInfo[3] != null) ? hostInfo[3] : hostInfo[2];
            IPHostEntry entry    = GetHostEntry(ConvertToHostString(stringCast, hostName), false);

            RubyArray result = new RubyArray(2);

            result.Add(HostNameToMutableString(context, entry.HostName));
            if (service != null)
            {
                result.Add(MutableString.Create(service.Name));
            }
            else
            {
                result.Add(port);
            }
            return(result);
        }
예제 #29
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (Enabled != null)
         {
             hashCode = hashCode * 59 + Enabled.GetHashCode();
         }
         if (AgentName != null)
         {
             hashCode = hashCode * 59 + AgentName.GetHashCode();
         }
         if (DiffPath != null)
         {
             hashCode = hashCode * 59 + DiffPath.GetHashCode();
         }
         if (ObservedPath != null)
         {
             hashCode = hashCode * 59 + ObservedPath.GetHashCode();
         }
         if (ServiceName != null)
         {
             hashCode = hashCode * 59 + ServiceName.GetHashCode();
         }
         if (PropertyNames != null)
         {
             hashCode = hashCode * 59 + PropertyNames.GetHashCode();
         }
         if (DistributionDelay != null)
         {
             hashCode = hashCode * 59 + DistributionDelay.GetHashCode();
         }
         if (ServiceUserTarget != null)
         {
             hashCode = hashCode * 59 + ServiceUserTarget.GetHashCode();
         }
         return(hashCode);
     }
 }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (DiffPath != null)
         {
             hashCode = hashCode * 59 + DiffPath.GetHashCode();
         }
         if (ServiceName != null)
         {
             hashCode = hashCode * 59 + ServiceName.GetHashCode();
         }
         if (ServiceUserTarget != null)
         {
             hashCode = hashCode * 59 + ServiceUserTarget.GetHashCode();
         }
         return(hashCode);
     }
 }
예제 #31
0
        private List <Rate> GetServiceRates(ServiceName serviceName, DateTime date)
        {
            List <Rate>         rates   = new List <Rate>();
            IServiceDataAdapter service = new ServiceFactory(_configuration).ExecuteCreation(serviceName);

            try {
                string             content      = service.GetContent(date);
                List <ServiceRate> serviceRates = service.GetRates(content);
                rates = serviceRates.Select(serviceRate => new Rate()
                {
                    ServiceId = service.GetId(),
                    Code      = serviceRate.Code,
                    Date      = date.ToString(),
                    Value     = serviceRate.Value
                }).ToList();
            }
            catch (Exception exception) {
                _logger.LogWarning(exception.Message);
            }
            return(rates);
        }
        public void ResolveServiceRequestObject()
        {
            moq::Mock <LookupService.LookupServiceClient> mockGrpcClient = new moq::Mock <LookupService.LookupServiceClient>(moq::MockBehavior.Strict);
            ResolveServiceRequest request = new ResolveServiceRequest
            {
                ServiceName    = ServiceName.FromProjectLocationNamespaceService("[PROJECT]", "[LOCATION]", "[NAMESPACE]", "[SERVICE]"),
                MaxEndpoints   = 1499755084,
                EndpointFilter = "endpoint_filter76fda152",
            };
            ResolveServiceResponse expectedResponse = new ResolveServiceResponse
            {
                Service = new Service(),
            };

            mockGrpcClient.Setup(x => x.ResolveService(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            LookupServiceClient    client   = new LookupServiceClientImpl(mockGrpcClient.Object, null);
            ResolveServiceResponse response = client.ResolveService(request);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
예제 #33
0
파일: Service1.cs 프로젝트: vf1/turnserver
        public void Debug(string[] args)
        {
            const int mutexDelay = 1000;

            Mutex mutex1 = new Mutex(false, @"{4A85555B-8675-4230-84A0-4C87FC234B42}-" + extension);
            Mutex mutex2 = new Mutex(false, @"{2F36CC7D-4486-46fd-AB4F-44C5D2157B46}-" + extension);

            mutex2.WaitOne();
            bool anotherStopped = mutex1.WaitOne(mutexDelay * 5);

            mutex2.ReleaseMutex();

            if (anotherStopped)
            {
                try
                {
                    fileLog = new FileStream(GetAppPath(ServiceName.Replace(' ', '.') + @".log"),
                                             FileMode.Create, FileAccess.Write, FileShare.Read);

                    Start2();

                    while (mutex2.WaitOne(0))
                    {
                        Thread.Sleep(mutexDelay);
                        mutex2.ReleaseMutex();
#if DEBUG
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        GC.Collect();
#endif
                    }
                }
                finally
                {
                    Stop2();
                }

                mutex1.ReleaseMutex();
            }
        }
예제 #34
0
        /// <summary>
        /// Set things in motion so your service can do its work.
        /// </summary>
        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            string          WorkingDirectory = System.Windows.Forms.Application.StartupPath;
            int             MultiXID         = 1;
            int             WSPort           = 18080;
            string          ConfigFile       = "TpmConfig.xml";
            ServiceSettings Settings         = new ServiceSettings();

            if (Settings.MultiXTpmInstances != null)
            {
                foreach (InstanceSettings Instance in Settings.MultiXTpmInstances)
                {
                    if (Instance.ServiceName.ToLower().Trim() == ServiceName.ToLower())
                    {
                        if (Instance.MultiXID != 0)
                        {
                            MultiXID = Instance.MultiXID;
                        }
                        if (Instance.ConfigFileName != null && Instance.ConfigFileName.Trim().Length > 0)
                        {
                            ConfigFile = Instance.ConfigFileName.Trim();
                        }
                        if (Instance.WebServicePort != 0)
                        {
                            WSPort = Instance.WebServicePort;
                        }
                        if (Instance.WorkingDirectory != null && Instance.WorkingDirectory.Trim().Length > 0)
                        {
                            WorkingDirectory = Instance.WorkingDirectory.Trim();
                        }
                    }
                }
            }
            Tpm = new CMultiXTpmCtrlClass();
            Tpm.WorkingDirectory = WorkingDirectory;
            Tpm.ConfigFileName   = ConfigFile;
            Tpm.WebServicePort   = (ushort)WSPort;
            Tpm.StartWithID(MultiXID);
        }
예제 #35
0
        public async Task GetServiceAsync()
        {
            Mock <ServiceMonitoringService.ServiceMonitoringServiceClient> mockGrpcClient = new Mock <ServiceMonitoringService.ServiceMonitoringServiceClient>(MockBehavior.Strict);
            GetServiceRequest expectedRequest = new GetServiceRequest
            {
                ServiceName = new ServiceName("[PROJECT]", "[SERVICE]"),
            };
            Service expectedResponse = new Service
            {
                ServiceName = new ServiceName("[PROJECT]", "[SERVICE]"),
                DisplayName = "displayName1615086568",
            };

            mockGrpcClient.Setup(x => x.GetServiceAsync(expectedRequest, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <Service>(Task.FromResult(expectedResponse), null, null, null, null));
            ServiceMonitoringServiceClient client = new ServiceMonitoringServiceClientImpl(mockGrpcClient.Object, null);
            ServiceName name     = new ServiceName("[PROJECT]", "[SERVICE]");
            Service     response = await client.GetServiceAsync(name);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public bool ValidateName(List <string> errors)
        {
            errors.Clear();

            if (string.IsNullOrEmpty(ServiceName))
            {
                errors.Add("Name cannot be empty.");
                return(false);
            }

            if (!ServiceName.EndsWith("Service"))
            {
                errors.Add("Name must end with 'Service' suffix.");
            }

            if (!CSharpCodeProvider.CreateProvider("C#").IsValidIdentifier(ServiceName))
            {
                errors.Add("Name must not contain illegal characters.");
            }

            return(errors.Count == 0);
        }
예제 #37
0
 public Task StartListener(ServiceName service, Func <byte[], byte[]> onRead, Action <NetworkStream, byte[]> onWrite, Action <ServiceEventData> onException)
 {
     return(Task.Run(() =>
     {
         _cancellation.ThreadActivity(service,
                                      () =>
         {
             if (_server.Pending())
             {
                 HandleRequestAsync(onRead, onWrite);
             }
             else
             {
                 Thread.Sleep(50);
             }
         },
                                      data => onException(data),
                                      () => _server.Stop()
                                      );
     },
                     _cancellation.Token));
 }
예제 #38
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ServiceName.Length != 0)
            {
                hash ^= ServiceName.GetHashCode();
            }
            if (MethodName.Length != 0)
            {
                hash ^= MethodName.GetHashCode();
            }
            if (RequestId != 0)
            {
                hash ^= RequestId.GetHashCode();
            }
            if (Payload.Length != 0)
            {
                hash ^= Payload.GetHashCode();
            }
            return(hash);
        }
 private Injection[] DetectInjections(ServiceName name)
 {
     var memberSetters = provider.GetMembers(name.Type);
     var result = new Injection[memberSetters.Length];
     for (var i = 0; i < result.Length; i++)
     {
         var member = memberSetters[i].member;
         try
         {
             result[i].value = container.Resolve(member.MemberType(),
                 name.Contracts.Concat(InternalHelpers.ParseContracts(member)));
             result[i].value.CheckSingleInstance();
         }
         catch (SimpleContainerException e)
         {
             const string messageFormat = "can't resolve member [{0}.{1}]";
             throw new SimpleContainerException(string.Format(messageFormat, member.DeclaringType.FormatName(), member.Name), e);
         }
         result[i].setter = memberSetters[i].setter;
     }
     return result;
 }
예제 #40
0
        public TreeConnectAndXRequest(byte[] buffer, int offset, bool isUnicode) : base(buffer, offset)
        {
            int parametersOffset = 4;

            Flags = (TreeConnectFlags)LittleEndianReader.ReadUInt16(SMBParameters, ref parametersOffset);
            ushort passwordLength = LittleEndianReader.ReadUInt16(SMBParameters, ref parametersOffset);

            int dataOffset = 0;

            Password = ByteReader.ReadBytes(SMBData, ref dataOffset, passwordLength);
            if (isUnicode)
            {
                // wordCount is 1 byte
                int padding = (1 + passwordLength) % 2;
                dataOffset += padding;
            }
            Path = SMB1Helper.ReadSMBString(SMBData, ref dataOffset, isUnicode);
            // Should be read as OEM string but it doesn't really matter
            string serviceString = ByteReader.ReadNullTerminatedAnsiString(SMBData, ref dataOffset);

            Service = ServiceNameHelper.GetServiceName(serviceString);
        }
예제 #41
0
        public async Task OnGetAsync(int?pageIndex)
        {
            var queryable = _context.GranteeService.AsQueryable();

            if (!string.IsNullOrEmpty(ServiceName))
            {
                queryable = queryable.Where(s => s.ServiceName.ToLower().Contains(ServiceName.ToLower()));
            }
            if (!string.IsNullOrEmpty(GranteeName))
            {
                queryable = queryable.Where(s => s.Grantee.Name.ToLower().Contains(GranteeName.ToLower()));
            }
            if (!string.IsNullOrEmpty(GranteeNationalId))
            {
                queryable = queryable.Where(s => s.Grantee.NationalId.Contains(GranteeNationalId));
            }


            GranteeService = await PaginatedList <GranteeService> .CreateAsync(queryable
                                                                               .Include(g => g.Grantee)
                                                                               .Include(g => g.Organization).AsNoTracking(), pageIndex ?? 1, _PageSize);
        }
        private (bool, AccessControl) GetFirstMatchingAccessControl(ServiceName serviceName,
                                                                    ServiceUri serviceUri,
                                                                    Identity identity)
        {
            var controls = GetAccessControls(serviceName);
            var matching = controls
                           .Where(control => control.Path == null || serviceUri.Value.StartsWith(control.Path))
                           .FirstOrDefault(control =>
            {
                var block = control.ControlType == ControlType.Allow
                        ? identity.AccessTier.IsHigherTierThan(control.MinimumAccessTier ?? AccessTier.Failure)
                        : identity.AccessTier.IsLowerTierThan(control.MinimumAccessTier ?? AccessTier.NoAccess);
                if (control.Exempt.Contains(identity.Username))
                {
                    block = !block;
                }

                return(block);
            });

            return(controls.Length > 0, matching);
        }
예제 #43
0
        internal static int ConvertToPortNum(RubyContext /*!*/ context, object port)
        {
            // conversion protocol: if it's a Fixnum, return it
            // otherwise, convert to string & then convert the result to a Fixnum
            if (port is int)
            {
                return((int)port);
            }

            MutableString serviceName = Protocols.CastToString(context, port);
            ServiceName   service     = SearchForService(serviceName);

            if (service != null)
            {
                return(service.Port);
            }

            int result;

            Protocols.IntegerAsFixnum(Protocols.ConvertToInteger(context, serviceName), out result);
            return(result);
        }
예제 #44
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ServiceName.Length != 0)
            {
                hash ^= ServiceName.GetHashCode();
            }
            if (Name.Length != 0)
            {
                hash ^= Name.GetHashCode();
            }
            if (payload_ != null)
            {
                hash ^= Payload.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
예제 #45
0
        public void GetService()
        {
            Mock <ServiceMonitoringService.ServiceMonitoringServiceClient> mockGrpcClient = new Mock <ServiceMonitoringService.ServiceMonitoringServiceClient>(MockBehavior.Strict);
            GetServiceRequest expectedRequest = new GetServiceRequest
            {
                ServiceName = new ServiceName("[PROJECT]", "[SERVICE]"),
            };
            Service expectedResponse = new Service
            {
                ServiceName = new ServiceName("[PROJECT]", "[SERVICE]"),
                DisplayName = "displayName1615086568",
            };

            mockGrpcClient.Setup(x => x.GetService(expectedRequest, It.IsAny <CallOptions>()))
            .Returns(expectedResponse);
            ServiceMonitoringServiceClient client = new ServiceMonitoringServiceClientImpl(mockGrpcClient.Object, null);
            ServiceName name     = new ServiceName("[PROJECT]", "[SERVICE]");
            Service     response = client.GetService(name);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessageKeyboardInteractive"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 public RequestMessageKeyboardInteractive(ServiceName serviceName, string username)
     : base(serviceName, username)
 {
     this.Language = string.Empty;
     this.SubMethods = string.Empty;
 }
예제 #47
0
        public static bool TryCreate(ContainerService.Builder builder)
        {
            if (!builder.Type.IsDelegate())
                return false;
            if (!builder.Type.IsNestedPublic)
                return false;
            var invokeMethod = builder.Type.GetMethod("Invoke");
            if (invokeMethod.ReturnType != builder.Type.DeclaringType)
                return false;
            var constructor = builder.Type.DeclaringType.GetConstructor();
            if (!constructor.isOk)
            {
                builder.SetError(constructor.errorMessage);
                return true;
            }
            var delegateParameters = invokeMethod.GetParameters();
            var delegateParameterNameToIndexMap = new Dictionary<string, int>();
            for (var i = 0; i < delegateParameters.Length; i++)
                delegateParameterNameToIndexMap[delegateParameters[i].Name] = i;

            var dynamicMethodParameterTypes = new Type[delegateParameters.Length + 1];
            dynamicMethodParameterTypes[0] = typeof (object[]);
            for (var i = 1; i < dynamicMethodParameterTypes.Length; i++)
                dynamicMethodParameterTypes[i] = delegateParameters[i - 1].ParameterType;

            var dynamicMethod = new DynamicMethod("", invokeMethod.ReturnType,
                dynamicMethodParameterTypes, typeof (ReflectionHelpers), true);

            var il = dynamicMethod.GetILGenerator();
            var ctorParameters = constructor.value.GetParameters();
            var notBoundCtorParameters = ctorParameters
                .Where(x => x.ParameterType.IsSimpleType() && !delegateParameterNameToIndexMap.ContainsKey(x.Name))
                .Select(x => x.Name)
                .ToArray();
            if (notBoundCtorParameters.Length > 0)
            {
                builder.SetError(string.Format("ctor has not bound parameters [{0}]", notBoundCtorParameters.JoinStrings(",")));
                return true;
            }
            var serviceTypeToIndex = new Dictionary<Type, int>();
            var services = new List<object>();
            foreach (var p in ctorParameters)
            {
                int delegateParameterIndex;
                if (delegateParameterNameToIndexMap.TryGetValue(p.Name, out delegateParameterIndex))
                {
                    var delegateParameterType = delegateParameters[delegateParameterIndex].ParameterType;
                    if (!p.ParameterType.IsAssignableFrom(delegateParameterType))
                    {
                        const string messageFormat = "type mismatch for [{0}], delegate type [{1}], ctor type [{2}]";
                        builder.SetError(string.Format(messageFormat,
                            p.Name, delegateParameterType.FormatName(), p.ParameterType.FormatName()));
                        return true;
                    }
                    il.EmitLdArg(delegateParameterIndex + 1);
                    delegateParameterNameToIndexMap.Remove(p.Name);
                }
                else
                {
                    int serviceIndex;
                    if (!serviceTypeToIndex.TryGetValue(p.ParameterType, out serviceIndex))
                    {
                        object value;
                        if (p.ParameterType == typeof (ServiceName))
                            value = null;
                        else
                        {
                            var dependency = builder.Context.Container.InstantiateDependency(p, builder).CastTo(p.ParameterType);
                            builder.AddDependency(dependency, false);
                            if (dependency.ContainerService != null)
                                builder.UnionUsedContracts(dependency.ContainerService);
                            if (builder.Status != ServiceStatus.Ok)
                                return true;
                            value = dependency.Value;
                        }
                        serviceIndex = serviceTypeToIndex.Count;
                        serviceTypeToIndex.Add(p.ParameterType, serviceIndex);
                        services.Add(value);
                    }
                    il.Emit(OpCodes.Ldarg_0);
                    il.EmitLdInt32(serviceIndex);
                    il.Emit(OpCodes.Ldelem_Ref);
                    il.Emit(p.ParameterType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, p.ParameterType);
                }
            }
            if (delegateParameterNameToIndexMap.Count > 0)
            {
                builder.SetError(string.Format("delegate has not used parameters [{0}]",
                    delegateParameterNameToIndexMap.Keys.JoinStrings(",")));
                return true;
            }
            builder.EndResolveDependencies();
            int serviceNameIndex;
            if (serviceTypeToIndex.TryGetValue(typeof (ServiceName), out serviceNameIndex))
                services[serviceNameIndex] = new ServiceName(builder.Type.DeclaringType, builder.FinalUsedContracts);
            il.Emit(OpCodes.Newobj, constructor.value);
            il.Emit(OpCodes.Ret);
            var context = serviceTypeToIndex.Count == 0 ? null : services.ToArray();
            builder.AddInstance(dynamicMethod.CreateDelegate(builder.Type, context), true);
            return true;
        }
 public bool HasCycle(ServiceName name)
 {
     var context = this;
     while (context != null)
     {
         if (context.Container == Container && context.ConstructingServices.Contains(name))
             return true;
         context = context.prev;
     }
     return false;
 }
예제 #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessagePassword"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="password">Authentication password.</param>
 public RequestMessagePassword(ServiceName serviceName, string username, byte[] password)
     : base(serviceName, username)
 {
     this.Password = password;
 }
예제 #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessagePublicKey"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="keyAlgorithmName">Name of private key algorithm.</param>
 /// <param name="keyData">Private key data.</param>
 public RequestMessagePublicKey(ServiceName serviceName, string username, string keyAlgorithmName, byte[] keyData)
     : base(serviceName, username, "publickey")
 {
     PublicKeyAlgorithmName = SshData.Ascii.GetBytes(keyAlgorithmName);
     PublicKeyData = keyData;
 }
 public TestService(ServiceName name, ServiceHost host) : base(name, host) { }
예제 #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessagePassword"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 public RequestMessageNone(ServiceName serviceName, string username)
     : base(serviceName, username)
 {
 }
예제 #53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessagePassword"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="password">Authentication password.</param>
 /// <param name="newPassword">New authentication password.</param>
 public RequestMessagePassword(ServiceName serviceName, string username, byte[] password, byte[] newPassword)
     : this(serviceName, username, password)
 {
     this.NewPassword = newPassword;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessage"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 public RequestMessage(ServiceName serviceName, string username)
 {
     this.ServiceName = serviceName;
     this.Username = username;
 }
예제 #55
0
 public static ServiceAcceptMessageBuilder Create(ServiceName serviceName)
 {
     return new ServiceAcceptMessageBuilder(serviceName);
 }
예제 #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessagePublicKey"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="keyAlgorithmName">Name of private key algorithm.</param>
 /// <param name="keyData">Private key data.</param>
 /// <param name="signature">Private key signature.</param>
 public RequestMessagePublicKey(ServiceName serviceName, string username, string keyAlgorithmName, byte[] keyData, byte[] signature)
     : this(serviceName, username, keyAlgorithmName, keyData)
 {
     Signature = signature;
 }
 public EchoService(ServiceName name, ServiceHost host) : base(name, host) { }
예제 #58
0
 private ServiceAcceptMessageBuilder(ServiceName serviceName)
 {
     _serviceName = serviceName;
 }
예제 #59
0
파일: Tuxedo.cs 프로젝트: sunpander/VSDT
 public static DataSet CallService(ServiceName str)
 {
     DataSet ds = new DataSet();
     return ds;
 }
예제 #60
-1
 public void RequestMessageConstructorTest()
 {
     ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     RequestMessage target = new RequestMessage(serviceName, username);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }