Пример #1
0
            public void when_endpointname_is_provided_via_configuration_it_should_have_second_priority()
            {
                Configure.With().DefineEndpointName("EndpointNameFromConfiguration");
                Sut = new EndpointType(hostArguments, typeof (TestEndpointType));

                Assert.AreEqual("EndpointNameFromConfiguration", Sut.EndpointName);
            }
Пример #2
0
        public static string GetContentType(EndpointType endpointType)
        {
            switch (endpointType)
            {
                case EndpointType.Soap11:
                case EndpointType.Soap12:
                case EndpointType.Xml:
                    return Xml;

                case EndpointType.Json:
                    return Json;

                case EndpointType.Jsv:
                    return JsvText;

                case EndpointType.Csv:
                    return Csv;

                case EndpointType.ProtoBuf:
                    return ProtoBuf;

                case EndpointType.MsgPack:
                    return MsgPack;

                default:
                    return null;
            }
        }
 public EndpointInformation(int endpoint, EndpointDirection direction, EndpointType type, int maxPacketSize)
 {
     Endpoint = endpoint;
       Direction = direction;
       Type = type;
       MaximumPacketSize = maxPacketSize;
 }
Пример #4
0
            public void when_endpointname_attribute_exists_it_should_have_first_priority()
            {
                Configure.With().DefineEndpointName("EndpointNameFromConfiguration");
                Sut = new EndpointType(hostArguments, typeof (TestEndpointTypeWithEndpointNameAttribute));

                Assert.AreEqual("EndpointNameFromAttribute", Sut.EndpointName);
            }
Пример #5
0
 public ServiceProviderEndpoint(EndpointType type, string localPath, string redirectUrl = null, BindingType bindingType = BindingType.NotSet) : this()
 {
     Type = type;
     LocalPath = localPath;
     RedirectUrl = redirectUrl;
     Binding = bindingType;
 }
        public IEnumerable<Endpoint> GetMetadataByType(EndpointType endpointType)
        {
            using (var client = new HttpClient()) {
                var url = string.Concat(BaseUrl, "metadata/bytype/", endpointType.ToString());

                var responseMessage = client.GetAsync(url).Result;
                var body = responseMessage.Content.ReadAsStringAsync().Result;

                return JsonConvert.DeserializeObject<List<Endpoint>>(body);
            }
        }
Пример #7
0
            public void when_endpointName_is_provided_via_configuration_it_should_have_second_priority()
            {
                var configuration = new BusConfiguration();

                configuration.EndpointName("EndpointNameFromConfiguration");

                Bus.Create(configuration);

                EndpointType = new EndpointType(hostArguments, typeof (TestEndpointType));

                Assert.AreEqual("EndpointNameFromConfiguration", EndpointType.EndpointName);
            }
Пример #8
0
 public IEndpoint CreateEndpoint(EndpointType type)
 {
     switch (type)
     {
         case EndpointType.InProc:
             throw new NotImplementedException();
         case EndpointType.Ipc:
             return new NamedPipeEndpoint(this.frameReaderFactory, this.frameWriterFactory);
         case EndpointType.Tcp:
             return new TcpEndpoint(this.frameReaderFactory, this.frameWriterFactory);
         default:
             throw new NotSupportedException(ExceptionMessages.EndpointUnknownType);
     }
 }
Пример #9
0
 internal UsbEndpointBase(UsbDevice usbDevice, byte epNum, EndpointType endpointType)
 {
     mUsbDevice = usbDevice;
     mUsbApi = mUsbDevice.mUsbApi;
     mUsbHandle = mUsbDevice.Handle;
     mEpNum = epNum;
     mEndpointType = endpointType;
     if ((mEpNum & 0x80) > 0)
     {
         mPipeTransferSubmit = ReadPipe;
     }
     else
         mPipeTransferSubmit = WritePipe;
 }
 public MetadataConfig GetEndpointConfig(EndpointType endpointType)
 {
     switch (endpointType)
     {
         case EndpointType.Soap11:
             return this.Soap11;
         case EndpointType.Soap12:
             return this.Soap12;
         case EndpointType.Xml:
             return this.Xml;
         case EndpointType.Json:
             return this.Json;
         case EndpointType.Jsv:
             return this.Jsv;
     }
     return null;
 }
Пример #11
0
    internal HttpRequestMessage CreateHttpRequestMessage(object content, EndpointType endPointType, Encoding encoding)
    {
        var data = CreateContent(content, encoding);

        var endpoint = GetEndpoint(endPointType);

        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, endpoint)
        {
            Content = data
        };

        if (credentials != null)
        {
            string basicAuthHeader = credentials.CreateToken();

            httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue(credentials.Schema, basicAuthHeader);
        }

        return(httpRequestMessage);
    }
        public MetadataConfig GetEndpointConfig(EndpointType endpointType)
        {
            switch (endpointType)
            {
            case EndpointType.Soap11:
                return(this.Soap11);

            case EndpointType.Soap12:
                return(this.Soap12);

            case EndpointType.Xml:
                return(this.Xml);

            case EndpointType.Json:
                return(this.Json);

            case EndpointType.Jsv:
                return(this.Jsv);
            }
            return(null);
        }
Пример #13
0
 /// <summary>
 /// Closes a discrete interval endpoint.
 /// </summary>
 /// <remarks>
 /// Discrete intervals are rarely displayed using open endpoints. This method updates an open endpoint with
 /// its equivalent closed representation (e.g. ]0,5] => [1,5] or [0,5[ => [0,4]).
 /// </remarks>
 /// <param name="value">The endpoint value.</param>
 /// <param name="type">The endpoint type.</param>
 /// <param name="adjustment">The adjustment to be made on the endpoint (i.e. 1 or -1).</param>
 private static void CloseEndpoint(ref T?value, ref EndpointType type, short adjustment)
 {
     if (type == EndpointType.Open)
     {
         if (value is short?)
         {
             // Using the simpler conversion syntax causes unboxing errors with shorts.
             value = (T?)Convert.ChangeType((short)((short)(object)value.Value + adjustment), typeof(object));
             type  = EndpointType.Closed;
         }
         else if (value is int?)
         {
             value = (T?)(object)((int)(object)value.Value + adjustment);
             type  = EndpointType.Closed;
         }
         else if (value is long?)
         {
             value = (T?)(object)((long)(object)value.Value + adjustment);
             type  = EndpointType.Closed;
         }
     }
 }
Пример #14
0
        // Creates an IdP SSO descriptor
        private static IDPSSODescriptor CreateIDPSSODescriptor()
        {
            IDPSSODescriptor idpSSODescriptor = new IDPSSODescriptor();
            idpSSODescriptor.WantAuthnRequestsSigned = true;
            idpSSODescriptor.ProtocolSupportEnumeration = SAML.NamespaceURIs.Protocol;

            X509Certificate2 x509Certificate = new X509Certificate2(idpCertificateFileName);
            idpSSODescriptor.KeyDescriptors.Add(CreateKeyDescriptor(x509Certificate));

            IndexedEndpointType artifactResolutionService = new IndexedEndpointType(1, true);
            artifactResolutionService.Binding = SAMLIdentifiers.BindingURIs.SOAP;
            artifactResolutionService.Location = "https://www.idp.com/ArtifactResolutionService";

            idpSSODescriptor.ArtifactResolutionServices.Add(artifactResolutionService);

            idpSSODescriptor.NameIDFormats.Add(SAMLIdentifiers.NameIdentifierFormats.Transient);

            EndpointType singleSignOnService = new EndpointType(SAMLIdentifiers.BindingURIs.HTTPRedirect, "https://www.idp.com/SSOService", null);
            idpSSODescriptor.SingleSignOnServices.Add(singleSignOnService);

            return idpSSODescriptor;
        }
Пример #15
0
		public List<Network> Last15Results(EndpointType type)
		{
			IEnumerable<Network> networks = (from net in tableNetwork
									where net.EndpointType.Equals(type.ToString())
									orderby net.Id descending
									select net).Take(16);

			List<Network> lists = new List<Network>(networks);
			if (lists.Count != 0)
			{
				lists.RemoveAt(0);
			}

			foreach (Network net in lists)
			{
				net.PingStringToArrays();
				net.GeneratingPingTcpStats();
				net.GeneratingPingUdpStats();
			}

			return lists;
		}
Пример #16
0
        public RavenActionAttribute(
            string path,
            string method,
            AuthorizationStatus requireAuth,
            EndpointType endpointType,
            bool isDebugInformationEndpoint = false,
            bool isPosixSpecificEndpoint    = false,
            CorsMode corsMode = CorsMode.None)
        {
            if (requireAuth != AuthorizationStatus.ValidUser)
            {
                throw new InvalidOperationException($"Please use the other constructor without endpoint type parameter. Route: '{method} {path}'");
            }

            Path         = path;
            Method       = method;
            EndpointType = endpointType;
            IsDebugInformationEndpoint = isDebugInformationEndpoint;
            RequiredAuthorization      = requireAuth;
            IsPosixSpecificEndpoint    = isPosixSpecificEndpoint;
            CorsMode = corsMode;
        }
Пример #17
0
        public List <ClimaCellForecast> getForecast(string cityName, EndpointType endpoint)
        {
            List <ClimaCellForecast> forecastList = new List <ClimaCellForecast>();

            AccuWeatherController accuweatherController = new AccuWeatherController();

            List <float> coordinates = accuweatherController.getCoordinates(cityName);

            restClient.endpoint = climaCellEndpoint.getByCityNameEndpointForecast(coordinates[0], coordinates[1], EndpointType.FORECAST);
            string response = restClient.makeRequest();

            JSONParser <List <ClimaCellForecastModel> > jsonParser = new JSONParser <List <ClimaCellForecastModel> >();

            var deserialisedAccuWeatherModel = jsonParser.parseJSON(response, Parser.Version.NETCore2);

            foreach (ClimaCellForecastModel model in deserialisedAccuWeatherModel)
            {
                forecastList.Add(new ClimaCellForecast(model.temp[0].min.value, model.temp[1].max.value));
            }

            return(forecastList);
        }
        public List <WeatherBitForecast> getForecastList(string city, EndpointType endpoint)
        {
            List <WeatherBitForecast> forecastList = new List <WeatherBitForecast>();

            restClient.endpoint = weatherBitEndpoint.getByCityNameEndpoint(city, endpoint);
            string response = restClient.makeRequest();

            JSONParser <WeatherBitForecastModel> jsonParser = new JSONParser <WeatherBitForecastModel>();

            WeatherBitForecastModel deserialisedWeatherBitMapModel = new WeatherBitForecastModel();

            deserialisedWeatherBitMapModel = jsonParser.parseJSON(response, Parser.Version.NETCore2);
            //Console.WriteLine(deserialisedWeatherBitMapModel);
            foreach (BitForecastObj forecastMain in deserialisedWeatherBitMapModel.data)
            {
                //DateTime dt = DateTimeOffset.FromUnixTimeSeconds(forecastMain.datetime).UtcDateTime;
                DateTime dt = DateTime.Parse(forecastMain.datetime);
                //Console.WriteLine(dt);
                forecastList.Add(new WeatherBitForecast(dt, forecastMain.min_temp, forecastMain.max_temp));
            }
            return(forecastList);
        }
Пример #19
0
        public List <DarkSkyForecast> getForecast(string cityName, EndpointType endpoint)
        {
            List <DarkSkyForecast> forecastList = new List <DarkSkyForecast>();

            AccuWeatherController accuweatherController = new AccuWeatherController();

            List <float> coordinates = accuweatherController.getCoordinates(cityName);

            restClient.endpoint = darkSkyEndpoint.getByCityNameEndpointForecast(coordinates[0], coordinates[1], EndpointType.FORECAST);
            string response = restClient.makeRequest();

            JSONParser <DarkSkyForecastModel> jsonParser = new JSONParser <DarkSkyForecastModel>();

            var deserialisedAccuWeatherModel = jsonParser.parseJSON(response, Parser.Version.NETCore2);

            foreach (DailyForecastDaily model in deserialisedAccuWeatherModel.daily.data)
            {
                forecastList.Add(new DarkSkyForecast(model.temperatureHigh, model.temperatureLow));
            }

            return(forecastList);
        }
Пример #20
0
        public static string GetContentType(EndpointType endpointType)
        {
            switch (endpointType)
            {
            case EndpointType.Soap11:
            case EndpointType.Soap12:
            case EndpointType.Xml:
                return(Xml);

            case EndpointType.Json:
                return(Json);

            case EndpointType.Jsv:
                return(JsvText);

            case EndpointType.ProtoBuf:
                return(ProtoBuf);

            default:
                throw new NotSupportedException(endpointType.ToString());
            }
        }
Пример #21
0
        public static string GetContentType(EndpointType endpointType)
        {
            switch (endpointType)
            {
            case EndpointType.Soap11:
            case EndpointType.Soap12:
            case EndpointType.Xml:
                return(Xml);

            case EndpointType.Json:
                return(Json);

            case EndpointType.Jsv:
                return(JsvText);

            case EndpointType.ProtoBuf:
                return(ProtoBuf);

            default:
                return(null);
            }
        }
Пример #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Endpoint"/> class.
 /// </summary>
 /// <param name="tenantId">
 /// The tenantId that should be used for requests by this endpoint.
 /// </param>
 /// <param name="tenantFriendlyName">The friendly name for this endpoint.</param>
 /// <param name="endpointType">
 /// The type of endpoint that this info object represents.
 /// </param>
 /// <param name="clientId">
 /// The ClientId that is used for authentication with the Store API.
 /// The Documentation\SETUP.md file within <c>http://aka.ms/StoreBroker</c>
 /// explains how to create a client and get its ClientId and Secret.
 /// </param>
 /// <param name="clientSecretEncrypted">
 /// The encrypted Client Secret used for API access.
 /// The Documentation\SETUP.md file within <c>http://aka.ms/StoreBroker</c>
 /// explains how to create a client and get its ClientId and Secret, and the
 /// RESTPROXY.md documentation covers how to encrypt the client secret.
 /// </param>
 /// <param name="clientSecretCertificateThumbprint">
 /// The thumbprint of the certificate that can be used to decrypt
 /// <paramref name="clientSecretEncrypted"/>. The Documentation\RESTPROXY.md file
 /// within <c>http://aka.ms/StoreBroker</c> explains how to get the certificate thumbprint.
 /// </param>
 /// <param name="readOnlySecurityGroupAlias">
 /// The security group that users must be in to perform GET API requests from this
 /// endpoint.
 /// </param>
 /// <param name="readWriteSecurityGroupAlias">
 /// The security group that users must be in to perform GET, POST, PUT, DELETE requests
 /// from this endpoint.
 /// </param>
 public Endpoint(
     string tenantId,
     string tenantFriendlyName,
     EndpointType endpointType,
     string clientId,
     string clientSecretEncrypted,
     string clientSecretCertificateThumbprint,
     string readOnlySecurityGroupAlias,
     string readWriteSecurityGroupAlias)
 {
     this.TenantId           = tenantId;
     this.TenantFriendlyName = tenantFriendlyName;
     this.Type     = endpointType;
     this.ClientId = clientId;
     this.ClientSecretEncrypted            = clientSecretEncrypted;
     this.ReadOnlySecurityGroupAlias       = readOnlySecurityGroupAlias;
     this.ReadWriteSecurityGroupAlias      = readWriteSecurityGroupAlias;
     this.ClientSecretCertificateThumbrint = clientSecretCertificateThumbprint;
     this.AccessToken = string.Empty;
     this.ValidThru   = DateTime.Now;
     this.AsyncLock   = new AsyncLock();
 }
Пример #23
0
        public static string GetContentType(EndpointType endpointType)
        {
            switch (endpointType)
            {
                case EndpointType.Soap11:
                case EndpointType.Soap12:
                case EndpointType.Xml:
                    return Xml;

                case EndpointType.Json:
                    return Json;

                case EndpointType.Jsv:
                    return JsvText;

                case EndpointType.ProtoBuf:
                    return ProtoBuf;

                default:
                    throw new NotSupportedException(endpointType.ToString());
            }
        }
Пример #24
0
        /// <summary>
        /// Retrieves the query saved into specified HTTP session.
        /// </summary>
        /// <param name="session">
        /// the HTTP session
        /// </param>
        /// <returns>
        /// the query instance, which will never be <c>null</c> if the method succeeds
        /// </returns>
        public static SessionQuery GetSessionQuery(HttpSessionStateBase session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            SessionQuery query = (SessionQuery)session[Constants.HTTPSessionQueryAttr];

            //getting EndpointType
            NSIClientSettings settings     = NSIClientSettings.Instance;
            EndpointType      endPointType = (EndpointType)Enum.Parse(typeof(EndpointType), settings.EndPointType);

            query.EndPointType = Enum.IsDefined(typeof(EndpointType), endPointType) ? endPointType : EndpointType.V20;

            ApplyCultureToThread(query);

            // if (query == null)
            // {
            // throw new ArgumentException("No query instance found into HTTP session");
            // }
            return(query);
        }
Пример #25
0
        public List <Network> Last15Results(EndpointType type)
        {
            IEnumerable <Network> networks = (from net in tableNetwork
                                              where net.EndpointType.Equals(type.ToString())
                                              orderby net.Id descending
                                              select net).Take(16);

            List <Network> lists = new List <Network>(networks);

            if (lists.Count != 0)
            {
                lists.RemoveAt(0);
            }

            foreach (Network net in lists)
            {
                net.PingStringToArrays();
                net.GeneratingPingTcpStats();
                net.GeneratingPingUdpStats();
            }

            return(lists);
        }
Пример #26
0
        private string BuildEndpointForDoc(string doc, string extension = "", EndpointType type = EndpointType.UID, bool withAdapter = false)
        {
            List <string> segments = new List <string>();

            segments.Add(client.RestPath);
            if (!string.IsNullOrEmpty(Repository))
            {
                segments.Add("repo");
                segments.Add(Repository);
            }
            segments.Add(type == EndpointType.UID ? "id" : "path");
            segments.Add(doc);
            if (withAdapter && Adapter != null)
            {
                segments.Add(Adapter.GetEndpointSuffix());
            }
            if (!string.IsNullOrEmpty(extension))
            {
                segments.Add(extension);
            }

            return(UrlCombiner.Combine(segments.ToArray()));
        }
Пример #27
0
        /// <summary>
        /// Wrapper used for the purposes of logging user requests to Application Insights
        /// in case we need to review user actions at a later time.
        /// </summary>
        /// <param name="userName">The user that requested the action</param>
        /// <param name="pathAndQuery">
        /// The UriAbsolutePath and Query properties.  Simply, this is the entire Uri except for
        /// the protocol and domain information.
        /// </param>
        /// <param name="method">The <see cref="HttpMethod"/> of the REST API.</param>
        /// <param name="tenantId">The TenantId of the account that this request was for.</param>
        /// <param name="tenantName">The friendly name of <paramref name="tenantId"/>.</param>
        /// <param name="clientId">The id of the <see cref="Endpoint"/> that owned the request.</param>
        /// <param name="endpointType">The type of endpoint that should be used for the request.</param>
        /// <param name="statusCode">The <see cref="HttpStatusCode"/> for the result of the request.</param>
        /// <param name="correlationId">
        /// An ID that a client (or the API) may have set in the header to track a string of related requests.
        /// </param>
        /// <param name="requestId">The ID given to the request by the API to enable post-mortem analysis.</param>
        /// <param name="clientRequestId">
        /// An ID that a client may have set in the header to track an individual request.
        /// </param>
        /// <param name="duration">The total number of seconds that the request took to complete.</param>
        private static void LogTelemetryEvent(
            string userName,
            string pathAndQuery,
            HttpMethod method,
            string tenantId,
            string tenantName,
            string clientId,
            EndpointType endpointType,
            HttpStatusCode statusCode,
            string correlationId,
            string requestId,
            string clientRequestId,
            double duration)
        {
            ProxyManager.telemetryClient.Context.Session.Id        = System.Guid.NewGuid().ToString();
            ProxyManager.telemetryClient.Context.Component.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Dictionary <string, string> properties = new Dictionary <string, string>();

            properties.Add("UserName", userName);
            properties.Add("PathAndQuery", pathAndQuery);
            properties.Add("Method", method.ToString());
            properties.Add("StatusCode", statusCode.ToString());
            properties.Add("CorrelationId", correlationId);
            properties.Add("RequestId", requestId);
            properties.Add("ClientRequestId", clientRequestId);
            properties.Add("EndpointType", endpointType.ToString());
            properties.Add("TenantId", tenantId);
            properties.Add("TenantFriendlyName", tenantName);
            properties.Add("ClientId", clientId);

            Dictionary <string, double> metrics = new Dictionary <string, double>();

            metrics.Add("Duration", duration);

            ProxyManager.telemetryClient.TrackEvent("ProxyRequest", properties, metrics);
        }
Пример #28
0
        public BookAndChapterSpec ParseBookAndChapter(string text, EndpointType type, List <ParseError> errors)
        {
            Match match = Regex.Match(text, @"^\s*(\d*\s*\p{L}+)\s*(\d+)*\s*$");

            if (!match.Success)
            {
                errors.Add(new ParseError(text, "Not a book/book+chapter"));
                return(null);
            }
            string   bookSearchText = match.Groups[1].Value;
            BookSpec bookSpec       = ParseBook(bookSearchText, errors);

            if (bookSpec == null)
            {
                return(null);
            }
            if (!match.Groups[2].Success)
            {
                int chapterNumber = 1;
                if (type == EndpointType.End)
                {
                    chapterNumber = bookSpec.ChapterCount;
                }
                return(new BookAndChapterSpec(this, bookSpec.Names[0], chapterNumber));
            }
            else
            {
                string strval        = match.Groups[2].Value;
                int    chapterNumber = int.Parse(strval);
                if (chapterNumber < 1 || chapterNumber > bookSpec.ChapterCount)
                {
                    errors.Add(new ParseError(strval, "Chapter number out of range"));
                    return(null);
                }
                return(new BookAndChapterSpec(this, bookSpec.Names[0], chapterNumber));
            }
        }
Пример #29
0
        public async Task <NameCheckModel> NameCheckAsync(string name, EndpointType endpointType = EndpointType.NotSet, string userIp = null)
        {
            Guard.ArgumentNotNullOrWhiteSpace(name, "name");
            Stopwatch timer = new Stopwatch();

            timer.Start();

            var key    = NameCheckHelper.FormatKey(name);
            var result = Cache.GetItem(key);

            if (result != null)
            {
                return(result);
            }

            result              = new NameCheckModel();
            result.Id           = DescendingSortedGuid.NewSortedGuid();
            result.Key          = key;
            result.DateUtc      = DateTime.UtcNow;
            result.EndpointType = endpointType;
            result.Name         = NameCheckHelper.FormatName(name);
            result.Query        = NameCheckHelper.FormatQuery(name);
            result.UserIp       = userIp;

            var twitterResult = await TwitterApiManager.IsNameAvailable(result.Query);

            var gandiResult = GandiApiManager.CheckDomains(result.Query, new string[] { "com", "net", "org" });

            result.SocialNetworks = new Dictionary <string, bool>();
            result.SocialNetworks.Add("twitter", twitterResult.Content);
            result.Domains = gandiResult;

            timer.Stop();
            result.QueryDurationMs = timer.ElapsedMilliseconds;
            Cache.AddItem(key, result);
            return(result);
        }
Пример #30
0
        /// <summary>
        /// Rotates through all the <see cref="Endpoint"/>s in this collection, round-robin style,
        /// and retrieves the next available one for the specified <paramref name="endpointType"/>.
        /// </summary>
        /// <param name="endpointType">The type of endpoint that should be used for the request.</param>
        /// <returns>
        /// The next <see cref="Endpoint"/> in the collection that matches the specified type.
        /// </returns>
        /// <exception cref="KeyNotFoundException">
        /// No <see cref="Endpoint"/> is defined for the specified <paramref name="endpointType"/>.
        /// </exception>
        public Endpoint GetNextEndpoint(EndpointType endpointType)
        {
            try
            {
                this.semaphore.Wait();

                List <Endpoint> endpoints;
                if (this.EndpointsByType.TryGetValue(endpointType, out endpoints))
                {
                    int      nextIndex = this.NextEndpointIndex[endpointType];
                    Endpoint endpoint  = endpoints[nextIndex];

                    // Careful not to do a post-increment here, as the increment would happen _after_ the assignment.
                    // A pre-increment would work, but I'd argue that expliclty adding 1 here is more clear.
                    this.NextEndpointIndex[endpointType] = nextIndex + 1;
                    if (this.NextEndpointIndex[endpointType] >= endpoints.Count)
                    {
                        this.NextEndpointIndex[endpointType] = 0;
                    }

                    return(endpoint);
                }
                else
                {
                    throw new KeyNotFoundException(string.Format(
                                                       "This Proxy is not configured to handle requests for Tenant [{0} ({1})] with the endpoint type of [{2}].",
                                                       this.TenantId,
                                                       this.TenantFriendlyName,
                                                       endpointType.ToString()));
                }
            }
            finally
            {
                this.semaphore.Release();
            }
        }
        public ClimaRealTimeModel getWeather(string cityName, EndpointType endpointType)
        {
            AccuWeatherLocationModel awlm = awc.getPosition(cityName);

            //Console.WriteLine(awlm.GeoPosition.Latitude);

            //List<AccuWeatherForecast> forecastList = new List<AccuWeatherForecast>();

            restClient.endpoint = climaCellEndpoint.getByCityNameEndpoint(awlm.GeoPosition.Longitude, awlm.GeoPosition.Latitude, endpointType);
            string response = restClient.makeRequest();

            JSONParser <ClimaRealTimeModel> jsonParser = new JSONParser <ClimaRealTimeModel>();


            ClimaRealTimeModel deserialisedClimaModel = new ClimaRealTimeModel();

            deserialisedClimaModel = jsonParser.parseJSON(response, Parser.Version.NETCore2);

            //foreach (DailyForecast dailyForecast in deserialisedAccuWeatherModel.DailyForecasts)
            //{
            //    forecastList.Add(new AccuWeatherForecast(dailyForecast.EpochDate, dailyForecast.Temperature.Minimum.Value, dailyForecast.Temperature.Maximum.Value));
            //}
            return(deserialisedClimaModel);
        }
Пример #32
0
        //
        // Only for use by UdpEndpointI
        //
        internal UdpConnector(Communicator communicator, string transport, EndpointType type, EndPoint addr,
                              IPAddress?sourceAddr, string mcastInterface, int mcastTtl, string connectionId)
        {
            _communicator   = communicator;
            Transport       = transport;
            Type            = type;
            _addr           = addr;
            _sourceAddr     = sourceAddr;
            _mcastInterface = mcastInterface;
            _mcastTtl       = mcastTtl;
            _connectionId   = connectionId;

            var hash = new System.HashCode();

            hash.Add(_addr);
            if (sourceAddr != null)
            {
                hash.Add(_sourceAddr);
            }
            hash.Add(_mcastInterface);
            hash.Add(_mcastTtl);
            hash.Add(_connectionId);
            _hashCode = hash.ToHashCode();
        }
Пример #33
0
 public void TestFixtureSetup()
 {
     Sut = new EndpointType(typeof (TestEndpointType));
 }
Пример #34
0
 public void When_type_does_not_have_empty_public_constructor_it_should_blow_up()
 {
     Sut = new EndpointType(typeof (TypeWithoutEmptyPublicConstructor));
 }
Пример #35
0
            public void when_servicename_is_provided_via_hostargs_it_should_have_first_priority()
            {
                hostArguments = new HostArguments(new string[0])
                    {
                        ServiceName = "ServiceNameFromHostArgs"
                    };
                Sut = new EndpointType(hostArguments, typeof (TestEndpointType));

                Assert.AreEqual("ServiceNameFromHostArgs", Sut.ServiceName);
            }
Пример #36
0
            public void when_serviceName_is_not_provided_via_hostArgs_and_endpoint_has_a_namespace_it_should_use_the_namespace()
            {
                hostArguments = new HostArguments(new string[0]);
                EndpointType = new EndpointType(hostArguments, typeof (TestEndpointType));

                Assert.AreEqual("NServiceBus.Hosting.Tests.EndpointTypeTests", EndpointType.ServiceName);
            }
 internal MonoUsbEndpointWriter(UsbDevice usbDevice, WriteEndpointID writeEndpointID,EndpointType endpointType)
     : base(usbDevice, writeEndpointID, endpointType) { }
Пример #38
0
 internal UsbEndpointBase(UsbDevice usbDevice, byte alternateInterfaceID, byte epNum, EndpointType endpointType)
 {
     mUsbDevice = usbDevice;
     this.alternateInterfaceID = alternateInterfaceID;
     mUsbApi       = mUsbDevice.mUsbApi;
     mUsbHandle    = mUsbDevice.Handle;
     mEpNum        = epNum;
     mEndpointType = endpointType;
     if ((mEpNum & 0x80) > 0)
     {
         mPipeTransferSubmit = ReadPipe;
     }
     else
     {
         mPipeTransferSubmit = WritePipe;
     }
 }
 internal MonoUsbEndpointReader(UsbDevice usbDevice, int readBufferSize, ReadEndpointID readEndpointID, EndpointType endpointType)
     : base(usbDevice, readBufferSize, readEndpointID, endpointType) { }
Пример #40
0
 internal UsbEndpointReader(UsbDevice usbDevice, int readBufferSize, ReadEndpointID readEndpointID, EndpointType endpointType)
     : base(usbDevice, (Byte)readEndpointID, endpointType)
 {
     mReadBufferSize = readBufferSize;
 }
Пример #41
0
            public void when_endpointname_is_provided_via_hostargs_it_should_have_third_priority()
            {
                Sut = new EndpointType(hostArguments, typeof (TestEndpointType));

                Assert.AreEqual("EndpointNameFromHostArgs", Sut.EndpointName);
            }
Пример #42
0
 internal BufSizeWarnInfo GetBufSizeWarn(EndpointType type) => Communicator.GetBufSizeWarn(type);
Пример #43
0
 public void SetRcvBufSizeWarn(EndpointType type, int size) => Communicator.SetRcvBufSizeWarn(type, size);
Пример #44
0
 public IEndpointFactory?GetEndpointFactory(EndpointType type) => Communicator.FindEndpointFactory(type);
Пример #45
0
        internal static unsafe Error TransferAsync(
            DeviceHandle device,
            byte endPoint,
            EndpointType endPointType,
            IntPtr buffer,
            int offset,
            int length,
            int timeout,
            int isoPacketSize,
            out int transferLength)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }

            // Determin the amount of isosynchronous packets
            int numIsoPackets = 0;

            if (isoPacketSize > 0)
            {
                numIsoPackets = length / isoPacketSize;
            }

            var transfer = NativeMethods.AllocTransfer(numIsoPackets);

            ManualResetEventSlim mre = new ManualResetEventSlim(false);

            int transferId = 0;

            lock (TransferLock)
            {
                transferId = transferIndex++;
            }

            Transfers.AddOrUpdate(transferId, mre, (index, data) => throw new NotImplementedException());

            // Fill common properties
            transfer->DevHandle     = device.DangerousGetHandle();
            transfer->Endpoint      = endPoint;
            transfer->Timeout       = (uint)timeout;
            transfer->Type          = (byte)endPointType;
            transfer->Buffer        = (byte *)buffer + offset;
            transfer->Length        = length;
            transfer->NumIsoPackets = numIsoPackets;
            transfer->Flags         = (byte)TransferFlags.None;
            transfer->Callback      = transferDelegatePtr;
            transfer->UserData      = new IntPtr(transferId);

            NativeMethods.SubmitTransfer(transfer).ThrowOnError();

            transferLength = 0;
            mre.Wait();

            transferLength = transfer->ActualLength;

            Error ret = Error.Success;

            switch (transfer->Status)
            {
            case TransferStatus.Completed:
                ret = Error.Success;
                break;

            case TransferStatus.TimedOut:
                ret = Error.Timeout;
                break;

            case TransferStatus.Stall:
                ret = Error.Pipe;
                break;

            case TransferStatus.Overflow:
                ret = Error.Overflow;
                break;

            case TransferStatus.NoDevice:
                ret = Error.NoDevice;
                break;

            case TransferStatus.Error:
            case TransferStatus.Cancelled:
                ret = Error.Io;
                break;

            default:
                ret = Error.Other;
                break;
            }

            NativeMethods.FreeTransfer(transfer);

            return(ret);
        }
Пример #46
0
 public static string GetContentFormat(EndpointType endpointType)
 {
     return(endpointType.ToString().ToLower());
 }
Пример #47
0
        /// <summary>
        /// Tries to get the <see cref="Endpoint"/> that should be used to execute the request
        /// with the specified properties.
        /// </summary>
        /// <param name="tenantId">
        /// [Optional] The tenantId that should be used for the request if the proxy supports
        /// multiple tenants.  Mutually exclusive with <paramref name="tenantName"/> since
        /// <paramref name="tenantName"/> is a "friendly" version of this value.  If neither this
        /// nor <paramref name="tenantName"/> are provided, the default TenantId will be used for
        /// this request.
        /// </param>
        /// <param name="tenantName">
        /// [Optional] The friendly name of the <paramref name="tenantId"/> that should be used for
        /// the request if the proxy supports multiple tenants.  Mutually exclusive with
        /// <paramref name="tenantId"/> since this is a friendly name version of that value.
        /// If neither this nor <paramref name="tenantId"/> are provided, the default TenantId will
        /// be used for this request.
        /// </param>
        /// <param name="endpointType">The type of endpoint that should be used for the request.</param>
        /// <param name="endpoint">
        /// The resolved <see cref="Endpoint"/> that should be used for this request.
        /// </param>
        /// <param name="errorResponse">
        /// This contains the <see cref="HttpResponseMessage"/> that should be returned to the user
        /// with the appropriate explanation if we are unable to determine a valid
        /// <see cref="Endpoint"/> to execute this request on.
        /// </param>
        /// <returns>true if a valid <see cref="Endpoint"/> was found; false otherwise.</returns>
        /// <remarks>
        /// We are intentionally trying to encapsulate the exception handling within here, hence the
        /// "Try" naming scheme that returns a boolean with <paramref name="endpoint"/> and
        /// <paramref name="errorResponse"/> as out parameters.
        /// <para />
        /// When both tenantId and tenantName are specified, it will be considered a failure case.
        /// </remarks>
        private static bool TryGetEndpoint(
            string tenantId,
            string tenantName,
            EndpointType endpointType,
            out Endpoint endpoint,
            out HttpResponseMessage errorResponse)
        {
            endpoint      = null;
            errorResponse = null;
            string errorMessage = string.Empty;
            Dictionary <EndpointType, Endpoint> endpointByType;

            try
            {
                if (string.IsNullOrWhiteSpace(tenantId) && string.IsNullOrWhiteSpace(tenantName))
                {
                    if (string.IsNullOrWhiteSpace(ProxyManager.defaultTenantId))
                    {
                        errorMessage = "No TenantId was specified with this request, and this Proxy is not configured with a default TenantId.";
                        return(false);
                    }
                    else
                    {
                        if (ProxyManager.endpointByTenantId.TryGetValue(ProxyManager.defaultTenantId, out endpointByType))
                        {
                            if (!endpointByType.TryGetValue(endpointType, out endpoint))
                            {
                                errorMessage = string.Format(
                                    "No TenantId was specified with this request, and the default TenantId for this Proxy is not configured to handle requests for the specified endpoint type [{0}].",
                                    endpointType.ToString());
                                return(false);
                            }
                        }
                        else
                        {
                            errorMessage = "No TenantId was specified with this request, and the default TenantId for this Proxy is misconfigured.";
                            return(false);
                        }
                    }
                }
                else if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(tenantName))
                {
                    errorMessage = "Do not specify BOTH TenantId and TenantName.  Only specify one of those values to avoid ambiguity.";
                    return(false);
                }
                else if (!string.IsNullOrWhiteSpace(tenantId))
                {
                    if (ProxyManager.endpointByTenantId.TryGetValue(tenantId.ToLowerInvariant(), out endpointByType))
                    {
                        if (!endpointByType.TryGetValue(endpointType, out endpoint))
                        {
                            errorMessage = string.Format(
                                "This Proxy is not configured to handle requests for TenantId [{0}] with the endpoint type of [{1}].",
                                tenantId,
                                endpointType.ToString());
                            return(false);
                        }
                    }
                    else
                    {
                        errorMessage = string.Format(
                            "This Proxy is not configured to handle requests for the requested TenantId [{0}].",
                            tenantId);
                        return(false);
                    }
                }
                else
                {
                    if (ProxyManager.endpointByTenantName.TryGetValue(tenantName.ToLowerInvariant(), out endpointByType))
                    {
                        if (!endpointByType.TryGetValue(endpointType, out endpoint))
                        {
                            errorMessage = string.Format(
                                "This Proxy is not configured to handle requests for Tenant [{0}] with the endpoint type of [{1}].",
                                tenantName,
                                endpointType.ToString());
                            return(false);
                        }
                    }
                    else
                    {
                        errorMessage = string.Format(
                            "This Proxy is not configured to handle requests for the requested Tenant [{0}].",
                            tenantName);
                        return(false);
                    }
                }

                return(true);
            }
            finally
            {
                if (endpoint == null)
                {
                    const string ErrorMessageFormat = "{{\"code\":\"BadRequest\", \"message\":{0}}}";
                    string       formattedError     = string.Format(ErrorMessageFormat, JsonConvert.ToString(errorMessage));
                    errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent(formattedError, Encoding.UTF8, ProxyManager.JsonMediaType)
                    };
                }
            }
        }
 internal MonoUsbEndpointReader(UsbDevice usbDevice, int readBufferSize, byte alternateInterfaceID, ReadEndpointID readEndpointID, EndpointType endpointType)
     : base(usbDevice, readBufferSize, alternateInterfaceID, readEndpointID, endpointType)
 {
 }
        public void CreateADefinitionAndEnableTheProfile(
            string profileName,
            string domain,
            EndpointType endpointType,
            LoadBalancingMethod testMethod = LoadBalancingMethod.Performance)
        {
            DefinitionEndpointCreateParameters endpointParameter = new DefinitionEndpointCreateParameters();
            endpointParameter.DomainName = domain;
            endpointParameter.Status = EndpointStatus.Enabled;
            endpointParameter.Type = endpointType;

            CreateADefinitionAndEnableTheProfile(profileName, LoadBalancingMethod.Performance, endpointParameter);
        }
Пример #50
0
        /// <summary>
        /// Opens an endpoint for reading
        /// </summary>
        /// <param name="readEndpointID">Endpoint number for read operations.</param>
        /// <param name="readBufferSize">Size of the read buffer allocated for the <see cref="UsbEndpointReader.DataReceived"/> event.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointReader"/> class ready for reading. If the specified endpoint is already been opened, the original <see cref="UsbEndpointReader"/> class is returned.</returns>
        public virtual UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in mActiveEndpoints)
                if (activeEndpoint.EpNum == (byte) readEndpointID)
                    return (UsbEndpointReader) activeEndpoint;

            byte altIntefaceID = mClaimedInterfaces.Count == 0 ? UsbAltInterfaceSettings[0] : UsbAltInterfaceSettings[mClaimedInterfaces[mClaimedInterfaces.Count - 1]];

            UsbEndpointReader epNew = new UsbEndpointReader(this, readBufferSize, altIntefaceID, readEndpointID, endpointType);
            return (UsbEndpointReader) mActiveEndpoints.Add(epNew);
        }
Пример #51
0
 internal UsbEndpointWriter(UsbDevice usbDevice, WriteEndpointID writeEndpointID, EndpointType endpointType)
     : base(usbDevice, (byte)writeEndpointID, endpointType)
 {
 }
Пример #52
0
 internal MonoUsbEndpointWriter(UsbDevice usbDevice, byte alternateInterfaceID, WriteEndpointID writeEndpointID, EndpointType endpointType)
     : base(usbDevice, alternateInterfaceID, writeEndpointID, endpointType)
 {
 }
        public string GetEndpointBaseUri(EndpointType endpoint, string protocol, bool secondary = false)
        {
            string url = string.Empty;
            bool isHttps = (string.Compare(protocol, "https", StringComparison.InvariantCultureIgnoreCase) == 0);
            if (DMLibTestHelper.GetTestAgainst() == TestAgainst.DevFabric)
            {
                int port;
                string host;
                if (endpoint == EndpointType.Blob)
                {
                    port = isHttps ? 10100 : 10000;
                    host = this.Account.BlobEndpoint.Host;
                }
                else if (endpoint == EndpointType.Queue)
                {
                    port = isHttps ? 10101 : 10001;
                    host = this.Account.QueueEndpoint.Host;
                }
                else if (endpoint == EndpointType.Table)
                {
                    port = isHttps ? 10102 : 10002;
                    host = this.Account.TableEndpoint.Host;
                }
                else
                {
                    port = isHttps ? 10104 : 10004;
                    host = this.Account.FileEndpoint.Host;
                }

                url = string.Format(@"{0}://{1}:{2}/{3}", protocol, host, port, this.AccountName);
                if (secondary)
                {
                    Test.Error("DevFabric doesn't have secondary endpoint.");
                }
            }
            else
            {
                Uri endpointUri;
                if (endpoint == EndpointType.Blob)
                {
                    endpointUri = secondary ? this.Account.BlobStorageUri.SecondaryUri : this.Account.BlobStorageUri.PrimaryUri;
                }
                else if (endpoint == EndpointType.Queue)
                {
                    endpointUri = secondary ? this.Account.QueueStorageUri.SecondaryUri : this.Account.QueueStorageUri.PrimaryUri;
                }
                else if (endpoint == EndpointType.Table)
                {
                    endpointUri = secondary ? this.Account.TableStorageUri.SecondaryUri : this.Account.TableStorageUri.PrimaryUri;
                }
                else
                {
                    endpointUri = secondary ? this.Account.FileStorageUri.SecondaryUri : this.Account.FileStorageUri.PrimaryUri;
                }

                url = endpointUri.AbsoluteUri.Replace(endpointUri.Scheme, protocol);
            }

            if (url.EndsWith("/"))
            {
                url = url.Remove(url.Length - 1);
            }

            return url;
        }
        /// <summary>
        /// Opens an endpoint for writing
        /// </summary>
        /// <param name="writeEndpointID">Endpoint number for read operations.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointWriter"/> class ready for writing. If the specified endpoint is already been opened, the original <see cref="UsbEndpointWriter"/> class is returned.</returns>
        public override UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in ActiveEndpoints)
                if (activeEndpoint.EpNum == (byte)writeEndpointID)
                    return (UsbEndpointWriter)activeEndpoint;

            UsbEndpointWriter epNew = new LibUsbEndpointWriter(this, writeEndpointID, endpointType);
            return (UsbEndpointWriter) mActiveEndpoints.Add(epNew);
        }
Пример #55
0
 public void when_no_endpointname_defined_it_should_return_null()
 {
     hostArguments.EndpointName = null;
     Sut = new EndpointType(hostArguments, typeof (TestEndpointType));
     Assert.IsNull(Sut.EndpointName);
 }
Пример #56
0
            public void when_servicename_is_not_provided_via_hostargs_and_endpoint_has_no_namespace_it_should_use_the_assembly_name()
            {
                hostArguments = new HostArguments(new string[0]);
                Sut = new EndpointType(hostArguments, typeof (TestEndpointTypeWithoutANamespace));

                Assert.AreEqual("NServiceBus.Hosting.Tests", Sut.ServiceName);
            }
Пример #57
0
 internal MonoUsbEndpointReader(UsbDevice usbDevice, int readBufferSize, byte alternateInterfaceID, ReadEndpointID readEndpointID, EndpointType endpointType)
     : base(usbDevice, readBufferSize, alternateInterfaceID, readEndpointID, endpointType)
 {
 }
Пример #58
0
        /// <summary>
        /// Opens an endpoint for writing
        /// </summary>
        /// <param name="writeEndpointID">Endpoint number for read operations.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointWriter"/> class ready for writing. If the specified endpoint is already been opened, the original <see cref="UsbEndpointWriter"/> class is returned.</returns>
        public virtual UsbEndpointWriter OpenEndpointWriter(WriteEndpointID writeEndpointID, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in ActiveEndpoints)
                if (activeEndpoint.EpNum == (byte) writeEndpointID)
                    return (UsbEndpointWriter) activeEndpoint;

            byte altIntefaceID = mClaimedInterfaces.Count == 0 ? UsbAltInterfaceSettings[0] : UsbAltInterfaceSettings[mClaimedInterfaces[mClaimedInterfaces.Count - 1]];

            UsbEndpointWriter epNew = new UsbEndpointWriter(this, altIntefaceID, writeEndpointID, endpointType);
            return (UsbEndpointWriter) mActiveEndpoints.Add(epNew);
        }
Пример #59
0
 /// <summary>
 /// This is a short-hand for instantiating a <see cref="SimulatedErrorRequest"/>.
 /// </summary>
 private static SimulatedErrorRequest SER(EndpointType endpointType, SimulatedErrorType simulatedErrorType)
 {
     return(new SimulatedErrorRequest(endpointType, simulatedErrorType));
 }
        /// <summary>
        /// Opens an endpoint for reading
        /// </summary>
        /// <param name="readEndpointID">Endpoint number for read operations.</param>
        /// <param name="readBufferSize">Size of the read buffer allocated for the <see cref="UsbEndpointReader.DataReceived"/> event.</param>
        /// <param name="endpointType">The type of endpoint to open.</param>
        /// <returns>A <see cref="UsbEndpointReader"/> class ready for reading. If the specified endpoint is already been opened, the original <see cref="UsbEndpointReader"/> class is returned.</returns>
        public override UsbEndpointReader OpenEndpointReader(ReadEndpointID readEndpointID, int readBufferSize, EndpointType endpointType)
        {
            foreach (UsbEndpointBase activeEndpoint in mActiveEndpoints)
                if (activeEndpoint.EpNum == (byte)readEndpointID) 
                    return (UsbEndpointReader)activeEndpoint;

            UsbEndpointReader epNew = new LibUsbEndpointReader(this, readBufferSize, readEndpointID, endpointType);
            return (UsbEndpointReader) ActiveEndpoints.Add(epNew);
        }