GetLeftPart() public method

public GetLeftPart ( UriPartial part ) : string
part UriPartial
return string
		static void createHttpRequest(IFakeAccessor context)
		{
			// MvcContrib.FakeHttpRequest doesn't implement RawUrl.
			var uri = new Uri(_currentUrl);
			context.The<HttpRequestBase>().WhenToldTo(x => x.Url).Return(uri);
			context.The<HttpRequestBase>().WhenToldTo(x => x.RawUrl)
				.Return(uri.AbsoluteUri.Substring(uri.GetLeftPart(UriPartial.Authority).Length));
			// Used by PathHelpers.GenerateClientUrl(...)
			context.The<HttpRequestBase>().WhenToldTo(x => x.ApplicationPath).Return("/");
		}
Beispiel #2
0
        public string Build(Uri uri)
        {
            if (_qs.Count <= 0)
                return uri.GetLeftPart(UriPartial.Path);

            List<string> qs = new List<string>();
            foreach (var kv in _qs.Where(x => !string.IsNullOrEmpty(x.Key)))
                qs.Add(kv.Key + "=" + HttpUtility.UrlEncode(kv.Value));

            if(qs.Count > 0)
                return uri.GetLeftPart(UriPartial.Path) + "?" + string.Join("&", qs);
            else
                return uri.GetLeftPart(UriPartial.Path);
        }
Beispiel #3
0
        private static void Run(string[] args)
        {
            Arguments arguments;
            try
            {
                arguments = Arguments.Parse(args);
            }
            catch (Exception e)
            {
                throw new ArgumentException(string.Format("Error parsing arguments: {0}", e.Message), e);
            }

            string urlString = arguments.Url;

            if (urlString == null)
                throw new ArgumentException("Url to API has to be specified.");

            if (!urlString.StartsWith("http"))
                urlString = "http://" + urlString;

            var url = new Uri(urlString, UriKind.Absolute);
            string baseUrl = url.GetLeftPart(UriPartial.Authority);
            string apiPath = url.AbsolutePath;

            if (apiPath == "/")
                apiPath = "/w/api.php";

            var wiki = new Wiki(baseUrl, apiPath, arguments.Namespace, arguments.PropsFile);
            wiki.AddAllModules();
            wiki.AddAllQueryModules();
            var result = wiki.Compile(arguments.OutputName, arguments.Directory);

            foreach (CompilerError error in result.Errors)
                Console.WriteLine(error);
        }
        public static void GetAdfsConfigurationFromTargetUri(Uri targetApplicationUri, out string adfsHost, out string adfsRelyingParty)
        {
            adfsHost = "";
            adfsRelyingParty = "";

            var trustEndpoint = new Uri(new Uri(targetApplicationUri.GetLeftPart(UriPartial.Authority)), "/_trust/");
            var request = (HttpWebRequest)WebRequest.Create(trustEndpoint);
            request.AllowAutoRedirect = false;

            try
            {
                using (var response = request.GetResponse())
                {
                    var locationHeader = response.Headers["Location"];
                    if (locationHeader != null)
                    {
                        var redirectUri = new Uri(locationHeader);
                        Dictionary<string, string> queryParameters = Regex.Matches(redirectUri.Query, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => Uri.UnescapeDataString(x.Groups[3].Value));
                        adfsHost = redirectUri.Host;
                        adfsRelyingParty = queryParameters["wtrealm"];
                    }
                }
            }
            catch (WebException ex)
            {
                throw new Exception("Endpoint does not use ADFS for authentication.", ex);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogin();

            if (!ClientScript.IsStartupScriptRegistered("JsFunc_DefaultSize"))
                Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc_DefaultSize", "DefaultSize();", true);

            if (!IsPostBack)
            {
                if (Request.UrlReferrer != null)
                {
                    var uri = new Uri(Request.UrlReferrer.ToString());
                    prevPage = uri.GetLeftPart(UriPartial.Path);
                }

                if (Session["Test_dtmember"] != null && prevPage.Contains("/Master/SingleMember.aspx"))
                {
                    if (!ClientScript.IsStartupScriptRegistered("JsFunc_Setsize"))
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc_Setsize", "Setsize();", true);

                    GridViewPlan.DataSource = (DataTable)Session["Test_dtmember"];
                    GridViewPlan.DataBind();
                }

                //Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFun", "DefaultSize()", true);
                DataTable dtFellowship = CobcYouthDAL.GetFellowship();
                dpFellowship.DataSource = dtFellowship;
                dtFellowship.Rows.Add(0, "全部團契");
                dtFellowship.DefaultView.Sort = "FellowshipID";
                dpFellowship.DataValueField = "FellowshipID";
                dpFellowship.DataTextField = "name";
                dpFellowship.DataBind();
            }

        }
Beispiel #6
0
        public static string EncodeUri(Uri uri)
        {

            if (!uri.IsAbsoluteUri)
            {
                var uriString = uri.IsWellFormedOriginalString() ? uri.ToString() : Uri.EscapeUriString(uri.ToString());
                return EscapeReservedCspChars(uriString);
            }

            var host = uri.Host;
            var encodedHost = EncodeHostname(host);

            var needsReplacement = !host.Equals(encodedHost);

            var authority = uri.GetLeftPart(UriPartial.Authority);

            if (needsReplacement)
            {
                authority = authority.Replace(host, encodedHost);
            }

            if (uri.PathAndQuery.Equals("/"))
            {
                return authority;
            }

            return authority + EscapeReservedCspChars(uri.PathAndQuery);
        }
Beispiel #7
0
        public void Should_remove_username_and_password_from_source_address()
        {
            var inputAddress = new Uri("rabbitmq://*****:*****@localhost/mt/test_queue");
            var sourceAddress = new Uri("rabbitmq://localhost/mt/test_queue");
            var future = new Future<IConsumeContext<A>>();

            using (IServiceBus bus = ServiceBusFactory.New(c =>
                {
                    c.ReceiveFrom(inputAddress);
                    c.UseRabbitMq(r =>
                        {
                            r.ConfigureHost(sourceAddress, h =>
                                {
                                    h.SetUsername("testUser");
                                    h.SetPassword("test");
                                });
                        });

                    c.Subscribe(s => s.Handler<A>((context, message) => future.Complete(context)));
                }))
            {
                bus.Publish(new A());

                Assert.IsTrue(future.WaitUntilCompleted(TimeSpan.FromSeconds(8)));
            }

            Assert.AreEqual(sourceAddress.ToString(), future.Value.SourceAddress.ToString());
            Assert.AreEqual(sourceAddress.GetLeftPart(UriPartial.Authority),
                future.Value.DestinationAddress.GetLeftPart(UriPartial.Authority));
        }
        protected override bool HandleRequest(string url, ref byte[] responseBody, ref string[] responseHeaders)
        {
            var uri = new Uri(url);
            var path = uri.GetLeftPart(UriPartial.Path).Replace(Scheme, "");

            if (path.EndsWith("/"))
                path = path.Substring(0, path.Length - 1);

            var stream = OpenFile(path);

            if (stream == null) {
                responseHeaders = new string[] {
                    "HTTP/1.1 404 Not Found"
                };
                return false;
            }

            using (stream) {
                responseBody = new byte[stream.Length];
                stream.Read(responseBody, 0, responseBody.Length);
            }

            var mimeType = SelectMimeType(path);
            responseHeaders = new string[] {
                "HTTP/1.1 200 OK",
                String.Format("Content-type: {0}; charset=utf-8", mimeType)
            };

            return true;
        }
Beispiel #9
0
        public static string Build(string href, Uri uri)
        {
            if (href.StartsWith("http"))
                return href;

            return string.Format("{0}{1}{2}", uri.GetLeftPart(UriPartial.Scheme), uri.Authority, href);
        }
Beispiel #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var uri = new Uri(Request.Url.ToString());
            string path = uri.GetLeftPart(UriPartial.Path);

            if (!(((string)Session["loginName"]) != null && !(((string)Session["loginName"]).Equals(""))))
            {
                post.InnerHtml = "";
            }

            string paramThread = Request.QueryString["thread"];
            if (paramThread != null)
            {
                test.Text += loadThread(Convert.ToInt32(paramThread));
            }
            else
            {
                test.Text = "<div class=\"jumbotron\"><div class=\"container\"><h1>Bienvenue Pirates!</h1><p>C'est le temps de se parler!</p></div></div>";
                test.Text += loadIndex();
                post.InnerHtml = "";
                if (((string)Session["loginName"]) != null && !((string)Session["loginName"]).Equals(""))
                {
                    test.Text += "<h2><a href=\"NewThread.aspx\">Créer un nouveau sujet!</a></h2>";
                }

            }
        }
Beispiel #11
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            // No checking of password for this sample.  Just care about the username
            // as that's what we're including in the token to send back to the authorization server

            // Corresponds to shared secret the authorization server knows about for this resource
            const string encryptionKey = "WebAPIsAreAwesome";

            // Build token with info the authorization server needs to know
            var tokenContent = model.UserName + ";" + DateTime.Now.ToString(CultureInfo.InvariantCulture) + ";" + model.RememberMe;
            var encryptedToken = EncodingUtility.Encode(tokenContent, encryptionKey);

            // Redirect back to the authorization server, including the authentication token
            // Name of authentication token corresponds to that known by the authorization server
            returnUrl += (returnUrl.Contains("?") ? "&" : "?");
            returnUrl += "resource-authentication-token=" + encryptedToken;
            var url = new Uri(returnUrl);
            var redirectUrl = url.ToString();

            // URL Encode the values of the querystring parameters
            if (url.Query.Length > 1)
            {
                var helper = new UrlHelper(HttpContext.Request.RequestContext);
                var qsParts = HttpUtility.ParseQueryString(url.Query);
                redirectUrl = url.GetLeftPart(UriPartial.Path) + "?" + String.Join("&",qsParts.AllKeys.Select(x => x + "=" + helper.Encode(qsParts[x])));
            }

            return Redirect(redirectUrl);
        }
Beispiel #12
0
        public static bool TranslateHref(string pageURL, string href, out string translatedURL)
        {
            string lwhref = LowerString(href);
            var opageurl = new Uri(pageURL);
            Uri otranslatedurl = null;
            translatedURL = null;

            if (string.IsNullOrEmpty(href))
            {
                return false;
            }

            if (lwhref.StartsWith("//", StringComparison.InvariantCultureIgnoreCase))
            {
                translatedURL = opageurl.Scheme + ":" + href;
            }
            else if (lwhref.StartsWith("http", StringComparison.InvariantCultureIgnoreCase) || lwhref.StartsWith("https", StringComparison.InvariantCultureIgnoreCase))
            {
                translatedURL = href;
            }
            else
            {
                translatedURL = opageurl.GetLeftPart(UriPartial.Authority);
                if(!href.StartsWith("/"))
                {
                    translatedURL += "/";
                }

                translatedURL += href;
            }

            return Uri.TryCreate(translatedURL, UriKind.Absolute, out otranslatedurl);
        }
        public static string DownloadImage(string urlImage, string fileName)
        {
            string remoteImgPath = urlImage;
            try
            {
                var remoteImgPathUri = new Uri(remoteImgPath);
                string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
                string fileExtension = Path.GetExtension(remoteImgPathWithoutQuery); // .jpg, .png

                string folder = DateTime.Now.ToString("yyyyMMdd");
                string uploadPath = AppDomain.CurrentDomain.BaseDirectory + "Images\\I\\" + folder;
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                string localPathFull = AppDomain.CurrentDomain.BaseDirectory + "Images\\I\\" + folder + "\\" + fileName + fileExtension;

                var webClient = new WebClient();
                webClient.DownloadFile(remoteImgPath, localPathFull);
                return "images/I/" + "/" + folder + "/" + fileName + fileExtension;
            }
            catch (Exception ex)
            {
                return ConstantManager.DefaultImage;
            }
        }
Beispiel #14
0
        public static String FormatAbsoluteUrl(String relativeUrl, String baseUrl)
        {
            if (relativeUrl.Contains("http"))
            {
                return relativeUrl;
            }

            int askIndex = baseUrl.IndexOf('?');
            if (askIndex >= 0)
            {
                baseUrl = baseUrl.Substring(0, askIndex);
            }

            if (relativeUrl.StartsWith("/"))
            {
                Uri baseUri = new Uri(baseUrl);
                return String.Format("{0}{1}", baseUri.GetLeftPart(UriPartial.Authority), relativeUrl);
            }
            else
            {
                if (!baseUrl.EndsWith("/"))
                {
                    baseUrl = String.Format("{0}/", baseUrl);
                }

                Uri baseUri = new Uri(baseUrl);
                return String.Format("{0}{1}", baseUri.GetLeftPart(UriPartial.Path), relativeUrl);
            }            
        }
Beispiel #15
0
		/// <summary>
		/// Return a fake RequestContext that can be used to create a stub UrlHelper
		/// </summary>
		/// <param name="url">Url to fake a request for.</param>
		internal static RequestContext For(string url)
		{
			if (_specificationController == null)
				throw new InvalidOperationException(
					"Test context must inherit 'WithFakes' to use FakeUrlHelper or FakeRequestContext.");

			// MvcContrib.FakeHttpRequest doesn't implement RawUrl.
			var request = An<HttpRequestBase>();
			var uri = new Uri(url);
			request.WhenToldTo(x => x.Url).Return(uri);
			request.WhenToldTo(x => x.RawUrl).Return(uri.AbsoluteUri.Substring(uri.GetLeftPart(UriPartial.Authority).Length));
			// Used by PathHelpers.GenerateClientUrl(...)
			request.WhenToldTo(x => x.ApplicationPath).Return("/");

			var httpContext = An<HttpContextBase>();
			httpContext.WhenToldTo(x => x.Request).Return(request);
			// Used by RouteCollection.GetUrlWithApplicationPath(...)
			httpContext.WhenToldTo(x => x.Response).Return(new FakeHttpResponse());

			var routeData = An<RouteData>();
			var requestContext = An<RequestContext>();
			requestContext.WhenToldTo(x => x.HttpContext).Return(httpContext);
			// Used by UrlHelper.GenerateUrl(...)
			requestContext.WhenToldTo(x => x.RouteData).Return(routeData);

			return requestContext;
		}
        bool TryGetMatchingHost(Uri address, out IServiceBusHost host)
        {
            host = _hosts
                .Where(x => x.Settings.ServiceUri.GetLeftPart(UriPartial.Authority).Equals(address.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase))
                .OrderByDescending(x => address.AbsolutePath.StartsWith(x.Settings.ServiceUri.AbsolutePath, StringComparison.OrdinalIgnoreCase) ? 1 : 0)
                .FirstOrDefault();

            return host != null;
        }
Beispiel #17
0
        public Task Authenticated(GoogleOAuth2AuthenticatedContext context)
        {
            context.Identity.AddClaim(new Claim("external_access_token", context.AccessToken));

            var uri = new Uri(context.User["image"].Value<string>("url"));
            context.Identity.AddClaim(new Claim("picture_url", uri.GetLeftPart(UriPartial.Path)));

            return Task.FromResult<object>(null);
        }
 private static RestClient GetMetadataClient(Uri uri)
 {
     string baseUrl = uri.GetLeftPart(UriPartial.Authority);
     if (__metadataClient == null || !__metadataClient.BaseUrl.Equals(baseUrl)) {
         __metadataClient = new RestClient(baseUrl);
         __metadataClient.UseSynchronizationContext = false;
     }
     return __metadataClient;
 }
Beispiel #19
0
 public Captcha(string key, Uri referer)
 {
     RCKey = key;
     RCRefer = referer;
     wc = new WebClient();
     wc.Headers.Add("Referer: " + RCRefer.GetLeftPart(UriPartial.Authority) + "/");
     wc.Headers.Add("DNT: 1");
     wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17");
 }
        /// <summary>
        /// Resolves a matching <see cref="Localization"/> for a given URL.
        /// </summary>
        /// <param name="url">The URL to resolve.</param>
        /// <returns>A <see cref="Localization"/> instance which base URL matches that of the given URL.</returns>
        /// <exception cref="DxaUnknownLocalizationException">If no matching Localization can be found.</exception>
        public override Localization ResolveLocalization(Uri url)
        {
            using (new Tracer(url))
            {
                string urlLeftPart = url.GetLeftPart(UriPartial.Path);

                // TODO PERF: to optimize caching, we could only take the first part of the URL path (e.g. one or two levels)
                int espaceIndex = urlLeftPart.IndexOf("%");
                if (espaceIndex > 0)
                {
                    // TODO: This is a work-around for a bug in SDL Web 8 Publication Mapping: URLs with escaped characters don't resolve properly (CRQ-1585).
                    // Therefore we truncate the URL at the first escaped character for now (assuming that the URL is still specific enough to resolve the right Publication).
                    urlLeftPart = urlLeftPart.Substring(0, espaceIndex);
                }

                IPublicationMapping mapping = null;
                try
                {
                    // NOTE: we're not using UrlToLocalizationMapping here, because we may match too eagerly on a base URL when there is a matching mapping with a more specific URL.
                    mapping = _mappingsRetriever.GetPublicationMapping(urlLeftPart);
                }
                catch (Exception ex)
                {
                    // CIL throws Sdl.Web.Delivery.Service.InvalidResourceException if the mapping cannot be resolved.
                    // We don't have a direct reference to Sdl.Web.Delivery.Service, so we just check the type name
                    if (ex.GetType().FullName != "Sdl.Web.Delivery.Service.InvalidResourceException")
                    {
                        throw;
                    }
                    Log.Debug("Exception occurred in DynamicMappingsRetriever.GetPublicationMapping('{0}'):\n{1}", urlLeftPart, ex.ToString());
                    // Let mapping be null, we'll handle it below.
                }
                if (mapping == null || mapping.Port != url.Port.ToString()) // See CRQ-1195
                {
                    throw new DxaUnknownLocalizationException(string.Format("No matching Localization found for URL '{0}'", urlLeftPart));
                }

                Localization result;
                lock (KnownLocalizations)
                {
                    string localizationId = mapping.PublicationId.ToString();
                    if (!KnownLocalizations.TryGetValue(localizationId, out result))
                    {
                        result = new Localization
                        {
                            LocalizationId = localizationId,
                            Path = mapping.Path
                        };
                        KnownLocalizations.Add(localizationId, result);
                    }
                }

                result.EnsureInitialized();
                return result;
            }
        }
	    public RabbitMqEndpointAddress(Uri uri, ConnectionFactory connectionFactory, string name)
	    {
	        _uri = new Uri(uri.GetLeftPart(UriPartial.Path));
			_connectionFactory = connectionFactory;
			_name = name;

			_isTransactional = uri.Query.GetValueFromQueryString("tx", false);
			_isLocal = () => DetermineIfEndpointIsLocal(_uri);
		    _isHighAvailable = uri.Query.GetValueFromQueryString("ha", false);
		}
 public override EventResult PlayVideo(string videoToPlay)
 {
     ProcessComplete.Finished = false;
     ProcessComplete.Success = false;
     _videoToPlay = videoToPlay;
     Uri uri = new Uri(BaseUrl + videoToPlay);
     Url = uri.GetLeftPart(UriPartial.Path);
     _currentState = State.StartPlaying;
     return EventResult.Complete();
 }
Beispiel #23
0
        } //END TryUpload

        //-------------------------------------------------------------------------//
        private bool CreateFoldersToItem( string itemKey, out string status)
        //-------------------------------------------------------------------------//
        {
            FtpWebRequest request;

            System.Uri uri = new System.Uri( GetURL(serverURL, itemKey) );
            string[] segments = uri.Segments;

            string currentFolder = uri.GetLeftPart(System.UriPartial.Authority);

            for (int i = 0; i < segments.Length - 1; i++)
            {
                string segment = segments[i];

                try
                {
                    currentFolder = string.Concat(currentFolder, segment);

                    string requestUri = currentFolder;
                    if (currentFolder.Length > 0 && currentFolder[currentFolder.Length - 1] == '/')
                    {
                        requestUri = currentFolder.Substring(0, currentFolder.Length - 1);
                    }

                    request = CreateFtpWebRequest(requestUri, WebRequestMethods.Ftp.MakeDirectory);
                    WebResponse response = request.GetResponse();
                    response.GetResponseStream().Close();
                    response.Close();
                }
                catch (System.Net.WebException e)
                {
                    FtpWebResponse response = e.Response as FtpWebResponse;

                    if (response == null || response.StatusCode == FtpStatusCode.NotLoggedIn)
                    {
                        status = response.StatusDescription;
                        return false;
                    }
                    else if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    {
                        // Folder already exists...
                        continue;
                    }
                }
                catch (System.Exception)
                {
                    status = "Could not create folder tree in FTP server. Please check your FTP URL.";
                    return false;
                }
            }

            status = "OK";
            return true;

        } //END CreateFoldersToItem
Beispiel #24
0
        public static void SetupRequest(string uri, string method)
        {
            var requestUri = new Uri(uri);
            var request = new HttpRequest("", requestUri.GetLeftPart(UriPartial.Path), requestUri.Query);
            var httpMethodField = typeof(HttpRequest).GetField("_httpMethod", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance);
            httpMethodField.SetValue(request, method);

            HttpContextFactory.Current = new HttpContextWrapper(new HttpContext(
                request,
                new HttpResponse(null)));
        }
        /// <summary>
        /// Returns if a site collection is in a particular status. If the url contains a sub site then returns true is the sub site exists, false if not. 
        /// Status is irrelevant for sub sites
        /// </summary>
        /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param>
        /// <param name="siteFullUrl">Url to the site collection</param>
        /// <param name="status">Status to check (Active, Creating, Recycled)</param>
        /// <returns>True if in status, false if not in status</returns>
        public static bool CheckIfSiteExists(this Tenant tenant, string siteFullUrl, string status)
        {
            bool ret = false;
            //Get the site name
            var url = new Uri(siteFullUrl);
            var siteDomainUrl = url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority);
            int siteNameIndex = url.AbsolutePath.IndexOf('/', 1) + 1;
            var managedPath = url.AbsolutePath.Substring(0, siteNameIndex);
            var siteRelativePath = url.AbsolutePath.Substring(siteNameIndex);
            var isSiteCollection = siteRelativePath.IndexOf('/') == -1;

            //Judge whether this site collection is existing or not
            if (isSiteCollection)
            {
                try
                {
                    var properties = tenant.GetSitePropertiesByUrl(siteFullUrl, false);
                    tenant.Context.Load(properties);
                    tenant.Context.ExecuteQueryRetry();
                    ret = properties.Status.Equals(status, StringComparison.OrdinalIgnoreCase);
                }
                catch(ServerException ex)
                {
                    if (IsUnableToAccessSiteException(ex))
                    {
                        try
                        {
                            //Let's retry to see if this site collection was recycled
                            var deletedProperties = tenant.GetDeletedSitePropertiesByUrl(siteFullUrl);
                            tenant.Context.Load(deletedProperties);
                            tenant.Context.ExecuteQueryRetry();
                            ret = deletedProperties.Status.Equals(status, StringComparison.OrdinalIgnoreCase);
                        }
                        catch
                        {
                            // eat exception
                        }
                    }
                }
            }
            //Judge whether this sub web site is existing or not
            else
            {
                var subsiteUrl = string.Format(CultureInfo.CurrentCulture,
                            "{0}{1}{2}", siteDomainUrl, managedPath, siteRelativePath.Split('/')[0]);
                var subsiteRelativeUrl = siteRelativePath.Substring(siteRelativePath.IndexOf('/') + 1);
                var site = tenant.GetSiteByUrl(subsiteUrl);
                var subweb = site.OpenWeb(subsiteRelativeUrl);
                tenant.Context.Load(subweb, w => w.Title);
                tenant.Context.ExecuteQueryRetry();
                ret = true;
            }
            return ret;
        }
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            UriBuilder uriBuilder = new UriBuilder(AuthorizationEndpoint);
            uriBuilder.AppendQueryArgument("client_id", this.clientId);
            uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.GetLeftPart(UriPartial.Path));
            uriBuilder.AppendQueryArgument("response_type", "code");
            uriBuilder.AppendQueryArgument("scope", "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");
            uriBuilder.AppendQueryArgument("state", returnUrl.Query.Substring(1));

            return uriBuilder.Uri;
        }
Beispiel #27
0
        public static String Combine(String basePath, String relativePath)
        {
            Uri baseUri = new Uri(UriUtility.ExpandUri(basePath), UriKind.Absolute);
            Uri relativeUri = new Uri(relativePath, UriKind.RelativeOrAbsolute);

            String result = baseUri.IsAbsoluteUri ? baseUri.GetLeftPart(UriPartial.Query) : baseUri.ToString();
            result += result.EndsWith("/") ? "" : "/";
            result += relativeUri.IsAbsoluteUri ? relativeUri.PathAndQuery : relativeUri.ToString();

            return UriUtility.ExpandUri(result);
        }
Beispiel #28
0
        /// <summary>
        /// Gets the schema and authority segment of request uri.
        /// E.g. "https://www.google.com/?q=1" will return "https://www.google.com".
        /// </summary>
        /// <returns>A string contains the schema and authority of the uri. </returns>
        public static string GetRequestUriSchemaAndAuthority(Uri requestUri)
        {
            if (requestUri == null)
            {
                throw new ArgumentNullException("The 'requestUri' cannot be null.");
            }

            var requestUriLeftPart = requestUri.GetLeftPart(UriPartial.Authority);

            return requestUriLeftPart;
        }
        public static ImageViewer DetectImageViewer(string html, string sourceUrl)
        {
            List<ImageViewer> viewers = imageViewers;
            LazyLoader<List<Regex>> regexes = new LazyLoader<List<Regex>>(delegate
              {
                  List<Regex> regexList = new List<Regex>(viewers.Count);
                  foreach (ImageViewer v in viewers)
                  {
                      regexList.Add(new Regex(v.Pattern, RegexOptions.CultureInvariant));
                  }
                  return regexList;
              });

            HtmlExtractor ex = new HtmlExtractor(html);
            while (ex.Seek("<script src>").Success)
            {
                BeginTag tag = (BeginTag)ex.Element;
                string src = tag.GetAttributeValue("src");

                if (String.IsNullOrEmpty(src))
                {
                    continue;
                }

                try
                {
                    if (!UrlHelper.IsUrl(src))
                    {
                        // We need absolute URLs.
                        src = UrlHelper.EscapeRelativeURL(sourceUrl, src);
                    }

                    Uri srcUri = new Uri(src);
                    if (srcUri.IsAbsoluteUri)
                    {
                        // WinLive 248276: We want just the path portion since there could be an additional query or
                        // fragment on the URL that our regexs can't handle.
                        src = srcUri.GetLeftPart(UriPartial.Path);
                    }
                }
                catch (UriFormatException)
                {
                    // We'll just use the regex on the raw attribute value.
                }

                List<Regex> regexList = regexes.Value;
                for (int i = 0; i < regexList.Count; i++)
                {
                    if (regexList[i].IsMatch(src))
                        return viewers[i];
                }
            }
            return null;
        }
Beispiel #30
0
        public WebSpider(Uri startUri, WebSpiderOptions options = null)
        {
            StartUri = startUri;
            spiderOptions = options ?? new WebSpiderOptions();

            // In future this could be null and will process cross-site, but for now must exist
            spiderOptions.BaseUri = spiderOptions.BaseUri ?? new Uri(StartUri.GetLeftPart(UriPartial.Authority));

            webPagesPending = new Queue();
            webPages = new Hashtable();
            spiderOptions.WebPageProcessor.ContentHandler += HandleLinks;
        }
Beispiel #31
0
 public static string GetCurrentURL()
 {
     if (Application.absoluteURL.Length > 0)
     {
         var uri = new System.Uri(Application.absoluteURL);              //get url of whatever page we're running in (note: will not work if endpoint is not on same url as client)
         return(uri.GetLeftPart(System.UriPartial.Authority) + "/");     //strip out the bit saying "map"
     }
     else
     {
         return("http://localhost:8000/");
     }
 }
Beispiel #32
0
 // return domain from URI
 public static string GetDomainFromUri(string completeUri)
 {
     try
     {
         var tmpUri = new Uri(completeUri);
         return tmpUri.GetLeftPart(UriPartial.Authority).Replace("/www.", "/").Replace("http://", "").Replace("https://", "");
     }
     catch (Exception)
     {
         return null;
     }
 }
Beispiel #33
0
 static public int GetLeftPart(IntPtr l)
 {
     try {
         System.Uri        self = (System.Uri)checkSelf(l);
         System.UriPartial a1;
         checkEnum(l, 2, out a1);
         var ret = self.GetLeftPart(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #34
0
 static int GetLeftPart(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         System.Uri        obj  = (System.Uri)ToLua.CheckObject <System.Uri>(L, 1);
         System.UriPartial arg0 = (System.UriPartial)ToLua.CheckObject(L, 2, typeof(System.UriPartial));
         string            o    = obj.GetLeftPart(arg0);
         LuaDLL.lua_pushstring(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Beispiel #35
0
 public FTPUtil(System.Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)
 {
     this.ftpWebRequest_0  = null;
     this.ftpWebResponse_0 = null;
     this.webProxy_0       = null;
     this.bool_0           = false;
     this.string_4         = "";
     this.uri_0            = new System.Uri(FtpUri.GetLeftPart(UriPartial.Authority));
     this.string_0         = FtpUri.AbsolutePath;
     if (!this.string_0.EndsWith("/"))
     {
         this.string_0 = this.string_0 + "/";
     }
     this.string_1   = strUserName;
     this.string_3   = strPassword;
     this.webProxy_0 = objProxy;
 }
Beispiel #36
0
 public FtpHelper(System.Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)
 {
     this.Request           = null;
     this.Response          = null;
     this._Proxy            = null;
     this._isDeleteTempFile = false;
     this._UploadTempFile   = "";
     this._Uri           = new System.Uri(FtpUri.GetLeftPart(UriPartial.Authority));
     this._DirectoryPath = FtpUri.AbsolutePath;
     if (!this._DirectoryPath.EndsWith("/"))
     {
         this._DirectoryPath = this._DirectoryPath + "/";
     }
     this._UserName = strUserName;
     this._Password = strPassword;
     this._Proxy    = objProxy;
 }
Beispiel #37
0
 public FTPUtil(System.Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)
 {
     this.ftpWebRequest  = null;
     this.ftpWebResponse = null;
     this.proxy          = null;
     this.bool_0         = false;
     this.remoteFile     = "";
     this.uri            = new System.Uri(FtpUri.GetLeftPart(UriPartial.Authority));
     this.directoryPath  = FtpUri.AbsolutePath;
     if (!this.directoryPath.EndsWith("/"))
     {
         this.directoryPath = this.directoryPath + "/";
     }
     this.userName = strUserName;
     this.password = strPassword;
     this.proxy    = objProxy;
 }
Beispiel #38
0
        [ValidateAntiForgeryToken] //this prevents automated scripts from trying to register
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            //Check to confirm that my register model is filled out correctly
            if (ModelState.IsValid)
            {
                //this is creating my new user.  I simply used email only rather than username
                BurgerStoreUser newEmail = new BurgerStoreUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    PhoneNumber = model.PhoneNumber
                };

                IdentityResult creationResult = await this._signInManager.UserManager.CreateAsync(newEmail);

                if (creationResult.Succeeded)
                {
                    IdentityResult passwordResult = await this._signInManager.UserManager.AddPasswordAsync(newEmail, model.Password);

                    if (passwordResult.Succeeded)
                    {
                        Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                        search.Email.Is(model.Email);
                        var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

                        if (searchResult.Ids.Count == 0)
                        {
                            //creating a new braintree customer here
                            await _braintreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest
                            {
                                Email     = model.Email,
                                FirstName = model.FirstName,
                                LastName  = model.LastName,
                                Phone     = model.PhoneNumber
                            });
                        }
                        else
                        {
                            //update the existing braintree customer

                            Braintree.Customer existingCustomer = searchResult.FirstItem;
                            await _braintreeGateway.Customer.UpdateAsync(existingCustomer.Id, new Braintree.CustomerRequest
                            {
                                FirstName = model.FirstName,
                                LastName  = model.LastName,
                                Phone     = model.PhoneNumber
                            });
                        }



                        var confirmationToken = await _signInManager.UserManager.GenerateEmailConfirmationTokenAsync(newEmail);

                        confirmationToken = System.Net.WebUtility.UrlEncode(confirmationToken);

                        string     currentUrl      = Request.GetDisplayUrl();
                        System.Uri uri             = new System.Uri(currentUrl);
                        string     confirmationUrl = uri.GetLeftPart(System.UriPartial.Authority);
                        confirmationUrl += "/account/confirm?id=" + confirmationToken + "&userId=" + System.Net.WebUtility.UrlEncode(newEmail.Id);
                        await this._signInManager.SignInAsync(newEmail, false);

                        var emailResult = await this._emailService.SendEmailAsync(model.Email, "Welcome to Flavor Town Burgers", "<p> Thanks for signing up, " + model.Email + "!</p><p>< a href =\"" + confirmationUrl + "\">Confirm your account<a></p>", "Thanks for signing up, " + model.Email);

                        if (emailResult.Success)
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            return(BadRequest(emailResult.Message));
                        }
                    }
                    else
                    {
                        this._signInManager.UserManager.DeleteAsync(newEmail).Wait();
                        foreach (var error in passwordResult.Errors)
                        {
                            ModelState.AddModelError(error.Code, error.Description);
                        }
                    }
                }
                else
                {
                    foreach (var error in creationResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                }
            }

            return(View());
        }
Beispiel #39
0
 /* ----------------------------------------------------------------- */
 ///
 /// WithoutQuery
 ///
 /// <summary>
 /// Gets the Uri object that is removed queries from the specified
 /// one.
 /// </summary>
 ///
 /// <param name="src">Source URL.</param>
 ///
 /// <returns>Uri object that is removed queries.</returns>
 ///
 /* ----------------------------------------------------------------- */
 public static Source WithoutQuery(this Source src) =>
 new Source(src.GetLeftPart(UriPartial.Path));
        public static string getDomain(string property)
        {
            string result = null;

            property.Replace(" ", "%20");
            var client  = new RestClient("https://api.cognitive.microsoft.com/bing/v5.0/search?q=" + property + "&count=1&offset=0&mkt=en-us&safesearch=Moderate");
            var request = new RestRequest(Method.GET);

            request.AddHeader("postman-token", "445c2e32-337b-f346-bb55-c3da94318279");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("ocp-apim-subscription-key", "1ed58e2f0acb47f9a5cefd29000e1cfa");
            request.AddHeader("content-type", "application/json");
            request.AddParameter("application/json", "{\n    \"Ocp-Apim-Subscription-Key\" : \"AXMPcxlXPA2M7GCa3uJeTB/vwMCWNdYAT3CHkbWyt/I\"\n}", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);


            string secondParseString = null;

            for (int i = 0; i < 1; i++)
            {
                secondParseString = Parse(response.Content, @"Newtonsoft.Json.Linq.JArray", @"webPages").First();
            }



            var jobj = Newtonsoft.Json.Linq.JArray.Parse(secondParseString);

            for (int i2 = 0; i2 < jobj.Count(); i2++)
            {
                if (i2 == 0)
                {
                    foreach (Newtonsoft.Json.Linq.JObject thing in jobj.Children())
                    {
                        foreach (KeyValuePair <string, Newtonsoft.Json.Linq.JToken> jp in thing)
                        {
                            if (jp.Key == "displayUrl")
                            {
                                if (jp.Value.ToString().Substring(0, 2) == "ht")
                                {
                                    System.Uri URI       = new System.Uri(jp.Value.ToString());
                                    string     uriDomain = URI.GetLeftPart(UriPartial.Authority);
                                    uriDomain = uriDomain.Replace(@"https://", "");
                                    uriDomain = uriDomain.Replace(@"http://", "");
                                    uriDomain = uriDomain.Replace("www", "");
                                    result    = uriDomain;
                                }
                                else
                                {
                                    result = jp.Value.ToString();
                                }
                            }
                        }
                    }
                }
            }

            if (result != null)
            {
                return(result);
            }
            else
            {
                return("null error. Contact Adam");
            }
        }
Beispiel #41
0
 // Scrapes html pages from given Uri
 // Usage: this.Literal1.Text = new System.Uri("https://www.amazon.com/gp/goldbox/ref=nav_cs_gb").Scrape();
 public static string Scrape(this System.Uri uri)
 {
     using (var sr = new System.IO.StreamReader(System.Net.HttpWebRequest.Create(uri.GetLeftPart(System.UriPartial.Query)).GetResponse().GetResponseStream()))
     {
         return(sr.ReadToEnd());
     }
 }