Ejemplo n.º 1
0
        private static IWebRequestCreate GetCreator(string prefix)
        {
            int longestPrefix         = -1;
            IWebRequestCreate creator = null;

            prefix = prefix.ToLower(CultureInfo.InvariantCulture);

            IDictionaryEnumerator e = prefixes.GetEnumerator();

            while (e.MoveNext())
            {
                string key = e.Key as string;

                if (key.Length <= longestPrefix)
                {
                    continue;
                }

                if (!prefix.StartsWith(key))
                {
                    continue;
                }

                longestPrefix = key.Length;
                creator       = (IWebRequestCreate)e.Value;
            }

            if (creator == null)
            {
                throw new NotSupportedException(prefix);
            }

            return(creator);
        }
Ejemplo n.º 2
0
	// This method will attempt to create a particular subclass of WebRequest
	// based on the scheme from the uri passed in. Currently on HttpWebRequest
	// is supported.
	public static WebRequest Create(Uri requestUri)
	{

		IWebRequestCreate theCreator = null;
		
		if(CheckUriValidity(requestUri, false))
		{

			// Check here to see if the Uri scheme exists in the
			// prefixes table and if so, then return back the
			// proper WebRequest for it
			theCreator = (prefixes[requestUri.Scheme] as IWebRequestCreate);
			
			if(theCreator!=null)
			{
				return theCreator.Create(requestUri);
			}

		// TODO: this client does not have the permission to connect to the URI or
		// the URI that the request is redirected to.
		// throw new SecurityException("requestUriString");
		}
		   
		return null;
	}
Ejemplo n.º 3
0
 static WebRequest()
 {
     registred_prefixes = new Dictionary <string, IWebRequestCreate> (StringComparer.OrdinalIgnoreCase);
     browser_creator    = (IWebRequestCreate)Activator.CreateInstance(Type.GetType(BrowserStack));
     client_creator     = (IWebRequestCreate)Activator.CreateInstance(Type.GetType(ClientStack));
     default_creator    = browser_creator;
 }
Ejemplo n.º 4
0
        // We can register for
        // * a protocol (e.g. http) for all requests
        // * a protocol (e.g. https) for a domain
        // * a protocol (e.g. http) for a single request
        //
        // See "How to: Specify Browser or Client HTTP Handling" for more details
        // http://msdn.microsoft.com/en-us/library/dd920295%28VS.95%29.aspx
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }

            Uri uri;

            if (Uri.TryCreate(prefix, UriKind.Absolute, out uri))
            {
                // if a valid URI is supplied then only register the scheme + domain
                prefix = uri.Scheme + Uri.SchemeDelimiter + uri.DnsSafeHost;
            }

            // registering 'http', 'http://' or even 'http:/' are all ok - but *never* would 'http:' be correct!
            if ((String.Compare(prefix, "http:", StringComparison.OrdinalIgnoreCase) == 0) ||
                (String.Compare(prefix, "https:", StringComparison.OrdinalIgnoreCase) == 0))
            {
                return(false);
            }

            if (registred_prefixes.ContainsKey(prefix))
            {
                return(false);
            }

            registred_prefixes.Add(prefix, creator);
            return(true);
        }
Ejemplo n.º 5
0
        private static IWebRequestCreate GetCreator(string prefix)
        {
            int num = -1;
            IWebRequestCreate webRequestCreate = null;

            prefix = prefix.ToLower(CultureInfo.InvariantCulture);
            IDictionaryEnumerator enumerator = WebRequest.prefixes.GetEnumerator();

            while (enumerator.MoveNext())
            {
                string text = enumerator.Key as string;
                if (text.Length > num)
                {
                    if (prefix.StartsWith(text))
                    {
                        num = text.Length;
                        webRequestCreate = (IWebRequestCreate)enumerator.Value;
                    }
                }
            }
            if (webRequestCreate == null)
            {
                throw new NotSupportedException(prefix);
            }
            return(webRequestCreate);
        }
        /// <summary>
        /// Registers a <itemref>WebRequest</itemref> descendant for the
        /// specified URI.
        /// </summary>
        /// <param name="prefix">The complete URI or URI prefix that the
        /// <itemref>WebRequest</itemref> descendant services.</param>
        /// <param name="creator">The create method that the
        /// <itemref>WebRequest</itemref> calls to create the
        /// <itemref>WebRequest</itemref> descendant.</param>
        /// <returns><itemref>true</itemref>.</returns>
        public static bool RegisterPrefix(string prefix,
                                          IWebRequestCreate creator)
        {
            if (prefix == null || creator == null)
            {
                throw new ArgumentNullException();
            }

            // Changes prefix to lower becuase it is case insensitive.
            prefix = prefix.ToLower();
            lock (g_listLock)
            {
                // Iterate over list of prefixes and checks if this one is
                // already present.
                for (int i = 0; i < s_PrefixList.Count; i++)
                {
                    if (((WebRequestPrefixElement)s_PrefixList[i]).Prefix == prefix)
                    {
                        return(false);
                    }
                }

                // This is a new prefix, add it.
                s_PrefixList.Add(new WebRequestPrefixElement(prefix, creator));
            }

            return(true);
        }
Ejemplo n.º 7
0
        // We can register for
        // * a protocol (e.g. http) for all requests
        // * a protocol (e.g. https) for a domain
        // * a protocol (e.g. http) for a single request
        //
        // See "How to: Specify Browser or Client HTTP Handling" for more details
        // http://msdn.microsoft.com/en-us/library/dd920295%28VS.95%29.aspx
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }

            Uri uri;

            if (Uri.TryCreate(prefix, UriKind.Absolute, out uri))
            {
                // if a valid URI is supplied then only register the scheme + domain
                prefix = uri.Scheme + Uri.SchemeDelimiter + uri.DnsSafeHost;
            }

            if (registred_prefixes.ContainsKey(prefix))
            {
                return(false);
            }

            registred_prefixes.Add(prefix, creator);
            return(true);
        }
Ejemplo n.º 8
0
		static WebRequest ()
		{
			registred_prefixes = new Dictionary<string, IWebRequestCreate> (StringComparer.OrdinalIgnoreCase);
			browser_creator = (IWebRequestCreate) Activator.CreateInstance (Type.GetType (BrowserStack));
			client_creator = (IWebRequestCreate) Activator.CreateInstance (Type.GetType (ClientStack));
			default_creator = browser_creator;
		}
Ejemplo n.º 9
0
 public static IWebRequestCreate Decorate(this IWebRequestCreate webRequestProvider, Action <WebRequest> requestDecorator)
 {
     return(new WebRequestCreateDecorator(webRequestProvider, r =>
     {
         requestDecorator(r);
         return r;
     }));
 }
Ejemplo n.º 10
0
 public static IWebRequestCreate Decorate <TRequest>(this IWebRequestCreate webRequestProvider, Action <TRequest> requestDecorator)
     where TRequest : WebRequest
 {
     return(new WebRequestCreateDecorator(webRequestProvider, r =>
     {
         r.Maybe(requestDecorator);
         return r;
     }));
 }
Ejemplo n.º 11
0
        //
        // Add - Adds/Updates the collection
        //
        protected override void Add(string prefix, string type)
        {
            IWebRequestCreate moduleToRegister = null;

            if (type == null)
            {
                return;
            }

            // converts a type an object of type

            try {
                moduleToRegister = (IWebRequestCreate)Activator.CreateInstance(
                    Type.GetType(type, true, true),
                    BindingFlags.CreateInstance
                    | BindingFlags.Instance
                    | BindingFlags.NonPublic
                    | BindingFlags.Public,
                    null,                                      // Binder
                    new object[0],                             // no arguments
                    CultureInfo.InvariantCulture
                    );
            }
            catch (Exception e)  {
                //
                // throw exception for config debugging
                //

                throw new ConfigurationException("WebRequestModuleHandler", e);
            }


            bool matched         = false;
            int  indexToInsertAt = FindPrefix(prefix, ref matched);

            // When we get here either i contains the index to insert at or
            // we've had an error if we've already found it matched

            if (!matched)
            {
                // no adding on duplicates
                _res.Insert(indexToInsertAt,
                            new WebRequestPrefixElement(prefix, moduleToRegister)
                            );
            }
            else
            {
                // update
                _res[indexToInsertAt] =
                    new WebRequestPrefixElement(prefix, moduleToRegister);
            }

            return;
        }
Ejemplo n.º 12
0
        public TeamCity6Provider(IWebRequestCreate webRequestCreate, IClock clock, ILog log)
        {
            this.webRequestCreate = webRequestCreate;
            this.clock = clock;
            this.log = log;

            updateStrategies = new ITeamCity6UpdateStrategy[]
            {
                new PersonalBuildsTeamCity6UpdateStrategy(webRequestCreate, clock, log),
                new PerJobTeamCity6UpdateStrategy(webRequestCreate, clock, log)
            };
        }
Ejemplo n.º 13
0
        public LastfmRequest(string method, RequestType request_type, ResponseFormat response_format)
        {
            this.method          = method;
            this.request_type    = request_type;
            this.response_format = response_format;
            if (this.web_request_creator == null)
            {
                this.web_request_creator = new WebRequestCreator();
            }

            Init();
        }
Ejemplo n.º 14
0
        /// <summary>
        ///  Registers a WebRequest descendant for the specified URI.
        /// </summary>
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            prefix = prefix.ToLower();

            if (webRequestCreators.ContainsKey(prefix))
            {
                return(false);
            }

            webRequestCreators.Add(prefix, creator);

            return(true);
        }
Ejemplo n.º 15
0
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            bool flag = false;

            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }
            ExceptionHelper.WebPermissionUnrestricted.Demand();
            lock (InternalSyncObject)
            {
                Uri       uri;
                ArrayList list = (ArrayList)PrefixList.Clone();
                if (Uri.TryCreate(prefix, UriKind.Absolute, out uri))
                {
                    string absoluteUri = uri.AbsoluteUri;
                    if (!prefix.EndsWith("/", StringComparison.Ordinal) && uri.GetComponents(UriComponents.Fragment | UriComponents.PathAndQuery, UriFormat.UriEscaped).Equals("/"))
                    {
                        absoluteUri = absoluteUri.Substring(0, absoluteUri.Length - 1);
                    }
                    prefix = absoluteUri;
                }
                int index = 0;
                while (index < list.Count)
                {
                    WebRequestPrefixElement element = (WebRequestPrefixElement)list[index];
                    if (prefix.Length > element.Prefix.Length)
                    {
                        break;
                    }
                    if ((prefix.Length == element.Prefix.Length) && (string.Compare(element.Prefix, prefix, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        flag = true;
                        break;
                    }
                    index++;
                }
                if (!flag)
                {
                    list.Insert(index, new WebRequestPrefixElement(prefix, creator));
                    PrefixList = list;
                }
            }
            return(!flag);
        }
Ejemplo n.º 16
0
		public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
		{
			if (prefix == null)
				throw new ArgumentNullException ("prefix");
			if (creator == null)
				throw new ArgumentNullException ("creator");
			
			lock (prefixes.SyncRoot) {
				string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
				if (prefixes.Contains (lowerCasePrefix))
					return false;
				prefixes.Add (lowerCasePrefix, creator);
			}
			return true;
		}
Ejemplo n.º 17
0
        public void BrowserHttp()
        {
            IWebRequestCreate wrc = WebRequestCreator.BrowserHttp;

            Assert.AreEqual(wrc.GetType().ToString(), "System.Net.Browser.BrowserHttpWebRequestCreator", "Type");

            WebRequest wr = wrc.Create(Uri);

            Assert.AreEqual(wr.GetType().ToString(), "System.Net.Browser.BrowserHttpWebRequest", "Type");

            Assert.AreSame(wrc, wr.CreatorInstance, "CreatorInstance");

            // default so we don't register it - since we can do so only one time!
            // Assert.IsTrue (WebRequest.RegisterPrefix ("http://", WebRequestCreator.BrowserHttp), "RegisterPrefix");
        }
Ejemplo n.º 18
0
        public void RegisterCustomPrefix()
        {
            IWebRequestCreate creator = (IWebRequestCreate) new ConcreteWebRequest();

            Assert.IsTrue(WebRequest.RegisterPrefix("httpx", creator), "httpx-1");
            Assert.IsFalse(WebRequest.RegisterPrefix("httpx", creator), "httpx-2");

            Uri        httpx = new Uri("httpx://localhost/x");
            WebRequest wr    = WebRequest.Create(httpx);

            Assert.AreEqual("httpx://localhost/x", wr.RequestUri.OriginalString, "RequestUri");
            Assert.IsTrue(wr is ConcreteWebRequest, "ConcreteWebRequest");

            Assert.Throws <NotSupportedException> (delegate {
                WebRequest.CreateHttp(httpx);
            }, "httpx");
        }
Ejemplo n.º 19
0
        public static WebRequest Create(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (!uri.IsAbsoluteUri)
            {
                throw new InvalidOperationException("Uri is not absolute.");
            }

            IWebRequestCreate creator = null;

            // first we look if a domain is registred
            string scheme = uri.Scheme + Uri.SchemeDelimiter;
            string domain = scheme + uri.DnsSafeHost;

            if (!registred_prefixes.TryGetValue(domain, out creator))
            {
                // next we look if the protocol is registred (the delimiter '://' is important)
                if (!registred_prefixes.TryGetValue(scheme, out creator))
                {
                    scheme = uri.Scheme;                     // without the delimiter
                    // then we default to SL
                    switch (scheme)
                    {
                    case "http":
                    case "https":
                        creator = default_creator;
                        break;

                    default:
                        registred_prefixes.TryGetValue(scheme, out creator);
                        break;
                    }
                }
            }

            if (creator == null)
            {
                throw new NotSupportedException(string.Format("Scheme {0} not supported", scheme));
            }

            return(creator.Create(uri));
        }
Ejemplo n.º 20
0
        public static WebRequest Create(Uri requestUri)
        {
            if (requestUri == null)
            {
                throw new ArgumentNullException("requestUri");
            }
            if (!requestUri.IsAbsoluteUri)
            {
                throw new InvalidOperationException("This operation is not supported for a relative URI.");
            }

            IWebRequestCreate creator = null;
            int n = -1;

            // look for the most promising match in the registred prefixes
            foreach (KeyValuePair <string, IWebRequestCreate> kvp in registred_prefixes)
            {
                string key = kvp.Key;
                if ((key.Length > n) && requestUri.AbsoluteUri.StartsWith(key))
                {
                    creator = kvp.Value;
                    n       = key.Length;
                }
            }

            // 'http:/[/]' or 'https:/[/]' needs to be registred otherwise it gets ignored
            // note that this is unlike other protocols (e.g. 'ftp') - see unit tests
            string scheme = requestUri.Scheme;

            if ((scheme == "http" && n <= 5) || (scheme == "https" && n <= 6))
            {
                creator = default_creator;
            }

            if (creator == null)
            {
                throw new NotSupportedException(string.Format("Scheme {0} not supported", scheme));
            }

            return(creator.Create(requestUri));
        }
Ejemplo n.º 21
0
 /// <summary>Registers a <see cref="T:System.Net.WebRequest" /> descendant for the specified URI.</summary>
 /// <returns>true if registration is successful; otherwise, false.</returns>
 /// <param name="prefix">The complete URI or URI prefix that the <see cref="T:System.Net.WebRequest" /> descendant services. </param>
 /// <param name="creator">The create method that the <see cref="T:System.Net.WebRequest" /> calls to create the <see cref="T:System.Net.WebRequest" /> descendant. </param>
 /// <exception cref="T:System.ArgumentNullException">
 ///   <paramref name="prefix" /> is null-or- <paramref name="creator" /> is null. </exception>
 /// <PermissionSet>
 ///   <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
 ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
 ///   <IPermission class="System.Net.WebPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
 /// </PermissionSet>
 public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
 {
     if (prefix == null)
     {
         throw new ArgumentNullException("prefix");
     }
     if (creator == null)
     {
         throw new ArgumentNullException("creator");
     }
     lock (prefixes.SyncRoot)
     {
         string key = prefix.ToLower(CultureInfo.InvariantCulture);
         if (prefixes.Contains(key))
         {
             return(false);
         }
         prefixes.Add(key, creator);
     }
     return(true);
 }
Ejemplo n.º 22
0
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }

            // LAMESPEC: according to doc registering http or https will fail. Actually this is not true
            // the registration works but the class being registred won't be used for http[s]
            if (registred_prefixes.ContainsKey(prefix))
            {
                return(false);
            }

            registred_prefixes.Add(prefix, creator);
            return(true);
        }
        /// <summary>
        /// Replaces the default <see cref="IWebRequestCreate"/> for "http://" and
        /// "https:// urls with a custom <see cref="IWebRequestCreate"/>, such as
        /// <see cref="HttpWebRequestWrapperInterceptorCreator"/> or <see cref="HttpWebRequestWrapperRecorderCreator"/>.
        /// This will also hook into new <see cref="WebClient"/>s and <see cref="HttpClient"/>s!
        /// <para />
        /// After creating a <see cref="HttpWebRequestWrapperSession"/>, any code that uses
        /// <see cref="WebRequest.Create(System.Uri)"/>, new <see cref="WebClient"/>() or
        /// new <see cref="HttpClient"/>() will receive a custom <see cref="HttpWebRequest"/>
        /// built by the passed <see cref="IWebRequestCreate"/>.
        /// <para />
        /// This works by both hijacking <see cref="M:WebRequest.PrefixList"/>
        /// and using <see cref="TaskSchedulerProxy"/> and
        /// <see cref="HttpClientHandlerStartRequestTaskVisitor"/> to intercept
        /// <see cref="System.Net.Http.HttpClient"/> before it begins processing a
        /// <see cref="HttpWebRequest"/> / <see cref="HttpRequestMessage"/>
        /// <para />
        /// NOTE: This technique is only able to support <see cref="System.Net.Http.HttpClient"/>
        /// that are using a <see cref="HttpMessageHandler"/> that derives from
        /// <see cref="HttpClientHandler"/>.  If you are using a purely custom
        /// <see cref="HttpMessageHandler"/>, this class will not intercept
        /// http requests, you'd need to change how your <see cref="System.Net.Http.HttpClient"/>s
        /// are built to fallback to using the default <see cref="HttpClientHandler"/> for
        /// test runs.
        /// <para />
        /// Calling <see cref="Dispose"/> will reset reset the <see cref="M:WebRequest.PrefixList"/>
        /// and the <see cref="TaskScheduler.Default"/>; restoring default behavior.
        /// <para />
        /// See <see cref="HttpWebRequestWrapperSession"/> for more information on
        /// how the <see cref="IWebRequestCreate"/> process is intercepted.
        /// <para />
        /// NOTE: This class does not support concurrency.  It relies on manipulating a static field
        /// (<see cref="TaskScheduler.Default"/> and <see cref="M:WebRequest.PrefixList"/>).
        /// You can only create one Session at a time for a given
        /// App Domain. However, you can run concurrent code within the Session.
        /// </summary>
        public HttpWebRequestWrapperSession(IWebRequestCreate httpRequestCreator)
        {
            _originalWebRequestPrefixList = WebRequestReflectionExtensions.GetWebRequestPrefixList();

            WebRequest.RegisterPrefix("http://", httpRequestCreator);
            WebRequest.RegisterPrefix("https://", httpRequestCreator);

            _defaultTaskScheduler = TaskScheduler.Current;

            // replace the default TaskScheduler.Default with a custom
            // proxy that's wired up with the HttpClientHandlerStartRequestTaskVisitor
            var httpClientInterceptorTaskScheduler =
                new TaskSchedulerProxy(
                    new IVisitTaskOnSchedulerQueue[]
            {
                new HttpClientHandlerStartRequestTaskVisitor.DotNet45AndEarlierStrategy(),
                new HttpClientHandlerStartRequestTaskVisitor.DotNet47Strategy()
            },
                    TaskScheduler.Current);

            httpClientInterceptorTaskScheduler.SetAsDefaultTaskScheduler();
        }
Ejemplo n.º 24
0
        public void ClientHttp()
        {
            IWebRequestCreate wrc = WebRequestCreator.ClientHttp;

            Assert.AreEqual(wrc.GetType().ToString(), "System.Net.Browser.ClientHttpWebRequestCreator", "Type");

            WebRequest wr = wrc.Create(Uri);

            Assert.AreEqual(wr.GetType().ToString(), "System.Net.Browser.ClientHttpWebRequest", "Type");
            Assert.AreSame(wrc, wr.CreatorInstance, "CreatorInstance");

            // we use 'https' instead of 'http' to avoid messing with other tests

            // registering 'https:' is not valid
            Assert.IsFalse(WebRequest.RegisterPrefix("https:", WebRequestCreator.ClientHttp), "RegisterPrefix-https:");

            // registering 'https' is not good enough
            Assert.IsTrue(WebRequest.RegisterPrefix("https", WebRequestCreator.ClientHttp), "RegisterPrefix-https");
            wr = WebRequest.Create("https://www.mono-project.com");
            Assert.AreSame(WebRequestCreator.BrowserHttp, wr.CreatorInstance, "WebRequest.Create(string)-https");

            // you need to register 'https:/'
            Assert.IsTrue(WebRequest.RegisterPrefix("https:/", WebRequestCreator.ClientHttp), "RegisterPrefix-https:/");
            wr = WebRequest.Create("https://www.mono-project.com");
            Assert.AreSame(WebRequestCreator.ClientHttp, wr.CreatorInstance, "WebRequest.Create(string)-https");

            // or register 'https://'
            Assert.IsTrue(WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp), "RegisterPrefix-https://");
            wr = WebRequest.Create("https://www.mono-project.com");
            Assert.AreSame(WebRequestCreator.ClientHttp, wr.CreatorInstance, "WebRequest.Create(string)-https://");

            // we cannot register twice (e.g. go back to Browser)
            Assert.IsFalse(WebRequest.RegisterPrefix("https://", WebRequestCreator.BrowserHttp), "RegisterPrefix-https://-2");
            wr = WebRequest.Create(new Uri("https://www.mono-project.com"));
            Assert.AreSame(WebRequestCreator.ClientHttp, wr.CreatorInstance, "WebRequest.Create(Uri)-https://");

            // we cannot register twice (even with the same, Client, value)
            Assert.IsFalse(WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp), "RegisterPrefix-https://-2");
        }
Ejemplo n.º 25
0
        public void RegisterPrefix()
        {
            IWebRequestCreate creator = (IWebRequestCreate) new ConcreteWebRequest();

            Assert.Throws <ArgumentNullException> (delegate {
                WebRequest.RegisterPrefix(null, creator);
            }, "null,creator");
            Assert.Throws <ArgumentNullException> (delegate {
                WebRequest.RegisterPrefix("ftp", null);
            }, "ftp,null");

            Assert.Throws <NotSupportedException> (delegate {
                WebRequest.Create("ftp://ftp.novell.com");
            }, "ftp-unregistred");

            Assert.IsTrue(WebRequest.RegisterPrefix(String.Empty, creator), "Empty");
            Assert.AreEqual(creator.GetType(), WebRequest.Create("ftp://ftp.novell.com").GetType(), "empty registred");

            Assert.IsTrue(WebRequest.RegisterPrefix("ftp", new Ftp()), "ftp-1");
            Assert.AreEqual(typeof(Ftp), WebRequest.Create("ftp://ftp.novell.com").GetType(), "ftp registred");

            // not twice
            Assert.IsFalse(WebRequest.RegisterPrefix("ftp", creator), "ftp-2");
            // not case sensitive
            Assert.IsFalse(WebRequest.RegisterPrefix("FTP", creator), "ftp-3");

            // "ftp:" is not considered identical
            Assert.IsTrue(WebRequest.RegisterPrefix("ftp:", new FtpColon()), "ftp:");
            Assert.AreEqual(typeof(FtpColon), WebRequest.Create("ftp://ftp.novell.com").GetType(), "ftp: registred");

            // "ftp:/" is also not considered identical
            Assert.IsTrue(WebRequest.RegisterPrefix("ftp:/", new FtpColonSlash()), "ftp:/");
            Assert.AreEqual(typeof(FtpColonSlash), WebRequest.Create("ftp://ftp.novell.com").GetType(), "ftp:/ registred");

            // "ftp://" is also not considered identical
            Assert.IsTrue(WebRequest.RegisterPrefix("ftp://", new FtpColonSlashSlash()), "ftp://");
            Assert.AreEqual(typeof(FtpColonSlashSlash), WebRequest.Create("ftp://ftp.novell.com").GetType(), "ftp:// registred");
        }
Ejemplo n.º 26
0
        public void CustomIsolatedStorageWebRequest()
        {
            IWebRequestCreate creator = (IWebRequestCreate) new IsolatedStorageWebRequest();

            Assert.IsTrue(WebRequest.RegisterPrefix("iso", creator), "iso-1");
            Assert.IsFalse(WebRequest.RegisterPrefix("iso", creator), "iso-2");

            WebRequest wr = WebRequest.Create(new Uri("iso://site/data.log"));

            wr.Method = "SAVE";

            IAsyncResult result = wr.BeginGetRequestStream(null, String.Empty);

            result.AsyncWaitHandle.WaitOne();
            Stream s = wr.EndGetRequestStream(result);

            using (StreamWriter sw = new StreamWriter(s)) {
                sw.WriteLine("hello");
            }

            result = wr.BeginGetResponse(null, String.Empty);
            result.AsyncWaitHandle.WaitOne();
            Assert.IsNull(wr.EndGetResponse(result), "Response-Write");

            wr.Method = "LOAD";
            // should be in response but that would require a lot of extra code ;-)
            result = wr.BeginGetRequestStream(null, String.Empty);
            result.AsyncWaitHandle.WaitOne();
            s = wr.EndGetRequestStream(result);

            using (StreamReader sr = new StreamReader(s)) {
                Assert.IsTrue(sr.ReadToEnd().StartsWith("hello"), "ReadToEnd");
            }

            result = wr.BeginGetResponse(null, String.Empty);
            result.AsyncWaitHandle.WaitOne();
            Assert.IsNull(wr.EndGetResponse(result), "Response-Read");
        }
Ejemplo n.º 27
0
	public static bool RegisterPrefix(String prefix, IWebRequestCreate creator)
	{
		if (prefix== null)
		{
			throw new ArgumentNullException("prefix", S._("Arg_NotNull"));
		}

		if (creator== null)
		{
			throw new ArgumentNullException("creator", S._("Arg_NotNull"));
		}

		if(prefixes.Contains( prefix.ToLower() ))
		{
			return false;
		}
		else
		{
			prefixes.Add(prefix.ToLower(), creator);
		}
			
		return true;
	}
Ejemplo n.º 28
0
        public void ReRegisterHttp()
        {
            IWebRequestCreate creator = (IWebRequestCreate) new ConcreteWebRequest();

            // according to documentation we cannot register something else for http
            // because it would "fail" since they are already "sysetm registered".
            // however it seems no one told the API
            Assert.IsTrue(WebRequest.RegisterPrefix("http://", creator), "http-1");
            // but you can't register twice (like any other)
            Assert.IsFalse(WebRequest.RegisterPrefix("http://", creator));

            Uri        uri = new Uri("http://localhost/");
            WebRequest wr  = WebRequest.Create(uri);

            Assert.AreEqual("http://localhost/", wr.RequestUri.OriginalString, "RequestUri");
            Assert.IsTrue(wr is ConcreteWebRequest, "ConcreteWebRequest");
            Assert.IsNull(wr.CreatorInstance, "CreatorInstance");

            // CreateHttp is unaffected by the RegisterPrefix method
            HttpWebRequest hwr = WebRequest.CreateHttp(uri);

            Assert.AreEqual("http://localhost/", hwr.RequestUri.OriginalString, "CreateHttp-RequestUri");
            Assert.AreEqual("System.Net.Browser.ClientHttpWebRequestCreator", hwr.CreatorInstance.GetType().ToString(), "CreateHttp-CreatorInstance");
        }
Ejemplo n.º 29
0
        public LastfmRequest(string method, RequestType request_type, ResponseFormat response_format)
        {
            this.method = method;
            this.request_type = request_type;
            this.response_format = response_format;
            if (this.web_request_creator == null) {
                this.web_request_creator = new WebRequestCreator ();
            }

            Init ();
        }
 public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
 {
   return default(bool);
 }
Ejemplo n.º 31
0
		public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
		{
			if (prefix == null)
				throw new ArgumentNullException ("prefix");
			if (creator == null)
				throw new ArgumentNullException ("creator");
			
			lock (prefixes.SyncRoot) {
				string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
				if (prefixes.Contains (lowerCasePrefix))
					return false;
				prefixes.Add (lowerCasePrefix, creator);
			}
			return true;
		}
Ejemplo n.º 32
0
 public CcTrayProvider(IWebRequestCreate webRequestCreate, IClock clock)
 {
     this.webRequestCreate = webRequestCreate;
     this.clock = clock;
 }
Ejemplo n.º 33
0
 public static void RegisterPortableWebRequestCreator(IWebRequestCreate creator)
 {
 }
        /// <summary>
        /// Registers a <itemref>WebRequest</itemref> descendant for the
        /// specified URI.
        /// </summary>
        /// <param name="prefix">The complete URI or URI prefix that the
        /// <itemref>WebRequest</itemref> descendant services.</param>
        /// <param name="creator">The create method that the
        /// <itemref>WebRequest</itemref> calls to create the
        /// <itemref>WebRequest</itemref> descendant.</param>
        /// <returns><itemref>true</itemref>.</returns>
        public static bool RegisterPrefix(string prefix,
                                  IWebRequestCreate creator)
        {
            if (prefix == null || creator == null) { throw new ArgumentNullException(); }

            // Changes prefix to lower becuase it is case insensitive.
            prefix = prefix.ToLower();
            lock (g_listLock)
            {
                // Iterate over list of prefixes and checks if this one is
                // already present.
                for (int i = 0; i < s_PrefixList.Count; i++)
                {
                    if (((WebRequestPrefixElement)s_PrefixList[i]).Prefix == prefix)
                    {
                        return false;
                    }
                }

                // This is a new prefix, add it.
                s_PrefixList.Add(new WebRequestPrefixElement(prefix, creator));
            }

            return true;
        }
Ejemplo n.º 35
0
 public WebRequestPrefixElement(string P, IWebRequestCreate C)
 {
     Prefix = P;
     Creator = C;
 }
Ejemplo n.º 36
0
        /*++

            RegisterPrefix - Register an Uri prefix for creating WebRequests.

            This function registers a prefix for creating WebRequests. When an
            user wants to create a WebRequest, we scan a table looking for a
            longest prefix match for the Uri they're passing. We then invoke
            the sub creator for that prefix. This function puts entries in
            that table.

            We don't allow duplicate entries, so if there is a dup this call
            will fail.

        Input:

            Prefix           - Represents Uri prefix being registered.
            Creator         - Interface for sub creator.

        Returns:

            True if the registration worked, false otherwise.

        --*/
        /// <include file='doc\WebRequest.uex' path='docs/doc[@for="WebRequest.RegisterPrefix"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Registers a <see cref='System.Net.WebRequest'/> descendent
        ///       for a specific Uniform Resource Identifier.
        ///    </para>
        /// </devdoc>
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) {

            bool Error = false;
            int i;
            WebRequestPrefixElement Current;

            if (prefix == null) {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null) {
                throw new ArgumentNullException("creator");
            }

            // Lock this object, then walk down PrefixList looking for a place to
            // to insert this prefix.

            lock(typeof(WebRequest)) {
                //
                // clone the object and update the clone thus
                // allowing other threads to still read from it
                //

                ArrayList prefixList = (ArrayList) PrefixList.Clone();

                i = 0;

                // The prefix list is sorted with longest entries at the front. We
                // walk down the list until we find a prefix shorter than this
                // one, then we insert in front of it. Along the way we check
                // equal length prefixes to make sure this isn't a dupe.

                while (i < prefixList.Count) {
                    Current = (WebRequestPrefixElement)prefixList[i];

                    // See if the new one is longer than the one we're looking at.

                    if (prefix.Length > Current.Prefix.Length) {
                        // It is. Break out of the loop here.
                        break;
                    }

                    // If these are of equal length, compare them.

                    if (prefix.Length == Current.Prefix.Length) {
                        // They're the same length.
                        if (String.Compare(Current.Prefix, prefix, true, CultureInfo.InvariantCulture) == 0) {
                            // ...and the strings are identical. This is an error.

                            Error = true;
                            break;
                        }
                    }
                    i++;
                }

                // When we get here either i contains the index to insert at or
                // we've had an error, in which case Error is true.

                if (!Error) {
                    // No error, so insert.

                    prefixList.Insert(i,
                                        new WebRequestPrefixElement(prefix, creator)
                                       );

                    //
                    // no error, assign the clone to the static object, other
                    // threads using it will have copied the oriignal object already
                    //
                    PrefixList = prefixList;
                }


            }
            return !Error;
        }
Ejemplo n.º 37
0
 public static void RegisterPortableWebRequestCreator(IWebRequestCreate creator) { }       
 public WebRequestPrefixElement(string P, IWebRequestCreate C)
 {
     this.Prefix = P;
     this.Creator = C;
 }
 public PersonalBuildsTeamCity6UpdateStrategy(IWebRequestCreate webRequestCreate, IClock clock, ILog log)
 {
     this.webRequestCreate = webRequestCreate;
     this.clock = clock;
     this.log = log;
 }
Ejemplo n.º 40
0
 public HudsonProvider(IWebRequestCreate webRequestCreate, IClock clock)
 {
     this.webRequestCreate = webRequestCreate;
     this.clock = clock;
 }
Ejemplo n.º 41
0
 public WebRequestPrefixElement(string prefix, IWebRequestCreate creator)
 {
     Prefix = prefix;
     Creator = creator;
 }
 public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
 {
     bool flag = false;
     if (prefix == null)
     {
         throw new ArgumentNullException("prefix");
     }
     if (creator == null)
     {
         throw new ArgumentNullException("creator");
     }
     ExceptionHelper.WebPermissionUnrestricted.Demand();
     lock (InternalSyncObject)
     {
         Uri uri;
         ArrayList list = (ArrayList) PrefixList.Clone();
         if (Uri.TryCreate(prefix, UriKind.Absolute, out uri))
         {
             string absoluteUri = uri.AbsoluteUri;
             if (!prefix.EndsWith("/", StringComparison.Ordinal) && uri.GetComponents(UriComponents.Fragment | UriComponents.PathAndQuery, UriFormat.UriEscaped).Equals("/"))
             {
                 absoluteUri = absoluteUri.Substring(0, absoluteUri.Length - 1);
             }
             prefix = absoluteUri;
         }
         int index = 0;
         while (index < list.Count)
         {
             WebRequestPrefixElement element = (WebRequestPrefixElement) list[index];
             if (prefix.Length > element.Prefix.Length)
             {
                 break;
             }
             if ((prefix.Length == element.Prefix.Length) && (string.Compare(element.Prefix, prefix, StringComparison.OrdinalIgnoreCase) == 0))
             {
                 flag = true;
                 break;
             }
             index++;
         }
         if (!flag)
         {
             list.Insert(index, new WebRequestPrefixElement(prefix, creator));
             PrefixList = list;
         }
     }
     return !flag;
 }
Ejemplo n.º 43
0
		// We can register for
		// * a protocol (e.g. http) for all requests
		// * a protocol (e.g. https) for a domain
		// * a protocol (e.g. http) for a single request
		//
		// See "How to: Specify Browser or Client HTTP Handling" for more details
		// http://msdn.microsoft.com/en-us/library/dd920295%28VS.95%29.aspx
		public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
		{
			if (prefix == null)
				throw new ArgumentNullException ("prefix");
			if (creator == null)
				throw new ArgumentNullException ("creator");

			Uri uri;
			if (Uri.TryCreate (prefix, UriKind.Absolute, out uri)) {
				// if a valid URI is supplied then only register the scheme + domain
				prefix = uri.Scheme + Uri.SchemeDelimiter + uri.DnsSafeHost;
			}

			if (registred_prefixes.ContainsKey (prefix))
				return false;

			registred_prefixes.Add (prefix, creator);
			return true;
		}
 public WebRequestPrefixElement(string P, IWebRequestCreate C)
 {
     Prefix  = P;
     Creator = C;
 }
		internal static void RegisterDefaultStack (IWebRequestCreate creator)
		{
			default_creator = creator;
		}
Ejemplo n.º 46
0
        // RegisterPrefix - Register an Uri prefix for creating WebRequests.
        //
        // This function registers a prefix for creating WebRequests. When an
        // user wants to create a WebRequest, we scan a table looking for a
        // longest prefix match for the Uri they're passing. We then invoke
        // the sub creator for that prefix. This function puts entries in
        // that table.
        //
        // We don't allow duplicate entries, so if there is a dup this call
        // will fail.
        //
        // Input:
        //     Prefix  - Represents Uri prefix being registered.
        //     Creator - Interface for sub creator.
        //
        // Returns:
        //     True if the registration worked, false otherwise.
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            bool Error = false;
            int i;
            WebRequestPrefixElement Current;

            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }

            // Lock this object, then walk down PrefixList looking for a place to
            // to insert this prefix.
            lock (s_internalSyncObject)
            {
                // Clone the object and update the clone, thus
                // allowing other threads to still read from the original.
                List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(PrefixList);

                // As AbsoluteUri is used later for Create, account for formating changes 
                // like Unicode escaping, default ports, etc.
                Uri tempUri;
                if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
                {
                    String cookedUri = tempUri.AbsoluteUri;

                    // Special case for when a partial host matching is requested, drop the added trailing slash
                    // IE: http://host could match host or host.domain
                    if (!prefix.EndsWith("/", StringComparison.Ordinal)
                        && tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped)
                            .Equals("/"))
                    {
                        cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
                    }

                    prefix = cookedUri;
                }

                i = 0;

                // The prefix list is sorted with longest entries at the front. We
                // walk down the list until we find a prefix shorter than this
                // one, then we insert in front of it. Along the way we check
                // equal length prefixes to make sure this isn't a dupe.
                while (i < prefixList.Count)
                {
                    Current = prefixList[i];

                    // See if the new one is longer than the one we're looking at.
                    if (prefix.Length > Current.Prefix.Length)
                    {
                        // It is. Break out of the loop here.
                        break;
                    }

                    // If these are of equal length, compare them.
                    if (prefix.Length == Current.Prefix.Length)
                    {
                        // They're the same length.
                        if (String.Compare(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // ...and the strings are identical. This is an error.
                            Error = true;
                            break;
                        }
                    }
                    i++;
                }

                // When we get here either i contains the index to insert at or
                // we've had an error, in which case Error is true.
                if (!Error)
                {
                    // No error, so insert.
                    prefixList.Insert(i, new WebRequestPrefixElement(prefix, creator));

                    // Assign the clone to the static object. Other threads using it
                    // will have copied the original object already.
                    PrefixList = prefixList;
                }
            }
            return !Error;
        }
 public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
 {
 }
Ejemplo n.º 48
0
        /*++
         *
         *  RegisterPrefix - Register an Uri prefix for creating WebRequests.
         *
         *  This function registers a prefix for creating WebRequests. When an
         *  user wants to create a WebRequest, we scan a table looking for a
         *  longest prefix match for the Uri they're passing. We then invoke
         *  the sub creator for that prefix. This function puts entries in
         *  that table.
         *
         *  We don't allow duplicate entries, so if there is a dup this call
         *  will fail.
         *
         * Input:
         *
         *  Prefix           - Represents Uri prefix being registered.
         *  Creator         - Interface for sub creator.
         *
         * Returns:
         *
         *  True if the registration worked, false otherwise.
         *
         * --*/
        /// <devdoc>
        ///    <para>
        ///       Registers a <see cref='System.Net.WebRequest'/> descendent
        ///       for a specific Uniform Resource Identifier.
        ///    </para>
        /// </devdoc>
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            bool Error = false;
            int  i;
            WebRequestPrefixElement Current;

            if (prefix == null)
            {
                throw new ArgumentNullException("prefix");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }

#if FEATURE_MONO_CAS
            ExceptionHelper.WebPermissionUnrestricted.Demand();
#endif

            // Lock this object, then walk down PrefixList looking for a place to
            // to insert this prefix.

            lock (InternalSyncObject) {
                //
                // clone the object and update the clone thus
                // allowing other threads to still read from it
                //

                ArrayList prefixList = (ArrayList)PrefixList.Clone();

                // As AbsoluteUri is used later for Create, account for formating changes
                // like Unicode escaping, default ports, etc.
                Uri tempUri;
                if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
                {
                    String cookedUri = tempUri.AbsoluteUri;

                    // Special case for when a partial host matching is requested, drop the added trailing slash
                    // IE: http://host could match host or host.domain
                    if (!prefix.EndsWith("/", StringComparison.Ordinal) &&
                        tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment,
                                              UriFormat.UriEscaped)
                        .Equals("/"))
                    {
                        cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
                    }

                    prefix = cookedUri;
                }

                i = 0;

                // The prefix list is sorted with longest entries at the front. We
                // walk down the list until we find a prefix shorter than this
                // one, then we insert in front of it. Along the way we check
                // equal length prefixes to make sure this isn't a dupe.

                while (i < prefixList.Count)
                {
                    Current = (WebRequestPrefixElement)prefixList[i];

                    // See if the new one is longer than the one we're looking at.

                    if (prefix.Length > Current.Prefix.Length)
                    {
                        // It is. Break out of the loop here.
                        break;
                    }

                    // If these are of equal length, compare them.

                    if (prefix.Length == Current.Prefix.Length)
                    {
                        // They're the same length.
                        if (String.Compare(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            // ...and the strings are identical. This is an error.

                            Error = true;
                            break;
                        }
                    }
                    i++;
                }

                // When we get here either i contains the index to insert at or
                // we've had an error, in which case Error is true.

                if (!Error)
                {
                    // No error, so insert.

                    prefixList.Insert(i,
                                      new WebRequestPrefixElement(prefix, creator)
                                      );

                    //
                    // no error, assign the clone to the static object, other
                    // threads using it will have copied the oriignal object already
                    //
                    PrefixList = prefixList;
                }
            }
            return(!Error);
        }
 public bool RegisterPrefix(string prefix, IWebRequestCreate creator)
 {
     return System.Net.WebRequest.RegisterPrefix(prefix, creator);
 }
Ejemplo n.º 50
0
		// We can register for
		// * a protocol (e.g. http) for all requests
		// * a protocol (e.g. https) for a domain
		// * a protocol (e.g. http) for a single request
		//
		// See "How to: Specify Browser or Client HTTP Handling" for more details
		// http://msdn.microsoft.com/en-us/library/dd920295%28VS.95%29.aspx
		public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
		{
			if (prefix == null)
				throw new ArgumentNullException ("prefix");
			if (creator == null)
				throw new ArgumentNullException ("creator");

			Uri uri;
			if (Uri.TryCreate (prefix, UriKind.Absolute, out uri)) {
				// if a valid URI is supplied then only register the scheme + domain
				prefix = uri.Scheme + Uri.SchemeDelimiter + uri.DnsSafeHost;
			}

			// registering 'http', 'http://' or even 'http:/' are all ok - but *never* would 'http:' be correct!
			if ((String.Compare (prefix, "http:", StringComparison.OrdinalIgnoreCase) == 0) ||
			    (String.Compare (prefix, "https:", StringComparison.OrdinalIgnoreCase) == 0))
				return false;

			if (registred_prefixes.ContainsKey (prefix))
				return false;

			registred_prefixes.Add (prefix, creator);
			return true;
		}
Ejemplo n.º 51
0
 public ReportRequestBuilder()
 {
     _webRequestFactory = GlobalConfig.ServiceLocator.GetService<IWebRequestCreate>();
 }
Ejemplo n.º 52
0
        /// <summary>
        ///  Registers a WebRequest descendant for the specified URI.
        /// </summary>
        public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
        {
            prefix = prefix.ToLower();

            if (webRequestCreators.ContainsKey(prefix)) return false;
            
            webRequestCreators.Add(prefix, creator);
            
            return true;
        }
Ejemplo n.º 53
0
 internal LastfmRequest(string method, RequestType request_type, ResponseFormat response_format, IWebRequestCreate web_request_creator)
     : this(method, request_type, response_format)
 {
     this.web_request_creator = web_request_creator;
 }
Ejemplo n.º 54
0
 public WebRequestPrefixElement(string prefix, IWebRequestCreate creator)
 {
     Prefix  = prefix;
     Creator = creator;
 }
Ejemplo n.º 55
0
 public virtual bool RegisterPrefix(string prefix, IWebRequestCreate creator)
 {
     return WebRequest.RegisterPrefix(prefix, creator);
 }