C# (CSharp) Class System. Uri Code Examples

C# (CSharp) System.Uri - 30 examples found. These are the top rated real world C# (CSharp) examples of class System.Uri extracted from open source projects. You can rate examples to help us improve the quality of examples
Inheritance: ISerializable
        /// <summary>
        /// Does setup of AutoCAD IO. 
        /// This method will need to be invoked once before any other methods of this
        /// utility class can be invoked.
        /// </summary>
        /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
        /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
        public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
        {
            try
            {
                String clientId = autocadioclientid;
                String clientSecret = autocadioclientsecret;

                Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
                container = new AIO.Operations.Container(uri);
                container.Format.UseJson();

                using (var client = new HttpClient())
                {
                    var values = new List<KeyValuePair<string, string>>();
                    values.Add(new KeyValuePair<string, string>("client_id", clientId));
                    values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    var requestContent = new FormUrlEncodedContent(values);
                    var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
                    _accessToken = resValues["token_type"] + " " + resValues["access_token"];
                    if (!string.IsNullOrEmpty(_accessToken))
                    {
                        container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
                container = null;
                throw;
            }
        }
        /// <summary>
        /// Reads a URI.
        /// </summary>
        /// <param name="node">The node containing the URI.</param>
        /// <param name="table">The serialiser table.</param>
        /// <returns>A new instance of a <see cref="Uri"/> if the node is valid; null otherwise.</returns>
        public override object Read(XmlNode node, NetReflectorTypeTable table)
        {
            if (node == null)
            {
                // NetReflector should do this check, but doesn't
                if (this.Attribute.Required)
                {
                    throw new NetReflectorItemRequiredException(Attribute.Name + " is required");
                }
                else
                {
                    return null;
                }
            }

            Uri ret;
            if (node is XmlAttribute)
            {
                ret = new Uri(node.Value);
            }
            else
            {
                ret = new Uri(node.InnerText);
            }

            return ret;
        }
Example #3
0
        public static WarmupResult Warmup(IisSite site, string warmupUrl)
        {
            var uri = new Uri(warmupUrl);
            var testUrl = uri.ToString().Replace(uri.Host, "127.0.0.1");

            var request = WebRequest.Create(testUrl) as HttpWebRequest;
            request.Host = uri.Host + ":" + uri.Port;
            HttpWebResponse response;
            try
            {
                 response = (HttpWebResponse)request.GetResponse();
                 return new WarmupResult(response);
            }
            catch (WebException ex)
            {
                var exceptionResponse = (HttpWebResponse) ex.Response;

                if (exceptionResponse == null)
                {
                    return null;
                }

                return new WarmupResult(exceptionResponse);
            }
        }
Example #4
0
        protected AbstractMsmqListener(
            IQueueStrategy queueStrategy,
            Uri endpoint,
            int threadCount,
            IMessageSerializer messageSerializer,
            IEndpointRouter endpointRouter,
            TransactionalOptions transactional,
            IMessageBuilder<Message> messageBuilder)
        {
            this.queueStrategy = queueStrategy;
            this.messageSerializer = messageSerializer;
            this.endpointRouter = endpointRouter;
            this.endpoint = endpoint;

            this.threadCount = threadCount;
            threads = new Thread[threadCount];

            switch (transactional)
            {
                case TransactionalOptions.Transactional:
                    this.transactional = true;
                    break;
                case TransactionalOptions.NonTransactional:
                    this.transactional = false;
                    break;
                case TransactionalOptions.FigureItOut:
                    this.transactional = null;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("transactional");
            }
            this.messageBuilder = messageBuilder;
            this.messageBuilder.Initialize(Endpoint);
        }
        public static void Main()
        {
            var url = new Uri(ApiUrl + "?auth-id=" + AuthenticationID + "&auth-token=" + AuthenticationToken);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
                writer.Write(RequestPayload);

            using (var response = request.GetResponse())
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var rawResponse = reader.ReadToEnd();
                Console.WriteLine(rawResponse);

                // Suppose you wanted to use Json.Net to pretty-print the response (delete the next two lines if not):
                // Json.Net: http://http://json.codeplex.com/
                dynamic parsedJson = JsonConvert.DeserializeObject(rawResponse);
                Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));

                // Or suppose you wanted to deserialize the json response to a defined structure (defined below):
                var candidates = JsonConvert.DeserializeObject<CandidateAddress[]>(rawResponse);
                foreach (var address in candidates)
                    Console.WriteLine(address.DeliveryLine1);
            }

            Console.ReadLine();
        }
 public void ShouldSetShieldingWithNonIncludeExceptionDetailInFaults()
 {
     // create a mock service and its endpoint.
     Uri serviceUri = new Uri("http://tests:30003");
     ServiceHost host = new ServiceHost(typeof(MockService), serviceUri);
     host.AddServiceEndpoint(typeof(IMockService), new WSHttpBinding(), serviceUri);
     host.Open();
     try
     {
         // check that we have no ErrorHandler loaded into each channel that
         // has IncludeExceptionDetailInFaults turned off.
         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
         {
             Assert.AreEqual(0, dispatcher.ErrorHandlers.Count);
             Assert.IsFalse(dispatcher.IncludeExceptionDetailInFaults);
         }
         ExceptionShieldingBehavior behavior = new ExceptionShieldingBehavior();
         behavior.ApplyDispatchBehavior(null, host);
         // check that the ExceptionShieldingErrorHandler was assigned to each channel
         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
         {
             Assert.AreEqual(1, dispatcher.ErrorHandlers.Count);
             Assert.IsTrue(dispatcher.ErrorHandlers[0].GetType().IsAssignableFrom(typeof(ExceptionShieldingErrorHandler)));
         }
     }
     finally
     {
         if (host.State == CommunicationState.Opened)
         {
             host.Close();
         }
     }
 }
Example #7
0
 /// <summary>
 /// Конструктор с настройками библиотеки
 /// </summary>
 /// <param name="chunkSizeByte">Размер порции пересылаемых данных, байт</param>
 /// <param name="requestTimeOutSec">Таймаут запроса, сек</param>
 /// <param name="storageUrl">Адрес системы хранения</param>
 /// <param name="concurrentConnectionLimit">Количество одновременных потоков работы с системой хранения</param>
 public FSClient(int chunkSizeByte, int requestTimeOutSec, string storageUrl, int concurrentConnectionLimit)
 {
     _chunkSize = chunkSizeByte;
     _requestTimeOut = (int)TimeSpan.FromSeconds(requestTimeOutSec).TotalMilliseconds;
     _storageUrl = new Uri(storageUrl).ToString();
     ServicePointManager.DefaultConnectionLimit = concurrentConnectionLimit;
 }
Example #8
0
 public void NavigateTo(Uri pageUri)
 {
     if (EnsureMainFrame())
     {
         _mainFrame.Navigate(pageUri);
     }
 }
 /// <summary>Initializes a new instance of <see cref="MockWebRequest"/>
 /// with the response to return.</summary>
 public MockWebRequest(Uri uri, string response)
 {
     m_requestUri = uri;
     m_requestStream = new MemoryStream();
     Stream m_responseStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response));
     m_mockResponse = new MockWebResponse(m_responseStream);
 }
Example #10
0
        public static string GenerateRelativePath(string from, string to)
        {
            if(String.IsNullOrWhiteSpace(from) || String.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentNullException("Requires paths");
            }

            Uri fromUri = new Uri(from);
            Uri toUri = new Uri(to);

            //The URI schemes have to match in order for the path to be made relative
            if(fromUri.Scheme != toUri.Scheme)
            {
                return to;
            }

            Uri relativeUri = fromUri.MakeRelativeUri(toUri);
            string relative = Uri.UnescapeDataString(relativeUri.ToString());

            //If neccessary to do so, normalise the use of slashes to always be the default for this platform
            if(toUri.Scheme.ToUpperInvariant() == "FILE")
            {
                relative = relative.Replace(Path.AltDirectorySeparatorChar,
                    Path.DirectorySeparatorChar);
            }

            return relative;
        }
Example #11
0
        /**
         * Creates the fiHash-object and prepares the internal fields for the call to GetFileStream.
         *
         * \param file An Uri-object pointing to the file, that the hash should be calculated for. Only supports file:/ URLs!
        */
        public fiHash(Uri file)
        {
            if (file.Scheme != Uri.UriSchemeFile)
                throw new ArgumentException("Unsupported Uri Schema!");

            filename = file.LocalPath;
        }
        public IRedirect ProcessRedirection(string url)
        {
            var redirectResponse = new Redirect();

            // Check that we've received the url parameter
            if (string.IsNullOrEmpty(url))
            {
                redirectResponse.ErrorMessage = string.Format("Url parameter was missing or malformed - ({0}).", url);
                return redirectResponse;
            }

            // Check that url is valid as we don't want a broken redirect
            var uri = new Uri(url);
            redirectResponse.Allowed = true;
            redirectResponse.Url = uri;

            if (_siteConfiguration.SecureMode)
            {
                // Secure mode activated
                if (!uri.Host.EndsWith(_siteConfiguration.WebsiteDomain) || !uri.IsAbsoluteUri)
                {
                    redirectResponse.Allowed = false;
                    redirectResponse.Url = null;
                    redirectResponse.ErrorMessage =
                        string.Format(
                            "Potentially dangerous redirect detected and blocked. Submitted url ({0}) did not match allowed domain list or was malformed.",
                            url);
                }
            }

            return redirectResponse;
        }
        public static IEnumerable<string> GetAllStyleSheets(string searchFrom, IEnumerable<string> allowedExtensions)
        {
            var project = ProjectHelpers.GetProject(searchFrom);
            var projectPath = project.Properties.Item("FullPath").Value.ToString();
            var projectUri = new Uri(projectPath, UriKind.Absolute);
            var fileNames = new HashSet<string>();
            var projectDir = Path.GetDirectoryName(projectPath);

            if (projectDir == null)
            {
                return new string[0];
            }

            foreach (var extension in allowedExtensions)
            {
                var matchingFiles = Directory.GetFiles(projectDir, "*" + extension, SearchOption.AllDirectories);

                foreach (var file in matchingFiles)
                {
                    var mappedFile = GetStyleSheetFileForUrl(file, project, projectUri);

                    if (mappedFile != null)
                    {
                        fileNames.Add(mappedFile);
                    }
                }
            }

            return fileNames;
        }
Example #14
0
        IResource IResourceResolver.Resolve(Uri uri)
        {
            IResource resource = null;
            try
            {

                string fileName = uri.LocalPath;
                string ext = Path.GetExtension(fileName).ToLower();
                if (ext == m_ext)
                {
                    using (Stream stream = File.OpenRead(fileName))
                    {
                        var reader = new CustomDomXmlReader(Globals.ResourceRoot, m_schemaLoader);
                        DomNode node = reader.Read(stream, uri);                        
                        resource = Prefab.Create(node, uri);
                    }
                }
            }
            catch (System.IO.IOException e)
            {
                Outputs.WriteLine(OutputMessageType.Warning, "Could not load resource: " + e.Message);
            }

            return resource;
        }
	    public SubscriptionClient(IServiceBus bus, SubscriptionRouter router, Uri subscriptionServiceUri,
		                          TimeSpan startTimeout)
		{
			_bus = bus;
			_router = router;
			_subscriptionServiceUri = subscriptionServiceUri;
			_startTimeout = startTimeout;
			_network = router.Network;

			if (_log.IsDebugEnabled)
				_log.DebugFormat("Starting SubscriptionClient using {0}", subscriptionServiceUri);

			VerifyClientAndServiceNotOnSameEndpoint(bus);

			_ready.Reset();

			var consumerInstance = new SubscriptionMessageConsumer(_router, _network);

			_unsubscribeAction = _bus.ControlBus.SubscribeInstance(consumerInstance);
		    _unsubscribeAction += _bus.ControlBus.SubscribeContextHandler<SubscriptionRefresh>(Consume);

		    _subscriptionEndpoint = _bus.GetEndpoint(subscriptionServiceUri);
		    _producer = new SubscriptionServiceMessageProducer(router, _subscriptionEndpoint);

			WaitForSubscriptionServiceResponse();
		}
        private void play(string url)
        {
            this.mediaPlayer = new MediaPlayerLauncher();

            Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);

            if (uri.IsAbsoluteUri)
            {
                this.mediaPlayer.Media = uri;
            }
            else
            {
                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (isoFile.FileExists(url))
                    {
                        this.mediaPlayer.Location = MediaLocationType.Data;
                        this.mediaPlayer.Media = uri;
                    }
                    else
                    {
                        throw new ArgumentException("Media location doesn't exists.");
                    }
                }
            }

            this.mediaPlayer.Show();
        }
Example #17
0
 public static void PlayBackgroundMusic(string name)
 {
     string locationString = ResourceManager.GetSoundLocationByName(name);
     Uri location = new Uri(locationString);
     MediaPlayer.Stop();
     MediaPlayer.Play(Song.FromUri(name, location));
 }
Example #18
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            if (!loadConfigFile())
            {
                MessageBox.Show("Can't read configuration file!");
                Application.Exit();
            }
            try
            {
                project_uri = new Uri(getCfgValue("projecturl"));
            }
            catch (UriFormatException)
            {
                MessageBox.Show("Malformed projecturl tag in the configuration file!");
                Application.Exit();
            }

            var value = new Uri(project_uri, getCfgValue("updates_page_url", "updates.html"));            

            webBrowser1.Navigate(value); 
            update_state = UpdateStates.Ready;

            this.Text = getCfgValue("application_title");

            runWhenFinished = (RunApplications)getCfgValueInt("runWhenFinished");

            workInBackground.DoWork += new DoWorkEventHandler(UpdateTheClient);
            workInBackground.RunWorkerCompleted += new RunWorkerCompletedEventHandler(UpdateTheClientCompleted);
            workInBackground.ProgressChanged += new ProgressChangedEventHandler(UpdateTheClientProgressChanged);
        }
Example #19
0
        public UpdateBarModel(Version version, string downloadUri)
        {
            if (version == null || downloadUri == null)
            {
                UpdateAvailable = false;
                return;
            }

            Version = version;
            var currentVersion = typeof(CertInspector).Assembly.GetName().Version;
            var closed = Fiddler.FiddlerApplication.Prefs.GetPref(PreferenceNames.HIDE_UPDATED_PREF, false);
            UpdateAvailable = version > currentVersion && !closed;
            Fiddler.FiddlerApplication.Log.LogString($"FiddlerCert Inspector: Current version is {currentVersion}, latest version is {version}.");
            _downloadCommand = new RelayCommand(_ =>
            {
                var uri = new Uri(downloadUri);
                if (uri?.Scheme == Uri.UriSchemeHttps)
                {
                    Process.Start(uri.AbsoluteUri);
                }
                else
                {
                    Fiddler.FiddlerApplication.Log.LogString("Refusing to open non-HTTPS page.");
                }
            });
            _closeCommand = new RelayCommand(_ =>
            {
                Fiddler.FiddlerApplication.Prefs.SetPref(PreferenceNames.HIDE_UPDATED_PREF, true);
                UpdateAvailable = false;
            });
        }
Example #20
0
        internal static void SetGitHubBuildStatus(
            Build build,
            CommitState state,
            Func<string, string, BuildConfiguration> getBuildConfiguration,
            Func<Build, string> getBuildDescription,
            Func<string> getHost,
            Action<string, string, string, string, CommitState, Uri, string> createGitHubCommitStatus)
        {
            var buildConfiguration = getBuildConfiguration(
                build.RepositoryOwner,
                build.RepositoryName);

            if (buildConfiguration == null)
                throw new Exception("Could not find build configuration.");

            var targetUrl = new Uri(String.Format(
                "http://{0}/{1}/{2}/builds/{3}",
                getHost(),
                build.RepositoryOwner,
                build.RepositoryName,
                build.Id));

            createGitHubCommitStatus(
                buildConfiguration.Token,
                build.RepositoryOwner,
                build.RepositoryName,
                build.Revision,
                state,
                targetUrl,
                getBuildDescription(build));
        }
 public FakeStorageBlobContainer(MemoryBlobStore store, string containerName, IStorageBlobClient parent)
 {
     _store = store;
     _containerName = containerName;
     _parent = parent;
     _uri = new Uri("http://localhost/" + containerName);
 }
Example #22
0
            public void ReturnsSafeUriString()
            {
                var inputUri = new Uri("/Views/MainPage.xaml", UriKind.RelativeOrAbsolute);
                var uri = UrlHelper.GetSafeUriString(inputUri);

                Assert.AreEqual("/Views/MainPage.xaml", uri);
            }
Example #23
0
 public RssResult(string title, string desc, string link, List<SyndicationItem> items)
 {
     _title = title;
     _desc = desc;
     _altLink = new Uri(link);
     _items = items;
 }
Example #24
0
            public void ReturnsSafeUriStringForUriWithMultipleStartingSlashes()
            {
                var inputUri = new Uri("//Views/MainPage.xaml", UriKind.RelativeOrAbsolute);
                var uri = UrlHelper.GetSafeUriString(inputUri);

                Assert.AreEqual("/Views/MainPage.xaml", uri);
            }
Example #25
0
        private string BuildIFirstRowPTEUHtmlObject(Uri link, int level)
        {
            string page = this.GetWebDocument(link);

            int start = page.IndexOf("<script type=\"text/javascript\" src=\"http://www.04stream.com/weed.js");
            int end = page.IndexOf("script>", start);
            string js = page.Substring(start, end - start + 8).Replace('"', '\'');

            start = js.IndexOf("src='");
            end = js.IndexOf("'", start + 5);

            string jslink = js.Substring(start + 5, end - start - 5);

            page = this.GetWebDocument(new Uri(jslink));

            page = page.Replace("'+document.domain+'", link.Host);

            start = page.IndexOf("src=");
            end = page.IndexOf(">", start + 4);

            string iframe = page.Substring(start + 4, end - start - 4);

            if (level == 0)
                return iframe;

            return BuildStreamHtmlObject(new Uri(iframe), level - 1);
        }
		public static RemoteActorRegistryConfigurator ListenTo(this RemoteActorRegistryConfigurator configurator,
		                                                       string uriString)
		{
			var uri = new Uri(uriString);

			return configurator.ListenTo(uri);
		}
        public string AnalyzeAndRepair(Uri uri, string parentFileName, out bool success)
        {
            foreach (var newPath in from validIfContains in ContentServerData.BaseShares
                                       where uri.AbsoluteUri.ToLower(CultureInfo.CurrentCulture).Contains(validIfContains)
                                       select uri.AbsoluteUri.Substring(uri.AbsoluteUri.ToLower(CultureInfo.CurrentCulture).LastIndexOf(validIfContains, StringComparison.CurrentCulture)))
            {
                Uri newUri;
                if (Uri.TryCreate(ContentServerData.BaseUri, new Uri(newPath, UriKind.Relative), out newUri))
                {

                    if (!WebResourceExists(newUri))
                    {
                        ManualFixLog.PrintFileNotFoundMessage(uri.OriginalString, parentFileName);
                        success = false;
                        return uri.OriginalString;
                    }
                    success = true;
                    return newPath;
                }

                success = false;
                ManualFixLog.PrintBadPathOrImproperTerms(uri.OriginalString, parentFileName);
                return uri.OriginalString;
            }

            success = false;
            ManualFixLog.PrintBadPathOrImproperTerms(uri.OriginalString, parentFileName);
            return uri.OriginalString;
        }
 public string Download(Uri uri)
 {
     using(var reader = new StreamReader(uri.LocalPath))
     {
         return reader.ReadToEnd();
     }
 }
Example #29
0
 public ItemCrawler(Uri url)
 {
     _htmlDocument = new HtmlDocument();
     var html = new WebClient().DownloadString(url.OriginalString);
     _htmlDocument.LoadHtml(html);
     _document = _htmlDocument.DocumentNode;
 }
 public Menu(string _name,Uri pathToIcon,int _enabled=1)
 {
     this.name = _name;
     this.enabled = _enabled;
     if (pathToIcon != null)
         this.sysIcon = pathToIcon;
 }