protected SyndicationLink GetPreviousPageLink(string collection, int pageNumber)
        {
            Uri feedUri;

            if (pageNumber == 0)
            {
                feedUri = allEntriesTemplate.BindByPosition(this.webOperationContext.BaseUri, collection);
            }
            else
            {
                feedUri = pagedEntriesTemplate.BindByPosition(this.webOperationContext.BaseUri, collection, pageNumber.ToString(CultureInfo.InvariantCulture));
            }
            return(new SyndicationLink(feedUri, "previous", "Previous entries", ContentTypes.Atom, 0));
        }
示例#2
0
        /// <summary>
        /// Gets Safe Uri
        /// </summary>
        /// <param name="baseUri">Base Uri</param>
        /// <param name="uriTemplate">Uri Format template</param>
        /// <param name="args">Arguments array</param>
        /// <returns>Safe Uri or throws an Argument Exception</returns>
        public static Uri GetSafeUriFromTemplate(Uri baseUri, UriTemplate uriTemplate, params string[] args)
        {
            if (args != null)
            {
                for (var i = 0; i < args.Length; i++)
                {
                    args[i].ValidUriSegment();
                }

                return(uriTemplate.BindByPosition(baseUri, args));
            }

            return(uriTemplate.BindByPosition(baseUri));
        }
示例#3
0
        protected void BrakeButtonSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //Get the parameters
                string[] mileage = { BrakeCurrentMileage.Text, BrakeLastMileage.Text };

                //Generate the URI template
                Uri         baseUri     = new Uri("http://webstrar32.fulton.asu.edu/page7/Service1.svc");
                UriTemplate myTemplate  = new UriTemplate("BrakeService?currentMileage={currentMileage}&LastBrakeChangeMileage={lastMileage}");
                Uri         completeUri = myTemplate.BindByPosition(baseUri, mileage);

                WebClient channel = new WebClient();                   //create a channel
                byte[]    abc     = channel.DownloadData(completeUri); //return byte array
                Stream    strm    = new MemoryStream(abc);             //convert to mem stream

                DataContractSerializer obj = new DataContractSerializer(typeof(string));
                string randString          = obj.ReadObject(strm).ToString(); //convert to string

                //display the result
                BrakeLabelResult.Text = randString;
            }catch (Exception ex)
            {
                //display any error messages
                BrakeLabelResult.Text = ex.Message;
            }
        }
示例#4
0
            public void CreateDataContract(User user)
            {
                WebOperationContext context = WebOperationContext.Current;

                UriTemplateMatch match    = context.IncomingRequest.UriTemplateMatch;
                UriTemplate      template = new UriTemplate("/user/dc/{id}");

                MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);

                if (!String.IsNullOrEmpty(user.ID))
                {
                    context.OutgoingResponse.StatusCode        = HttpStatusCode.BadRequest;
                    context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' already exists", user.ID);
                    return;
                }

                user.ID = (users.Count + 1).ToString(); // generate new ID

                users.Add(user);

                Uri uri = template.BindByPosition(match.BaseUri, user.ID);

                context.OutgoingResponse.SetStatusAsCreated(uri);
                context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", user.ID, user.Name);
            }
示例#5
0
        static string BuildFullUriTemplate(Uri baseUri, string uriTemplate)
        {
            UriTemplate template = new UriTemplate(uriTemplate);
            Uri         result   = template.BindByPosition(baseUri, template.PathSegmentVariableNames.Concat(template.QueryValueVariableNames).Select(name => "{" + name + "}").ToArray());

            return(result.ToString());
        }
        public string SellStock(string name, int value)
        {
            try
            {
                double stockprice = 10.0;
                double net        = stockprice * value;
                // BankingServiceReference.Service1Client bankAc = new BankingServiceReference.Service1Client();
                //bankAc.DepositAmount(net);
                UriTemplate myTemplate = new UriTemplate("DepositAmount?value={value}");

                Uri completeUri = myTemplate.BindByPosition(baseUri, net.ToString());

                WebClient proxy = new WebClient();

                byte[] abc  = proxy.DownloadData(completeUri);
                Stream strm = new MemoryStream(abc);
                DataContractSerializer obj = new DataContractSerializer(typeof(string));
                // Boolean flag = Convert.ToBoolean(obj.ReadObject(strm));
                return("Sold Successfully..");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#7
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        /*
         * Get the credit card information that needs to be validated with
         * the set of credit cards available in the local text file
         */
        string cardNo = TextBox1.Text;
        string date   = TextBox2.Text;
        string name   = TextBox4.Text;
        string cvv    = TextBox3.Text;

        /*
         * Set the base URI of the service deployed in webstrar folder
         */
        Uri baseUri = new Uri("http://webstrar64.fulton.asu.edu/page4/Service1.svc");
        // Define UriTemplate for passing parameter
        UriTemplate myTemplate = new UriTemplate("validate?cardNo={cardNo}&expiry={date}&name={name}&cvv={cvv}");
        // Assign values to variable to obtain the complete URI
        Uri       completeUri = myTemplate.BindByPosition(baseUri, cardNo, date, name, cvv);
        WebClient channel     = new WebClient();                      // create a channel

        byte[] abc  = channel.DownloadData(completeUri);              // return byte array
        Stream strm = new MemoryStream(abc);                          // convert to mem stream
        DataContractSerializer obj = new DataContractSerializer(typeof(string));
        string randString          = obj.ReadObject(strm).ToString(); // convent to string

        Label1.Text = randString;
    }
        public void SelectOperationReturnsOperationName()
        {
            HttpOperationAssert.Execute <UriTemplateService>(
                (operations) =>
            {
                Uri baseAddress = new Uri("http://localhost/baseAddress");
                UriAndMethodOperationSelector selector = new UriAndMethodOperationSelector(baseAddress, operations, TrailingSlashMode.Ignore);

                foreach (HttpOperationDescription operation in operations)
                {
                    UriTemplate uriTemplate  = operation.GetUriTemplate();
                    HttpMethod method        = operation.GetHttpMethod();
                    string expectedOperation = operation.Name;

                    string[] uriParameters = uriTemplate.PathSegmentVariableNames
                                             .Concat(uriTemplate.QueryValueVariableNames)
                                             .ToArray();
                    Uri requestUri             = uriTemplate.BindByPosition(baseAddress, uriParameters);
                    HttpRequestMessage request = new HttpRequestMessage(method, requestUri);

                    string actualOperation = selector.SelectOperation(request);
                    Assert.AreEqual(expectedOperation, actualOperation, "The UriAndMethodOperationSelector should have returned the selected operation name.");
                }
            });
        }
示例#9
0
        public IEnumerable<Uri> GetValidURIs(IAsset asset, CloudMediaContext _context)
        {
            IEnumerable<Uri> ValidURIs;
            var ismFile = asset.AssetFiles.AsEnumerable().Where(f => f.Name.EndsWith(".ism")).OrderByDescending(f => f.IsPrimary).FirstOrDefault();

            if (ismFile != null)
            {
                var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin && l.ExpirationDateTime > DateTime.UtcNow).OrderByDescending(l => l.ExpirationDateTime);

                var se = _context.StreamingEndpoints.AsEnumerable().Where(o => (o.State == StreamingEndpointState.Running) && (CanDoDynPackaging(o))).OrderByDescending(o => o.CdnEnabled);

                if (se.Count() == 0) // No running which can do dynpackaging SE. Let's use the default one to get URL
                {
                    se = _context.StreamingEndpoints.AsEnumerable().Where(o => o.Name == "default").OrderByDescending(o => o.CdnEnabled);
                }

                var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");

                ValidURIs = locators.SelectMany(l =>
                    se.Select(
                            o =>
                                template.BindByPosition(new Uri("http://" + o.HostName), l.ContentAccessComponent,
                                    ismFile.Name)))
                    .ToArray();

                return ValidURIs;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// To the URI.
        /// </summary>
        /// <param name="meta">The meta.</param>
        /// <param name="uriTemplateKey">The URI template key.</param>
        /// <param name="bindByPositionValues">The bind by position values.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">bindByPositionValues;The expected bind-by-position values are not here.</exception>
        /// <exception cref="ConfigurationErrorsException">The expected REST API metadata URI template key is not here.</exception>
        public static Uri ToUri(this RestApiMetadata meta, string uriTemplateKey, params string[] bindByPositionValues)
        {
            if (meta == null)
            {
                return(null);
            }
            if ((bindByPositionValues == null) || !bindByPositionValues.Any())
            {
                throw new ArgumentNullException("bindByPositionValues", "The expected bind-by-position values are not here.");
            }
            if (!meta.UriTemplates.Keys.Any(i => i == uriTemplateKey))
            {
                throw new FormatException("The expected REST API metadata URI template key is not here.");
            }

            var forwardSlash = "/";
            var uriBase      = meta.ApiBase.OriginalString.EndsWith(forwardSlash) ?
                               string.Concat(meta.ApiBase.OriginalString, meta.UriTemplates[uriTemplateKey])
                :
                               string.Concat(meta.ApiBase.OriginalString, forwardSlash, meta.UriTemplates[uriTemplateKey]);

            var uriTemplate = new UriTemplate(uriBase);
            var uri         = uriTemplate.BindByPosition(bindByPositionValues);

            return(uri);
        }
示例#11
0
        /*
         * This control is meant to call the RESTful service provided by USGS based on desired ranges from our users.
         * This will allow the user to control the date range for the index, the specific maximum radius from the given
         * Latitude and Longitude Coordinates and it will also allow the user to specify the minimum magnitude for earthquakes
         * when determining the respective index for that territory.
         * Inputs: (string)starting date, (decimal)latitude/longitude, (double)radius and magnitude
         * Outputs: (decimal) Earthquake Index
         *
         * This is ONE service
         */
        public decimal GetEarthQuakeHazard(string start, decimal latitude, decimal longitude, double radius, double magnitude)
        {
            string todaysDate = DateTime.Now.ToString("yyyy-MM-dd");     // strore current date in correct format


            Uri baseUri = new Uri("https://earthquake.usgs.gov/fdsnws/event/1");    // establish our baseUri

            // UriTemplate to help to bind/construct our completeUri
            UriTemplate myTemplate = new UriTemplate("count?starttime={startDate}&endtime={todaysDate}&latitude={latitude}&longitude={longitude}&maxradiuskm={radius}&minmagnitude={magnitude}");

            Uri completeUri = myTemplate.BindByPosition(baseUri, start, todaysDate, latitude.ToString(), longitude.ToString(), radius.ToString(), magnitude.ToString());

            WebClient channel = new WebClient();    // create a channel

            //            byte[] abc = channel.DownloadData(completeUri);

            string responseString = channel.DownloadString(completeUri);    // download the "data" directly as a string

            //           System.IO.Stream strm = new System.IO.MemoryStream(abc);

            //           DataContractSerializer obj = new DataContractSerializer(typeof(string));

            //           string label = obj.ReadObject(strm).ToString();
            return(Convert.ToDecimal(responseString));                       // convert our string to decimal
        }
示例#12
0
        /*
         * This control is used specifically to gather details about an area based on the zipcode
         * It will receive a zipcode as input and be used to only gather the latitude and longitude
         * coordinates. This service will be complimentary to many of our services that require
         * latitude and longitude inputs, making it easier for our users to process search queries.
         * Input: (string) zipCode
         * Output: (string[]) Latitude and Longitude Coordinates
         *
         * This is a Second Service
         */
        public string[] GetZipCodeDetails(string zipCode)
        {
            Uri baseUri = new Uri("http://api.zippopotam.us/");    // establish our baseUri

            // UriTemplate to help to bind/construct our completeUri
            UriTemplate myTemplate = new UriTemplate("us/{zipCode}");

            Uri completeUri = myTemplate.BindByPosition(baseUri, zipCode);

            WebClient channel = new WebClient();                         // create a channel

            string responseString = channel.DownloadString(completeUri); // download the "data" directly as a string


            var responses = (JObject)JsonConvert.DeserializeObject(responseString);

            var parsing        = JObject.Parse(responses.ToString());
            var jobj_longitude = parsing.SelectToken("places[*].longitude");

            var jobj_latitude = parsing.SelectToken("places[*].latitude");


            string latitude  = jobj_latitude.ToString();
            string longitude = jobj_longitude.ToString();


            string[] output = new string[2];
            output[0] = latitude;
            output[1] = longitude;

            return(output);
        }
示例#13
0
    protected void WithdrawButton_Click(object sender, EventArgs e)
    {
        try {
            if (AmountTextBox.Text == "")
            {
                StatusLabel.Text = "Please enter a valid amount";
            }
            else
            {
                UriTemplate myTemplate = new UriTemplate("WithdrawAmount?value={value}");

                Uri completeUri = myTemplate.BindByPosition(baseUri, AmountTextBox.Text);

                WebClient proxy = new WebClient();

                byte[] abc  = proxy.DownloadData(completeUri);
                Stream strm = new MemoryStream(abc);
                DataContractSerializer obj = new DataContractSerializer(typeof(string));
                string generatedString     = obj.ReadObject(strm).ToString();

                string status = generatedString;
                //string status = cl.WithdrawAmount(Convert.ToDouble(AmountTextBox.Text));
                StatusLabel.Text = status;
            }
        }
        catch (Exception ex)
        {
            StatusLabel.Text = ex.Message;
        }
    }
示例#14
0
        public async Task ShouldGenerateAzureSearchServiceIndexer()
        {
            var projectDirectory = this.TestContext.ShouldGetAssemblyDirectoryParent(this.GetType(), expectedLevels: 2);

            #region test properties:

            var jsonPath = this.TestContext.Properties["jsonPath"].ToString();
            jsonPath = Path.Combine(projectDirectory, jsonPath);
            this.TestContext.ShouldFindFile(jsonPath);

            #endregion

            var apiTemplate   = new UriTemplate(restApiMetadata.UriTemplates["search-component"]);
            var apiVersion    = restApiMetadata.ClaimsSet["search-api-version"];
            var componentName = restApiMetadata.ClaimsSet["component-name-indexers"];

            var uri = apiTemplate.BindByPosition(restApiMetadata.ApiBase, componentName, apiVersion);
            this.TestContext.WriteLine("uri: {0}", uri);

            var json = File.ReadAllText(jsonPath);

            var response = await httpClient.PostJsonAsync(uri, json, request => request.Headers.Add(apiKeyHeader, restApiMetadata.ApiKey));

            this.TestContext.WriteLine($"response: {await response.Content.ReadAsStringAsync()}");
        }
示例#15
0
        public async Task ShouldGenerateAzureSearchServiceDataSource()
        {
            var projectDirectory = this.TestContext.ShouldGetConventionalProjectDirectoryInfo(this.GetType());

            #region test properties:

            var jsonPath = this.TestContext.Properties["jsonPath"].ToString();
            jsonPath = Path.Combine(projectDirectory.FullName, jsonPath);
            this.TestContext.ShouldFindFile(jsonPath);

            #endregion

            var apiTemplate   = new UriTemplate(restApiMetadata.UriTemplates["search-component"]);
            var apiVersion    = restApiMetadata.ClaimsSet["search-api-version"];
            var componentName = restApiMetadata.ClaimsSet["component-name-datasources"];

            var uri = apiTemplate.BindByPosition(restApiMetadata.ApiBase, componentName, apiVersion);
            this.TestContext.WriteLine("uri: {0}", uri);

            var json = File.ReadAllText(jsonPath);
            var jO   = JObject.Parse(json);
            jO["credentials"]["connectionString"] = cloudStorageMeta["classic"];
            jO["container"]["name"] = cloudStorageMeta["classic-day-path-container"];
            json = jO.ToString();
            this.TestContext.WriteLine($"JSON payload: {json}");

            var response = await httpClient.PostJsonAsync(uri, json, request => request.Headers.Add(apiKeyHeader, restApiMetadata.ApiKey));

            this.TestContext.WriteLine($"response: {await response.Content.ReadAsStringAsync()}");
        }
示例#16
0
            public void CreateXElement(XElement user)
            {
                WebOperationContext context = WebOperationContext.Current;

                UriTemplateMatch match    = context.IncomingRequest.UriTemplateMatch;
                UriTemplate      template = new UriTemplate("/user/xml/{id}");

                MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);

                if (user.Element("ID") != null && !String.IsNullOrEmpty(user.Element("ID").Value))
                {
                    context.OutgoingResponse.StatusCode        = HttpStatusCode.BadRequest;
                    context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' already exists", user.Element("ID"));
                    return;
                }

                User newUser = new User();

                newUser.ID   = (users.Count + 1).ToString(); // generate new ID
                newUser.Name = user.Element("Name").Value;

                users.Add(newUser);

                Uri uri = template.BindByPosition(match.BaseUri, newUser.ID);

                context.OutgoingResponse.SetStatusAsCreated(uri);
                context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", newUser.ID, newUser.Name);
            }
示例#17
0
        private void Register(string route, string verb)
        {
            if (_router == null)
            {
                _http.RegisterAction(
                    new ControllerAction(route, verb, Codec.NoCodecs, SupportedCodecs, AuthorizationLevel.None),
                    (x, y) => {
                    x.Reply(new byte[0], 200, "", "", Helper.UTF8NoBom, null, e => new Exception());
                    CountdownEvent.Signal();
                });
            }
            else
            {
                _router.RegisterAction(
                    new ControllerAction(route, verb, Codec.NoCodecs, SupportedCodecs, AuthorizationLevel.None),
                    (x, y) => {
                    CountdownEvent.Signal();
                    return(new RequestParams(TimeSpan.Zero));
                });
            }

            var uriTemplate = new UriTemplate(route);
            var bound       = uriTemplate.BindByPosition(new Uri("http://localhost:12345/"),
                                                         Enumerable.Range(0,
                                                                          uriTemplate.PathSegmentVariableNames.Count +
                                                                          uriTemplate.QueryValueVariableNames.Count)
                                                         .Select(x => "abacaba")
                                                         .ToArray());

            BoundRoutes.Add(Tuple.Create(bound.AbsoluteUri, verb));
        }
            public Stream Post(Stream stream)
            {
                WebOperationContext context = WebOperationContext.Current;

                UriTemplateMatch match    = context.IncomingRequest.UriTemplateMatch;
                UriTemplate      template = new UriTemplate("/user/{id}");

                MediaType mediaType = MediaType.Parse(context.IncomingRequest.ContentType);
                Encoding  encoding  = (mediaType == null) ? Encoding.UTF8 : mediaType.CharSet;

                string id = (users.Count + 1).ToString(); // generate new ID
                string name;

                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    name = reader.ReadToEnd();
                }

                if (String.IsNullOrEmpty(name))
                {
                    context.OutgoingResponse.StatusCode        = HttpStatusCode.BadRequest;
                    context.OutgoingResponse.StatusDescription = "Content cannot be null or empty";
                    return(CreateTextResponse(context, ""));
                }

                users.Add(id, name);

                Uri uri = template.BindByPosition(match.BaseUri, id);

                context.OutgoingResponse.SetStatusAsCreated(uri);
                context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", id, name);

                return(CreateTextResponse(context, id));
            }
        protected void btnWeather_Click(object sender, EventArgs e)
        {
            // error checking for correct length
            if (txtZipWeather.Text.Length != 5)
            {
                this.lblCity.Text = "Please enter valid Zip Code.";
                return;
            }
            // error checking for digits (no strings allowed)
            if (!Int32.TryParse(txtZipWeather.Text, out int x))
            {
                this.lblCity.Text = "Please enter valid Zip Code.";
                return;
            }

            // generating Uri for our RESTful service
            Uri         baseUri     = new Uri("http://webstrar12.fulton.asu.edu/page0/Service1.svc/");
            UriTemplate myTemplate  = new UriTemplate("weather?zip={zip}");
            Uri         completeUri = myTemplate.BindByPosition(baseUri, txtZipWeather.Text);
            WebClient   proxy       = new WebClient();

            byte[] abc    = proxy.DownloadData(completeUri);
            Stream stream = new MemoryStream(abc);
            DataContractSerializer obj = new DataContractSerializer(typeof(string));
            string generatedString     = obj.ReadObject(stream).ToString();

            // splitting up output string
            string[] words = generatedString.Split(' ');

            // generating outputs
            lblFahr.Text = words[0] + " F";
            lblCel.Text  = words[1] + " C";
            lblCity.Text = words[2] + ", " + words[3];
        }
示例#20
0
        public async Task ShouldGetBlogEntryAsync()
        {
            var projectInfo = this.TestContext.ShouldGetProjectDirectoryInfo(this.GetType());

            #region test properties:

            var pathTemplate = new UriTemplate(string.Concat(baseRoute, this.TestContext.Properties["pathTemplate"].ToString()));
            var id           = this.TestContext.Properties["id"].ToString();
            var outputFile   = this.TestContext.Properties["outputFile"].ToString();
            outputFile = projectInfo.ToCombinedPath(outputFile);
            this.TestContext.ShouldFindFile(outputFile);

            #endregion

            var path     = pathTemplate.BindByPosition(id);
            var client   = this._server.CreateClient();
            var response = await client.GetAsync(path);

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            Assert.IsFalse(string.IsNullOrEmpty(content), "The expected content is not here.");
            var jO = JObject.Parse(content);
            File.WriteAllText(outputFile, jO.ToString());
        }
示例#21
0
        public void BindByPosition()
        {
            var t = new UriTemplate("/{foo}/{bar}/");
            var u = t.BindByPosition(new Uri("http://localhost/"), "value1", "value2");

            Assert.AreEqual("http://localhost/value1/value2/", u.ToString());
        }
        public static IEnumerable <Uri> GetValidPaths(IAsset asset, string preferredSE = null)
        {
            IEnumerable <Uri> ValidURIs;

            var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin && l.ExpirationDateTime > DateTime.UtcNow).OrderByDescending(l => l.ExpirationDateTime);

            //var se = _context.StreamingEndpoints.AsEnumerable().Where(o => (o.State == StreamingEndpointState.Running) && (CanDoDynPackaging(o))).OrderByDescending(o => o.CdnEnabled);

            var se = MediaContext.StreamingEndpoints.AsEnumerable().Where(o =>

                                                                          (string.IsNullOrEmpty(preferredSE) || (o.Name == preferredSE))
                                                                          &&
                                                                          (!string.IsNullOrEmpty(preferredSE) || ((o.State == StreamingEndpointState.Running) && (CanDoDynPackaging(o)))
                                                                          ))
                     .OrderByDescending(o => o.CdnEnabled);

            if (se.Count() == 0) // No running which can do dynpackaging SE and if not preferredSE. Let's use the default one to get URL
            {
                se = MediaContext.StreamingEndpoints.AsEnumerable().Where(o => o.Name == "default").OrderByDescending(o => o.CdnEnabled);
            }

            var template = new UriTemplate("{contentAccessComponent}/");

            ValidURIs = locators.SelectMany(l => se.Select(
                                                o =>
                                                template.BindByPosition(new Uri("https://" + o.HostName), l.ContentAccessComponent)))
                        .ToArray();

            return(ValidURIs);
        }
示例#23
0
        public IEnumerable <Uri> GetNotValidURIs()
        {
            IEnumerable <Uri> NotValidURIs;
            IAsset            asset = _context.Assets.Where(a => a.Id == SelectedPrograms.FirstOrDefault().AssetId).Single();
            var ismFile             = asset.AssetFiles.AsEnumerable().FirstOrDefault(f => f.Name.EndsWith(".ism"));

            if (ismFile != null)
            {
                var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);

                var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");


                NotValidURIs = locators.SelectMany(l =>
                                                   _context
                                                   .StreamingEndpoints
                                                   .AsEnumerable()
                                                   .Where(o => o.State != StreamingEndpointState.Running)
                                                   .Select(
                                                       o =>
                                                       template.BindByPosition(new Uri("http://" + o.HostName), l.ContentAccessComponent,
                                                                               ismFile.Name)))
                               .ToArray();

                return(NotValidURIs);
            }
            else
            {
                return(null);
            }
        }
示例#24
0
		[ExpectedException (typeof (FormatException))] // it does not allow default values
		public void BindByPositionWithDefaults ()
		{
			var d = new Dictionary<string,string> ();
			d ["baz"] = "value3";
			var t = new UriTemplate ("/{foo}/{bar}/{baz}", d);
			t.BindByPosition (new Uri ("http://localhost/"), "value1", "value2");
		}
        private static Uri CreateUri(int key)
        {
            UriTemplate uriTemplate = new UriTemplate("/{key}");
            Uri         baseUri     = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri;
            Uri         locationUri = uriTemplate.BindByPosition(baseUri, key.ToString());

            return(locationUri);
        }
        public Uri GetMenuUri()
        {
            CheckArgumentNotNull(CachedType, "service type");

            var template = new UriTemplate(SegmentValues.Menus + "/{oid}");

            return(template.BindByPosition(prefix, CachedType));
        }
        public Uri GetObjectsPersistUri()
        {
            CheckArgumentNotNull(CachedType, "object type");

            var template = new UriTemplate(SegmentValues.Objects + "/{objectType}");

            return(template.BindByPosition(prefix, CachedType));
        }
        public Uri GetWellKnownUri(string name)
        {
            CheckArgumentNotNull(name, "well known name");

            var template = new UriTemplate("{fixed}");

            return(template.BindByPosition(prefix, name));
        }
        private Uri BuildDomainTypeUri(string type)
        {
            CheckArgumentNotNull(type, "domain type");

            var template = new UriTemplate(SegmentValues.DomainTypes + "/{type}");

            return(template.BindByPosition(prefix, type));
        }
示例#30
0
        /// <summary>
        /// Gets the torrent file download Uri with which other peers can download
        /// the torrent file from this server.
        /// </summary>
        /// <param name="nameSpace">The name space.</param>
        /// <param name="name">The name.</param>
        public string GetTorrentFileUrlToPublish(string nameSpace, string name)
        {
            var template = new UriTemplate("TorrentData/{namespace}/{name}/TorrentFile");
            var baseAddr = string.Format("http://{0}:{1}", _hostIP, _gsserverPort);
            Uri retVal   = template.BindByPosition(new Uri(baseAddr), nameSpace, name);

            return(retVal.ToString());
        }
 static string BuildFullUriTemplate(Uri baseUri, string uriTemplate)
 {
     UriTemplate template = new UriTemplate(uriTemplate);
     Uri result = template.BindByPosition(baseUri, template.PathSegmentVariableNames.Concat(template.QueryValueVariableNames).Select(name => "{" + name + "}").ToArray());            
     return result.ToString();
 }