public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestMessage request = actionContext.Request;
            string query = request.RequestUri.Query.Substring(1);
            var parts = query.Split('&').ToList();
            bool foundExpand = false;
            for (int i = 0; i < parts.Count; i++)
            {
                string segment = parts[i];
                if (segment.StartsWith(ODataExpandOption, StringComparison.Ordinal))
                {
                    foundExpand = true;
                    parts[i] += "," + this.AlwaysExpand;
                    break;
                }
            }

            if (!foundExpand)
            {
                parts.Add(ODataExpandOption + this.AlwaysExpand);
            }

            UriBuilder modifiedRequestUri = new UriBuilder(request.RequestUri);
            modifiedRequestUri.Query = string.Join("&",
                                        parts.Where(p => p.Length > 0));
            request.RequestUri = modifiedRequestUri.Uri;
            base.OnActionExecuting(actionContext);
        }
Beispiel #2
0
        public System.Uri GetURI(string subpath)
        {
            var builder = new System.UriBuilder();

            if (this.UseHTTPS)
            {
                builder.Scheme = "https";
            }
            else
            {
                builder.Scheme = "http";
            }

            builder.Host = this.Server;

            if (this.Port.HasValue)
            {
                builder.Port = this.Port.Value;
            }

            if (subpath != "")
            {
                builder.Path = subpath;
            }

            return(builder.Uri);
        }
 public void ProcessRequest(HttpContext context)
 {
     if (context == null)
     {
         throw new HttpException("HttpContext was unavailable.");
     }
     TheKnot.Membership.Security.Authentication.Provider.DeleteMsdTicket();
     UriBuilder builder = new UriBuilder(context.Request.QueryString["originalTarget"]);
     if ((builder == null) || (builder.Uri.PathAndQuery.Trim().Length == 0))
     {
         throw new TheKnot.Membership.Security.Providers.CustomAuthenticationException("The application requires 'originalTarget' as query string variable.");
     }
     if (builder.Query.IndexOf("MsdVisit") == -1)
     {
         if (builder.Query.Length > 0)
         {
             builder.Query = builder.Query + "&MsdVisit=1";
         }
         else
         {
             builder.Query = "MsdVisit=1";
         }
     }
     context.Response.Redirect(builder.Uri.AbsoluteUri, true);
 }
        public StressService(Uri serviceBusUri, string username, string password, ushort heartbeat, int iterations, int instances, int messageSize, bool cleanUp, bool mixed, int prefetchCount, int consumerLimit, int requestsPerInstance)
        {
            _username = username;
            _password = password;
            _heartbeat = heartbeat;
            _iterations = iterations;
            _instances = instances;
            _messageSize = messageSize;
            _prefetchCount = prefetchCount;
            _consumerLimit = consumerLimit;
            _requestsPerInstance = requestsPerInstance;
            _cleanUp = cleanUp;
            _mixed = mixed;
            _serviceBusUri = serviceBusUri;
            _messageContent = new string('*', messageSize);

            _clientUri = _serviceBusUri;

            var prefetch = new Regex(@"([\?\&])prefetch=[^\&]+[\&]?");
            string query = _serviceBusUri.Query;

            if (query.IndexOf("prefetch", StringComparison.InvariantCultureIgnoreCase) >= 0)
                query = prefetch.Replace(query, string.Format("prefetch={0}", _prefetchCount));
            else if (string.IsNullOrEmpty(query))
                query = string.Format("prefetch={0}", _prefetchCount);
            else
                query += string.Format("&prefetch={0}", _prefetchCount);

            var builder = new UriBuilder(_serviceBusUri);
            builder.Query = query.Trim('?');
            _serviceBusUri = builder.Uri;

            _cancel = new CancellationTokenSource();
            _clientTasks = new List<Task>();
        }
        /// <summary>
        /// Filtr wymuszający użycie HTTPS podczas połączenia z serwerem
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var request = actionContext.Request;

            if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                var html = "<p>Https is required</p>";

                if (request.Method.Method == "GET")
                {
                    actionContext.Response = request.CreateResponse(HttpStatusCode.Found);
                    actionContext.Response.Content = new StringContent(html, Encoding.UTF8, "text/html");

                    UriBuilder httpsNewUri = new UriBuilder(request.RequestUri)
                    {
                        Scheme = Uri.UriSchemeHttps,
                        Port = 443
                    };

                    actionContext.Response.Headers.Location = httpsNewUri.Uri;
                }
                else
                {
                    actionContext.Response = request.CreateResponse(HttpStatusCode.NotFound);
                    actionContext.Response.Content = new StringContent(html, Encoding.UTF8, "text/html");
                }

            }
        }
        public void DeleteDir(Uri relativeKeyUri)
        {
            if (!relativeKeyUri.OriginalString.EndsWith("/"))
            {
                throw new ArgumentException("Use Delete to delete a key, or end the key with a forward slash.to delete a directory.");
            }
            var fullKeyUriWithQuery = new UriBuilder(GetFullUri(relativeKeyUri)) { Query = "recursive=true" };

            var webRequest = (HttpWebRequest)WebRequest.Create(fullKeyUriWithQuery.Uri);
            webRequest.Method = "DELETE";

            try
            {
                using (webRequest.GetResponse())
                {
                }
            }
            catch (WebException ex)
            {
                if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                {
                    return;
                }
                throw;
            }
        }
        public ActionResult Generate(string tracker)
        {
            Captcha captcha;

            try
            {
#if NETCORE
                String referer = HttpContext.Request.Headers["Referer"].ToString();
                Microsoft.AspNetCore.Http.HttpRequest req = HttpContext.Request;
                Uri rUri = new System.UriBuilder(referer).Uri;
                if (req.Host.Host == rUri.Host && req.Host.Port == rUri.Port && req.Scheme == rUri.Scheme && rUri.AbsolutePath == req.Path)
                {
#elif NETFULL
                Uri rUri = System.Web.HttpContext.Current.Request.UrlReferrer;
                Uri req  = System.Web.HttpContext.Current.Request.Url;
                if (req.AbsolutePath == rUri.AbsolutePath)
                {
#endif
                    throw new InvalidOperationException();
                }

                captcha = Captcha.GenerateByTracker(tracker);
            }
            catch (Exception)
            {
                captcha = Captcha.Error;
            }

            return(File(captcha.ToStream().GetBuffer(), System.Net.Mime.MediaTypeNames.Image.Jpeg));
        }
Beispiel #8
0
        public void Configuration(IAppBuilder app)
        {
            app.UseNinjectMiddleware(() => _kernel.Value);

            HttpConfiguration webApiConfig = new HttpConfiguration();

            WebApiConfig.Register(webApiConfig);
            app.UseWebApi(webApiConfig);

            //Ninject
            app.UseNinjectWebApi(webApiConfig);

            //AutoMapper
            if (!AutoMapperConfig.IsInitialized)
            {
                AutoMapperConfig.Initialize();
            }

            //Database path
            string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

            System.UriBuilder uri  = new System.UriBuilder(codeBase);
            string            path = System.Uri.UnescapeDataString(uri.Path);
            var parent             = System.IO.Directory.GetParent(path);

            while (parent.Name.IndexOf("TAL.Developer.Test.") == -1)
            {
                parent = System.IO.Directory.GetParent(parent.FullName);
            }
            parent = System.IO.Directory.GetParent(parent.FullName); // ROOT
            System.AppDomain.CurrentDomain.SetData("DataDirectory", parent.FullName);
        }
        public string TestPass(int id)
        {
            string password = clientLoginHelper.TestPassword(id);

            string url = "http://demo2projects.com/stratasfair/sumitest/Login";

            var    urlBuilder = new System.UriBuilder(url);
            string PortalUrl  = string.Empty;

            if (urlBuilder.Uri.Authority.Contains("demo2projects"))
            {
                PortalUrl = urlBuilder.Uri.AbsolutePath.Replace("/stratasfair/", "").ToString();
            }
            else
            {
                PortalUrl = urlBuilder.Uri.AbsolutePath.TrimStart('/').ToString();
            }
            int endIndex = PortalUrl.IndexOf('/');

            PortalUrl = PortalUrl.Substring(0, endIndex);

            return(password);

            //string result = clientLoginHelper.TestPass();
        }
Beispiel #10
0
        public ActionResult ShowTickets(string orderId, decimal comission)
        {
            var orderInfo = GetOrderInfo(orderId, comission);

            // Printing tickets
            try
            {
                using (var client = new CommandServiceClient())
                {
                    UrlHelper urlHelper  = new UrlHelper(Request.RequestContext);
                    var       urlBuilder =
                        new System.UriBuilder(Request.Url.AbsoluteUri)
                    {
                        Path = urlHelper.Action("TicketsToPrint", new { orderId, comission })
                    };

                    Uri    uri = urlBuilder.Uri;
                    string url = HttpUtility.UrlDecode(uri.ToString());

                    client.PrintUrl(url);
                }

                return(Success(orderInfo));
            }
            catch (EndpointNotFoundException ex)
            {
#if DEBUG
                return(Success(orderInfo));
#endif
                throw;
            }
        }
        /// <summary>
        /// OAuth認証のリクエストトークン取得。リクエストトークンと組み合わせた認証用のUriも生成する
        /// </summary>
        /// <param name="requestTokenUrl">リクエストトークンの取得先URL</param>
        /// <param name="authorizeUrl">ブラウザで開く認証用URLのベース</param>
        /// <param name="requestToken">[OUT]取得したリクエストトークン</param>
        /// <returns>取得結果真偽値</returns>
        private Uri GetAuthenticatePageUri(string requestTokenUrl, string authorizeUrl, ref string requestToken)
        {
            const string tokenKey = "oauth_token";

            // リクエストトークン取得
            string content = "";
            NameValueCollection reqTokenData;

            if (this.GetOAuthToken(new Uri(requestTokenUrl), "", "", null, ref content, callbackUrl: "oob") != HttpStatusCode.OK)
            {
                return(null);
            }
            reqTokenData = base.ParseQueryString(content);

            if (reqTokenData != null)
            {
                requestToken = reqTokenData[tokenKey];
                // Uri生成
                UriBuilder ub = new UriBuilder(authorizeUrl);
                ub.Query = string.Format("{0}={1}", tokenKey, requestToken);
                return(ub.Uri);
            }
            else
            {
                return(null);
            }
        }
Beispiel #12
0
 public static string FindExecutionDirectory(Assembly assembly)
 {
     string applicationPath = assembly.CodeBase;
     UriBuilder uri = new UriBuilder(applicationPath);
     string path = Uri.UnescapeDataString(uri.Path);
     return Path.GetDirectoryName(path);
 }
        private static async Task GetPeople(string address)
        {
            var uriBuilder = new UriBuilder(address);
            uriBuilder.Path = "api/Customer";

            using (var client = new HttpClient())
            {
                Console.WriteLine("Getting data without a version...");
                var response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();

                Console.WriteLine("Getting data for v1...");
                client.DefaultRequestHeaders.Add("api-version", "1");
                response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();


                Console.WriteLine("Getting data for v2...");
                client.DefaultRequestHeaders.Remove("api-version");
                client.DefaultRequestHeaders.Add("api-version", "2");
                response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();
            }
        }
Beispiel #14
0
        public ActionResult ViewAuctionDetails(int id, FormCollection formObj)
        {
            ItemDAO itemDAO = new ItemDAO();

            if (ModelState.IsValid)
            {
                int     baseQuantity    = Convert.ToInt32(formObj["baseItemQuantity"]);
                int     newItemQuantity = Convert.ToInt32(formObj["newItemQuantity"]);
                int     newTotalItems   = baseQuantity + newItemQuantity;
                Auction auction         = new Auction(id, newTotalItems);

                var urlBuilder = new System.UriBuilder();
                if (id > 0)
                {
                    try
                    {
                        //Update Item Quantity
                        auctionDAO.Update(auction);
                        urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri)
                        {
                            Path  = Url.Action("ViewAuctionDetails", "Auction"),
                            Query = "id=" + id,
                        };
                    }
                    catch (Exception ex)
                    {
                        return(View("Update Item Quantity Error! ", new HandleErrorInfo(ex, "Item", "AddItem")));
                    }
                }
                Uri uri = urlBuilder.Uri;
                return(Redirect(uri.AbsoluteUri));
            }
            return(View());
        }
        public ActionResult SaveUser(UserRegistration model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var urlBuilder =
                        new System.UriBuilder(Request.Url.AbsoluteUri)
                    {
                        Path  = Url.Action("Activate", "User"),
                        Query = null,
                    };

                    Uri uri = urlBuilder.Uri;

                    model.ClientURL = urlBuilder.ToString() + "/" + CreateMD5(model.Username);
                    model.Token     = CreateMD5(model.Username);
                    var client = new HttpClient();
                    //client.BaseAddress = new Uri(ConfigurationManager.AppSettings["baseUrl"]);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));
                    var result = client.PostAsJsonAsync("http://localhost:53099/api/User", model).Result;
                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        ViewBag.Message = "User Registered Successfully";
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.ToString();
            }
            return(View("Index"));
        }
Beispiel #16
0
 /// <summary>
 /// Gets the location of the assembly as specified originally.
 /// </summary>
 /// <returns>The location of the assembly as specified originally.</returns>
 private string GetAssemblyPath()
 {
     string codeBase = Assembly.GetExecutingAssembly().CodeBase;
     var uri = new UriBuilder(codeBase);
     string path = Uri.UnescapeDataString(uri.Path);
     return System.IO.Path.GetDirectoryName(path);
 }
Beispiel #17
0
        private async Task <IActionResult> SendForgotPasswordEmail(AppUser user)
        {
            var originalCode = await _userManager.GeneratePasswordResetTokenAsync(user);

            var code = WebUtility.UrlEncode(originalCode);

            var urlBuilder =
                new System.UriBuilder(_configuration["SiteUrl"])
            {
                Path  = Url.Content("~/account/reset-password"),
                Query = "email=" + user.Email + "&code=" + code
            };
            var callbackUrl = urlBuilder.ToString();

            string resetPasswordText = @"Hi,<br /><br />" +
                                       "Someone recently requested a password change for your account.<br /><br />" +
                                       "If it was you, you can reset your password by clicking here:<br /><br />" +
                                       "<a href='" + callbackUrl + "'>Reset Password</a><br /><br />" +
                                       "If you don't want to change your password or didn't request this, just ignore and delete this message.<br /><br />" +
                                       "Thank you.<br /><br />" +
                                       "Site Admin";

            var response = await _emailSender.SendEmailAsync(user.Email, "Reset Your Password",
                                                             resetPasswordText);

            return(new OkObjectResult(null));
        }
Beispiel #18
0
        //
        // POST: /Account/Login

        private string ProcessOktaRelayState(System.Collections.Specialized.NameValueCollection form)
        {
            var relayStateStr = "RelayState";

            if (form[relayStateStr] == null)
            {
                return(null);
            }
            var relayState = HttpUtility.UrlDecode(form[relayStateStr]);

            if (relayState.StartsWith("//"))
            {
                // Delete the first "/" from the string:
                // Remove "1" character from the string, starting at position "0"
                relayState = relayState.Remove(0, 1);
            }
            // Use http://example.com because UriBuilder needs a scheme and domain to work
            var url = String.Format("http://example.com{0}", relayState);
            var uri = new System.UriBuilder(url);
            var qs  = HttpUtility.ParseQueryString(uri.Query);

            uri.Query = null;
            if (qs.Get(relayStateStr) != null)
            {
                uri.Query = String.Format("{0}={1}", relayStateStr, qs.Get(relayStateStr));
            }
            var relayStateClean = String.Join("", uri.Path, uri.Query);

            return(relayStateClean);
        }
        public string CallBack(string mrfid, string ReturnUrl)
        {
            client.AppId     = AppId;
            client.AppSecret = AppSecret;
            dynamic token = client.Get("oauth/access_token", new
            {
                client_id     = AppId,
                client_secret = AppSecret,
                grant_type    = "client_credentials",
                fields        = "public_actions,public_profile",
            });
            var redirect_uri = new System.UriBuilder(Request.Url.AbsoluteUri)
            {
                Path  = Url.Action("ReturnUrl", "facebook"),
                Query = null,
            };
            var url = client.GetLoginUrl(new
            {
                client_id     = client.AppId,
                client_secret = client.AppSecret,
                redirect_uri  = redirect_uri.Uri.AbsoluteUri + "?token=" + Token + "&mrfid=" + mrfid + "&returnurl=" + ReturnUrl
            }).AbsoluteUri;

            return(url);
        }
        public ExternalSearchService(IAppConfiguration config, IDiagnosticsService diagnostics)
        {
            ServiceUri = config.ServiceDiscoveryUri;

            Trace = diagnostics.SafeGetSource("ExternalSearchService");

            // Extract credentials
            var userInfo = ServiceUri.UserInfo;
            ICredentials credentials = null;
            if (!String.IsNullOrEmpty(userInfo))
            {
                var split = userInfo.Split(':');
                if (split.Length != 2)
                {
                    throw new FormatException("Invalid user info in SearchServiceUri!");
                }

                // Split the credentials out
                credentials = new NetworkCredential(split[0], split[1]);
                ServiceUri = new UriBuilder(ServiceUri)
                {
                    UserName = null,
                    Password = null
                }.Uri;
            }

            if (_healthIndicatorStore == null)
            {
                _healthIndicatorStore = new BaseUrlHealthIndicatorStore(new AppInsightsHealthIndicatorLogger());
            }

            _client = new SearchClient(ServiceUri, config.SearchServiceResourceType, credentials, _healthIndicatorStore, new TracingHttpHandler(Trace));
        }
Beispiel #21
0
        /// <summary>
        /// Get uri from url with http or https scheme
        /// </summary>
        /// <param name="url">url as string</param>
        /// <returns>URI</returns>
        /// <exception cref="ArgumentNullException">url is null</exception>
        /// <exception cref="UriFormatException">url format is not correct</exception>
        /// <exception cref="NotSupportedException">url scheme is not http or https</exception>
        public virtual Uri GetUri(string url)
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }

            Uri uri;

            try {
                uri = new System.UriBuilder(url).Uri;
            }
            catch (UriFormatException) {
                throw new UriFormatException("Url format is not correct");
            }
            if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
            {
                return(uri);
            }
            else
            {
                throw new NotSupportedException(
                          $"Sorry! Protocol '{uri.Scheme}' is not supported. Only http and https are supported");
            }
        }
Beispiel #22
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            string PortalUrl  = string.Empty;
            var    urlBuilder = new System.UriBuilder(HttpContext.Current.Request.Url.AbsoluteUri);

            if (urlBuilder.Uri.Authority.Contains("demo2projects"))
            {
                PortalUrl = urlBuilder.Uri.AbsolutePath.Replace("stratasfair/", "").ToString().Split('/')[0];
            }
            else
            {
                PortalUrl = urlBuilder.Uri.AbsolutePath.TrimStart('/').ToString().Split('/')[0];
            }


            if (ClientSessionData.ClientRoleName != "Owner")
            {
                filterContext.Result = new RedirectResult("~/" + ClientSessionData.ClientPortalLink + "/dashboard");
                return;
            }


            base.OnActionExecuting(filterContext);
        }
Beispiel #23
0
        void ProcessSingleFile(string selectedFileName, FileInfo selectedFile, object bw_sender, DoWorkEventArgs bw_e, Uri docUri)
        {
            System.UriBuilder ub = null;
            uniqueFileNameNonUI = System.DateTime.Now.ToString("yyyyMMdd_HHmmss_")
                                  + selectedFile.Name;
            uniqueFileNameList.Add(uniqueFileNameNonUI);
            currentDispatcher.BeginInvoke(() =>
            {
                Chunks         = new ObservableCollection <Chunk>();
                UniqueFileName = uniqueFileNameNonUI;
                FilePosition   = 0;
                FileSize       = selectedFile.Length;
                // Construct URI to the File upload Handler ASHX file
            });
            ub = new UriBuilder(docUri.AbsoluteUri);
            // Set any parameters the Handler will require.
            // Here we pass in the original + unique file name
            ub.Query = "filename=" + selectedFile.Name
                       + "&uniquefilename=" + uniqueFileNameNonUI;


            // The function that does the background work
            ProcessFileUpload(ub.Uri
                              , (System.IO.FileInfo)selectedFile
                              , (System.ComponentModel.BackgroundWorker)bw_sender
                              , bw_e);
        }
Beispiel #24
0
        private async Task SendConfirmationEmail(AppUser user)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            var originalCode = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var code       = WebUtility.UrlEncode(originalCode);
            var urlBuilder =
                new System.UriBuilder(Request.GetRawUrl())
            {
                Path  = Url.Content("~/account/confirm-email"),
                Query = "userId=" + user.Id + "&code=" + code
            };
            var callbackUrl = urlBuilder.ToString();

            callbackUrl = HtmlEncoder.Default.Encode(callbackUrl);

            string confirmText = @"Hi,<br /><br />" +
                                 "Thank you for registering an account on our site.<br /><br />" +
                                 "You are one step away from being able to link your website to your chosen word.<br /><br />" +
                                 "Please confirm your email address by clicking here:<br /><br />" +
                                 "<a href='" + callbackUrl + "'>Confirm Email</a><br /><br />" +
                                 "If you didn't register for this account, just ignore and delete this message.<br /><br />" +
                                 "Thank you.<br /><br />" +
                                 "Site Admin";

            await _emailSender.SendEmailAsync(user.Email, "Confirm your account",
                                              confirmText);
        }
Beispiel #25
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.HttpContext.Request.IsSecureConnection)
            {
                if (Redirect)
                {
                    var builder = new UriBuilder(filterContext.HttpContext.Request.Url);

                    builder.Scheme = Uri.UriSchemeHttps;

                    if (Port != 0 && Port != 443)
                    {
                        builder.Port = Port;
                    }

                    filterContext.Result = new RedirectResult(builder.ToString());
                }
                else
                {
                    throw new HttpException((int)HttpStatusCode.Forbidden, "Access forbidden. The requested resource requires an SSL connection.");
                }
            }
        }
		public void ReadFromRequestAuthorizationScattered() {
			// Start by creating a standard POST HTTP request.
			var postedFields = new Dictionary<string, string> {
				{ "age", "15" },
			};

			// Now add another field to the request URL
			var builder = new UriBuilder(MessagingTestBase.DefaultUrlForHttpRequestInfo);
			builder.Query = "Name=Andrew";

			// Finally, add an Authorization header
			var authHeaderFields = new Dictionary<string, string> {
				{ "Location", "http://hostb/pathB" },
				{ "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
			};
			var headers = new NameValueCollection();
			headers.Add(HttpRequestHeaders.Authorization, CreateAuthorizationHeader(authHeaderFields));
			headers.Add(HttpRequestHeaders.ContentType, Channel.HttpFormUrlEncoded);

			var requestInfo = new HttpRequestInfo("POST", builder.Uri, form: postedFields.ToNameValueCollection(), headers: headers);

			IDirectedProtocolMessage requestMessage = this.channel.ReadFromRequest(requestInfo);

			Assert.IsNotNull(requestMessage);
			Assert.IsInstanceOf<TestMessage>(requestMessage);
			TestMessage testMessage = (TestMessage)requestMessage;
			Assert.AreEqual(15, testMessage.Age);
			Assert.AreEqual("Andrew", testMessage.Name);
			Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
		}
        /// <summary>
        /// The OnAuthorization method checks if the request is in HTTPS format or not and passed the Authorization task to the base class.
        /// </summary>
        /// <param name="actionContext">Context of the request.</param>        
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var request = actionContext.Request;

            // Check if the request uri scheme is in HTTPS format.
            if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                var response = new HttpResponseMessage();

                if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Head)
                {
                    var uri = new UriBuilder(request.RequestUri);
                    uri.Scheme = Uri.UriSchemeHttps;
                    uri.Port = this.Port;

                    response.StatusCode = HttpStatusCode.Found;
                    response.Headers.Location = uri.Uri;
                }
                else
                {
                    response.StatusCode = HttpStatusCode.Forbidden;
                }

                actionContext.Response = response;
            }
            else
            {
                // Call the OnAuthorization method of the base class.
                base.OnAuthorization(actionContext);
            }
        }
        private async Task<Response> GeocodeAsync(IDictionary<string, string> query)
        {
            // build the request URI
            var builder = new UriBuilder(_endpoint);
            var resultingQuery = new Dictionary<string, string>();
            foreach (string key in query.Keys)
            {
                resultingQuery[key] = query[key];
            }
            resultingQuery["format"] = "jsonv2";
            resultingQuery["polygon"] = "1";
            resultingQuery["addressdetails"] = "1";
            var requestUri = QueryHelpers.AddQueryString(_endpoint, resultingQuery);

            // get the response
            ClientResponse clientResponse = await _client.GetAsync(requestUri).ConfigureAwait(false);

            // parse the response
            string content = Encoding.UTF8.GetString(clientResponse.Content);
            var places = JsonConvert.DeserializeObject<Place[]>(content);

            // project the response
            return new Response
            {
                Locations = places.Select(p => new Location
                {
                    Name = p.DisplayName,
                    Latitude = p.Latitude,
                    Longitude = p.Longitude
                }).ToArray()
            };
        }
 public static string GetPluginDirectory()
 {
     string codeBase = Assembly.GetExecutingAssembly().CodeBase;
     UriBuilder uri = new UriBuilder(codeBase);
     string path = Uri.UnescapeDataString(uri.Path);
     return Path.GetDirectoryName(path);
 }
Beispiel #30
0
        private void UploadFile(object item)
        {
            canUploadJob = false;
            JobMonitorCommand.UpdateCanExecuteCommand();

            Uri SourceUri = new Uri(App.Current.Host.Source, "../UploadFileHandler.ashx");

            System.UriBuilder ub = new System.UriBuilder(SourceUri);
            Uri docUri           = new System.UriBuilder(SourceUri).Uri;

            //Uri docUri = new System.UriBuilder(
            //        System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme
            //        , System.Windows.Browser.HtmlPage.Document.DocumentUri.Host
            //        , System.Windows.Browser.HtmlPage.Document.DocumentUri.Port
            //        , "UploadFileHandler.ashx").Uri;
            // Initiate a background worker so we don't hold up the UI of the Client App
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += (bw_sender, bw_e) =>
            {
                ProcessSingleFile(selectedWPCFileName, selectedWPCFile, bw_sender, bw_e, docUri);
                ProcessSingleFile(selectedLAFileName, selectedLAFile, bw_sender, bw_e, docUri);
                ProcessSingleFile(selectedCtyFileName, selectedCtyFile, bw_sender, bw_e, docUri);
                ProcessSingleFile(selectedLEAFileName, selectedLEAFile, bw_sender, bw_e, docUri);
                ProcessSingleFile(selectedNUTS1FileName, selectedNUTS1File, bw_sender, bw_e, docUri);
                ProcessSingleFile(selectedWDFileName, selectedWDFile, bw_sender, bw_e, docUri);
                ProcessSingleFile(selectedPCFileName, selectedPCFile, bw_sender, bw_e, docUri);
            };
            bw.RunWorkerAsync();
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }
        public static void GetDomain(string fromUrl, out string domain, out string subDomain)
        {
            domain = "";
            subDomain = "";
            try
            {
                if (fromUrl.IndexOf("的名片") > -1)
                {
                    subDomain = fromUrl;
                    domain = "名片";
                    return;
                }

                UriBuilder builder = new UriBuilder(fromUrl);
                fromUrl = builder.ToString();

                Uri u = new Uri(fromUrl);

                if (u.IsWellFormedOriginalString())
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";

                    }
                    else
                    {
                        string Authority = u.Authority;
                        string[] ss = u.Authority.Split('.');
                        if (ss.Length == 2)
                        {
                            Authority = "www." + Authority;
                        }
                        int index = Authority.IndexOf('.', 0);
                        domain = Authority.Substring(index + 1, Authority.Length - index - 1).Replace("comhttp","com");
                        subDomain = Authority.Replace("comhttp", "com");
                        if (ss.Length < 2)
                        {
                            domain = "不明路径";
                            subDomain = "不明路径";
                        }
                    }
                }
                else
                {
                    if (u.IsFile)
                    {
                        subDomain = domain = "客户端本地文件路径";
                    }
                    else
                    {
                        subDomain = domain = "不明路径";
                    }
                }
            }
            catch
            {
                subDomain = domain = "不明路径";
            }
        }
Beispiel #32
0
        /// <summary>
        /// Check that the source of an inventory request is one that we trust.
        /// </summary>
        /// <param name="peer"></param>
        /// <returns></returns>
        public bool CheckTrustSource(IPEndPoint peer)
        {
            if (m_doLookup)
            {
                m_log.InfoFormat("[GRID AGENT INVENTORY]: Checking trusted source {0}", peer);
                UriBuilder ub = new UriBuilder(m_userserver_url);
                IPAddress[] uaddrs = Dns.GetHostAddresses(ub.Host);
                foreach (IPAddress uaddr in uaddrs)
                {
                    if (uaddr.Equals(peer.Address))
                    {
                        return true;
                    }
                }

                m_log.WarnFormat(
                    "[GRID AGENT INVENTORY]: Rejecting request since source {0} was not in the list of trusted sources",
                    peer);

                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// Determines a route between two or more points.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="SolveException"></exception>
        public SolveResult Solve(SolveParameters parameters, Token token)
        {
            UriBuilder uriBuilder = new UriBuilder(this.Uri);
            uriBuilder.Path += "solve";
            string qs = parameters.ToQueryString();
            if (token != null)
            {
                qs = string.Format("token={1}&{0}&f=json", qs, token.AccessToken);
            }
            uriBuilder.Query = qs;

            var request = HttpWebRequest.Create(uriBuilder.Uri) as HttpWebRequest;
            string json = null;
            using (var response = request.GetResponse() as HttpWebResponse)
            {
                var stream = response.GetResponseStream();
                using (var streamReader = new StreamReader(stream))
                {
                    json = streamReader.ReadToEnd();
                }
            }

            // If the request returned an error, throw an exception.
            var errorResponse = JsonConvert.DeserializeObject<SolveErrorResponse>(json);
            if (errorResponse.error != null)
            {
                throw new SolveException(errorResponse);
            }

            SolveResult solveResult = null;

            solveResult = JsonConvert.DeserializeObject<SolveResult>(json);

            return solveResult;
        }
        public static Uri CreateRoute(Uri requestUrl, string path, string query = null)
        {
            if (requestUrl == null)
            {
                throw new ArgumentNullException("requestUrl");
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            var builder = new UriBuilder(requestUrl)
            {
                Path = path,
                Query = query
            };

            // Don't include port 80/443 in the Uri.
            if (builder.Uri.IsDefaultPort)
            {
                builder.Port = -1;
            }

            return builder.Uri;
        }
        private string ApiCall(string action, NameValueCollection queries = null)
        {
            string result = string.Empty;

            try {

                // if null, create new one, even it's empty
                if (queries == null)
                    queries = new NameValueCollection();

                // always attach access_token
                queries.Add("access_token", this.AccessToken);

                var requestUrl = new UriBuilder();
                requestUrl.Scheme = "https";
                requestUrl.Host = "api.instagram.com";
                requestUrl.Path = action;
                requestUrl.Query = string.Join("&", queries.AllKeys.Select(c => string.Format("{0}={1}", HttpUtility.UrlEncode(c), HttpUtility.UrlEncode(queries[c]))));

                var req = (HttpWebRequest)WebRequest.Create(requestUrl.ToString());
                var res = (HttpWebResponse)req.GetResponse();

                using (StreamReader stream = new StreamReader(res.GetResponseStream())) {
                    result = stream.ReadToEnd();
                    stream.Close();
                }
            } catch (Exception ex) {
                if (ex.Message.Contains("400")) {
                    // invalid response
                    result = ex.Message;
                }
            }

            return result;
        }
        /// <summary>
        /// Get the Enqueue URI
        /// </summary>
        /// <returns>Enqueue URI</returns>
        public Uri GetEnqueueUri()
        {
            //access the Connector API
            UriBuilder enqueueUri = new UriBuilder(Settings.RainierUri);
            enqueueUri.Path = Program.EnqueueRelativePath + Settings.RecurringJobId;

            // Data package
            if (Settings.IsDataPackage && !string.IsNullOrEmpty(Settings.Company))
            {
                enqueueUri.Query = "company=" + Settings.Company;
            }

            // Individual file
            else
            {
                string enqueueQuery = "entity=" + Settings.EntityName;
                // Append company if specified
                if (!string.IsNullOrEmpty(Settings.Company))
                {
                    enqueueQuery += "&company=" + Settings.Company;
                }

                enqueueUri.Query = enqueueQuery;
            }

            return enqueueUri.Uri;
        }
        public static Uri CreateCallBackUri(string providerKey, Uri requestUrl,
                                            string path = "/authentication/authenticatecallback")
        {
            if (string.IsNullOrEmpty(providerKey))
            {
                throw new ArgumentNullException("providerKey");
            }

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

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            var builder = new UriBuilder(requestUrl)
            {
                Path = path,
                Query = "providerkey=" + providerKey.ToLowerInvariant()
            };

            // Don't include port 80/443 in the Uri.
            if (builder.Uri.IsDefaultPort)
            {
                builder.Port = -1;
            }

            return builder.Uri;
        }
Beispiel #38
0
        public static Uri BuildUri(Uri baseUri, Version requestedApiVersion, string path, IQueryString queryString)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }

            UriBuilder builder = new UriBuilder(baseUri);

            if (requestedApiVersion != null)
            {
                builder.Path += string.Format(CultureInfo.InvariantCulture, "v{0}/", requestedApiVersion);
            }

            if (!string.IsNullOrEmpty(path))
            {
                builder.Path += path;
            }

            if (queryString != null)
            {
                builder.Query = queryString.GetQueryString();
            }

            return builder.Uri;
        }
    public void Search(string searchtag)
    {
      if (searchtag == null) return;
      if (searchtag == string.Empty) return;
      m_imageList.DisposeAndClearList();
      try
      {
        UriBuilder builder = new UriBuilder();
        builder.Host = "images.google.nl";
        builder.Path = "/images";
        builder.Query = String.Format("q={0}", searchtag);

        // Make the Webrequest
        WebRequest req = WebRequest.Create(builder.Uri.AbsoluteUri);
        try
        {
          // Use the current user in case an NTLM Proxy or similar is used.
          // wr.Proxy = WebProxy.GetDefaultProxy();
          req.Proxy.Credentials = CredentialCache.DefaultCredentials;
        }
        catch (Exception) {}
        WebResponse result = req.GetResponse();
        using (Stream ReceiveStream = result.GetResponseStream())
        {
          StreamReader sr = new StreamReader(ReceiveStream);
          string strBody = sr.ReadToEnd();
          Parse(strBody);
        }
      }
      catch (Exception ex)
      {
        Log.Warn("get failed:{0}", ex.Message);
      }
    }
Beispiel #40
0
        public static string RpcToWcf(EndpointBindingInfo bindingInfo)
        {
            if (bindingInfo.Protseq == RpcProtseq.ncacn_ip_tcp)
            {
                return new UriBuilder(Uri.UriSchemeNetTcp, bindingInfo.NetworkAddr, Int32.Parse(bindingInfo.EndPoint)).Uri.ToString();
            }
            if (bindingInfo.Protseq == RpcProtseq.ncalrpc)
            {

                var path = bindingInfo.EndPoint;

                var builder = new UriBuilder(UriSchemeIpc,null);
                builder.Path = path;
                //TODO: use builder to build with empty host ///
                //builder.Host = string.Empty;
                //return builder.Uri.ToString();
                string local = ":///";
                return builder.Scheme + local + builder.Path;
            }
            if (bindingInfo.Protseq == RpcProtseq.ncacn_np)
            {
                var path = bindingInfo.EndPoint.Replace(@"\pipe", string.Empty).Replace("\\", "/");
                var builder = new UriBuilder(Uri.UriSchemeNetPipe, bindingInfo.NetworkAddr);
                builder.Path = path;
                return builder.Uri.ToString();
            }
            throw new NotImplementedException(bindingInfo.Protseq + " not implemented");
        }
 public RemoteMsmqGrantReadWriteTask(PhysicalServer server, string queueName, string group)
 {
     _server = server;
     _group = group;
     var ub = new UriBuilder("msmq", server.Name) { Path = queueName };
     _address = new QueueAddress(ub.Uri);
 }
 /// <summary>
 /// Combines the specified OPC DA server URL with path.
 /// </summary>
 /// <param name="url">The OPC DA server URL.</param>
 /// <param name="path">The path.</param>
 /// <returns>
 /// The OPC DA server URL with path.
 /// </returns>
 public static Uri Combine(Uri url, string path)
 {
     var uriBuilder = new UriBuilder(url);
     uriBuilder.Path = string.Concat(uriBuilder.Path, @"/", Uri.EscapeDataString(path)); //workaround for split ProgId & ItemId in URL path
     Uri result = uriBuilder.Uri;
     return result;
 }
        private static string Sign(string url, string appSid, string appKey)
        {
            // Add AppSid parameter.
            UriBuilder uriBuilder = new UriBuilder(url);

            if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
                uriBuilder.Query = uriBuilder.Query.Substring(1) + "&appSID=" + appSid;
            else
                uriBuilder.Query = "appSID=" + appSid;

            // Remove final slash here as it can be added automatically.
            uriBuilder.Path = uriBuilder.Path.TrimEnd('/');

            // Compute the hash.
            byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
            HMACSHA1 algorithm = new HMACSHA1(privateKey);

            byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
            byte[] hash = algorithm.ComputeHash(sequence);
            string signature = Convert.ToBase64String(hash);

            // Remove invalid symbols.
            signature = signature.TrimEnd('=');
            signature = HttpUtility.UrlEncode(signature);

            // Convert codes to upper case as they can be updated automatically.
            signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());

            // Add the signature to query string.
            return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
        }
        public static bool InvokeDeleteContent(int id)
        {
            try
            {
                UriBuilder getQuestionsUri = new UriBuilder(Properties.Settings.Default.CloudCommunityUrlNew + @"/Resource/Service/Content/" + id.ToString());
                string appSecurityToken = Properties.Settings.Default.LiveIdToken;
                string body;
                WebRequest request = WebRequest.Create(getQuestionsUri.Uri);
                request.Method = "Delete";
                request.ContentLength = 0;
                request.Headers.Add(@"LiveUserToken", appSecurityToken);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseStreamReader = new StreamReader(responseStream))
                        {
                            body = responseStreamReader.ReadToEnd();
                            body = body.Substring(body.IndexOf('>') + 1);
                            body = body.Substring(0, body.IndexOf('<'));
                            return Boolean.Parse(body);
                        }
                    }
                }
            }
            catch
            {

            }
            return false;
        }
        static CommonLinkUtility()
        {
            try
            {
                var uriBuilder = new UriBuilder(Uri.UriSchemeHttp, "localhost");
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    var u = HttpContext.Current.Request.GetUrlRewriter();
                    uriBuilder = new UriBuilder(u.Scheme, "localhost", u.Port);
                }
                _serverRoot = uriBuilder.Uri;

                try
                {
                    _hostname = Dns.GetHostName();
                }
                catch { }

                DocServiceApiUrl = WebConfigurationManager.AppSettings["files.docservice.url.api"] ?? "";
            }
            catch (Exception error)
            {
                LogManager.GetLogger("ASC.Web").Error(error.StackTrace);
            }
        }
Beispiel #46
0
        public WebSearchCommand(string searchKeyword, string defaultUri, string searchUri)
        {
            _searchKeyword = searchKeyword;
            _defaultUri = defaultUri;
            _searchUri = searchUri;

            string rootUri = (new Uri(defaultUri)).GetLeftPart(UriPartial.Authority);
            UriBuilder faviconUri = new UriBuilder(rootUri);
            faviconUri.Path = "/apple-touch-icon.png";

            _icon = GetWebIcon(faviconUri.ToString());
            if (_icon == null)
            {
                faviconUri.Path = "/favicon.ico";
                _icon = GetWebIcon(faviconUri.ToString());
            }

            if (_icon != null)
            {
                // TODO: hack
                try
                {
                    _icon.MakeTransparent();
                }
                catch (InvalidOperationException)
                {
                    // Actual icons cannot be made transparent (they already are)
                }
            }
        }
        public string GetAccessToken(string Code, string Mrfid)
        {
            string parameters   = "";
            var    redirect_uri = new System.UriBuilder(Request.Url.AbsoluteUri)
            {
                Path  = Url.Action("linkedin", "linkedin"),
                Query = null,
            }.Uri.AbsoluteUri + "?mrfid=" + Mrfid;

            using (WebClient wc = new WebClient())
            {
                System.Collections.Specialized.NameValueCollection postData =
                    new System.Collections.Specialized.NameValueCollection()
                {
                    { "grant_type", "authorization_code" },
                    { "code", Code },
                    { "redirect_uri", redirect_uri },
                    { "client_id", ClientId },
                    { "client_secret", ClientSecret }
                };
                parameters = Encoding.UTF8.GetString(wc.UploadValues("https://www.linkedin.com/oauth/v2/accessToken/", postData));
            }
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            var accessToken = JsonConvert.DeserializeObject <AccessToken>(parameters);

            return(accessToken.access_token);
        }
Beispiel #48
0
        void ShowOccasionUI()
        {
            string   eventIdString     = eventId.ToString();
            DateTime currentDate       = DateTime.Now;
            string   currentDateString = currentDate.ToString("yyyy-MM-dd");

            Debug.Log(currentDateString);

            System.UriBuilder getTodaysOccasionsURL = UriWithOptionalPort(
                httpPort,
                "api/v1/events/" + eventIdString + "/occasions/upcoming?onOrAfterDate=" + currentDateString
                );

            HTTPRequest req = new HTTPRequest(
                getTodaysOccasionsURL.Uri,
                HTTPMethods.Get,
                (request, response) => {
                Debug.Log("req for occasions complete");
                if (response.IsSuccess)
                {
                    var results = JsonMapper.ToObject(response.DataAsText);
                    Debug.Log(results);

                    int occasionCount;
                    if (results.Count <= 3)
                    {
                        occasionCount = results.Count;
                    }
                    else
                    {
                        occasionCount = 3;
                    }

                    occasionIDs = new string[occasionCount];

                    for (int i = 0; i < occasionCount; i++)
                    {
                        JsonData occasionForToday         = results[i];
                        System.DateTime occasionStartTime = System.DateTime.Parse((string)occasionForToday["startDateTime"]);
                        string showDateTime          = occasionStartTime.ToString("MMM d h:mmtt");
                        UnityEngine.UI.Text btnLabel = occasionUI[i].GetComponentInChildren <UnityEngine.UI.Text>();
                        btnLabel.text = showDateTime;
                        int id        = (int)occasionForToday["id"];
                        Debug.Log(id);
                        occasionIDs[i] = id.ToString();
                        Debug.Log(occasionIDs[i]);
                        occasionUI[i].SetActive(true);
                    }
                }
                else
                {
                    Debug.Log("Error " + response.StatusCode + ": " + response.Message);
                }
            }
                );

            Debug.Log("sending req for occasions");
            req.Send();
        }
Beispiel #49
0
        //ported from IISOOB\projects\ui\wm\Deployment\Data\Profiles\PublishProfile.cs
        private string ConstructServiceUrlForDeployThruWMSVC(string serviceUrl)
        {
            const string https     = "https://";
            const string http      = "http://";
            const string msddepaxd = "msdeploy.axd";

            System.UriBuilder serviceUriBuilder = null;

            // We want to try adding https:// if there is no schema. However abc:123 is parsed as a schema=abc and path=123
            // so the goal is to isolate this case and add the https:// but allow for http if the user chooses to
            // since we do not allow for any schema other than http or https, it's safe to assume we can add it if none exist
            try
            {
                if (!(serviceUrl.StartsWith(http, StringComparison.OrdinalIgnoreCase) || serviceUrl.StartsWith(https, StringComparison.OrdinalIgnoreCase)))
                {
                    serviceUrl = string.Concat(https, serviceUrl.TrimStart());
                }

                serviceUriBuilder = new UriBuilder(serviceUrl);
            }
            catch (NullReferenceException)
            {
                return(string.Empty);
            }
            catch (ArgumentNullException)
            {
                return(string.Empty);
            }
            catch (UriFormatException)
            {
                return(serviceUrl);
            }

            // if the user did not explicitly defined a port
            if (serviceUrl.IndexOf(":" + serviceUriBuilder.Port.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) == -1)
            {
                serviceUriBuilder.Port = 8172;
            }

            // user did not explicitly set a path
            if (string.IsNullOrEmpty(serviceUriBuilder.Path) || serviceUriBuilder.Path.Equals("/", StringComparison.OrdinalIgnoreCase))
            {
                serviceUriBuilder.Path = msddepaxd;
            }

            // user did not explicityly set the scheme
            if (serviceUrl.IndexOf(serviceUriBuilder.Scheme, StringComparison.OrdinalIgnoreCase) == -1)
            {
                serviceUriBuilder.Scheme = https;
            }

            if (string.IsNullOrEmpty(serviceUriBuilder.Query))
            {
                string[] fragments = SiteName.Trim().Split(new char[] { '/', '\\' });
                serviceUriBuilder.Query = "site=" + fragments[0];
            }

            return(serviceUriBuilder.Uri.AbsoluteUri);
        }
        public virtual ActionResult ProcessAngularRequest()
        {
            if (AtPreviewMode() && InvalidCrossSiteAuth())
            {
                return(new HttpUnauthorizedResult());
            }

            CmsEngine.Response response;
            //try
            //{
#if (DEBUG)
            return(this.ProcessFakeAngularRequest());
#else
            var origUrl = _httponContextBase.Request.Url;
            if (origUrl == null)
            {
                response = new CmsEngine.Response {
                    Type = CmsEngine.ResponseType.Error
                };
            }
            else
            {
                var absolutePath = origUrl.AbsolutePath.ToLower().Replace("/templates", "").Replace(".html", "").Replace(".htm", "");
                var uriBuilder   = new System.UriBuilder(origUrl.AbsoluteUri)
                {
                    Path = absolutePath
                };
                response = _cmsEngine.ProcessRequest(uriBuilder.Uri, new MvcRequestContext(ControllerContext, ViewData, TempData));
            }
#endif
            //}
            //catch (Exception ex)
            //{
            //    Log.Error("Internal CMS error.", ex);
            //    return
            //        new FilePathResult(
            //            string.Format(_configurations.ErrorPagePath, (int)HttpStatusCode.InternalServerError,
            //                _cultureUtility.GetCultureCode()), MediaTypeNames.Text.Html);
            //}

            switch (response.Type)
            {
            case CmsEngine.ResponseType.OK:
                return(Content(response.Body));

            case CmsEngine.ResponseType.PageNotFound:
                return
                    (new FilePathResult(
                         string.Format(_configurations.ErrorPagePath, (int)HttpStatusCode.NotFound,
                                       _cultureUtility.GetCultureCode()), MediaTypeNames.Text.Html));

            default:
                return
                    (new FilePathResult(
                         string.Format(_configurations.ErrorPagePath, (int)HttpStatusCode.InternalServerError,
                                       _cultureUtility.GetCultureCode()), MediaTypeNames.Text.Html));
            }
        }
Beispiel #51
0
        private static string CreateHubUri(Uri connection)
        {
            UriBuilder uri = new System.UriBuilder(uri: connection);

            uri.Path += "stockshub/";
            var hubUri = uri.ToString();

            return(hubUri);
        }
Beispiel #52
0
        public async Task <string> testrequest()
        {
            var Builder  = new System.UriBuilder($"{URI}/entries?category=animals&https=true");
            var response = await httpClient.GetAsync(Builder.Uri);

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

            return(context);
        }
Beispiel #53
0
        public async Task <string> testRequest()
        {
            var Builder  = new System.UriBuilder($"{URI}/api/getFlight{1}");
            var response = await restClient.GetAsync(Builder.Uri);

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

            return(context);
        }
Beispiel #54
0
        // GET: Login
        public ActionResult SendResetEmail(string email)
        {
            Random rand = new Random();
            string key  = "";
            int    i    = 0;

            for (i = 0; i < 16; i++)
            {
                int[] randoms   = new int [] { rand.Next(48, 58), rand.Next(65, 91), rand.Next(97, 123) };
                int   rand_indx = rand.Next(0, 3);
                int   curr_byte = randoms[rand_indx];
                char  c         = (char)curr_byte;
                key += c;
            }
            var urlBuilder =
                new System.UriBuilder(Request.Url.AbsoluteUri)
            {
                Path  = Url.Action("ResetPassword", "Login"),
                Query = null,
            };

            Uri    uri = urlBuilder.Uri;
            string url = urlBuilder.ToString();
            String m   = "<a href='" + url + "?key=" + key + "'>לחץ כאן להמשך איפוס סיסמא</a>";

            GMailer.GmailUsername = "******";
            GMailer.GmailPassword = "******";
            var     body   = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
            GMailer mailer = new GMailer();

            mailer.ToEmail = email;
            mailer.Subject = "מערכת ניהול מכרזים - איפוס סיסמא";
            mailer.Body    = string.Format(body, "*****@*****.**", "מערכת לניהול מכרזים, לא להגיב!", m);
            mailer.IsHtml  = true;

            mailer.Send();
            bool exist = false;

            foreach (String s in LoginController.email_key.Keys)
            {
                if (s.CompareTo(email) == 0)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                LoginController.email_key.Remove(email);
            }

            LoginController.email_key.Add(email, key);



            return(Json("Sent", JsonRequestBehavior.AllowGet));
        }
Beispiel #55
0
        static string BuildOptions(Options opts)
        {
            string resultUrl = string.Empty;

            if (opts.Url.IsValidURL())
            {
                UriBuilder builder = new System.UriBuilder(cdcUrl);
                var        query   = HttpUtility.ParseQueryString(string.Empty);

                query["url"]      = opts.Url + (opts.ExactUrl ? "" : "/*");
                query["fl"]       = "urlkey,digest,timestamp,original,mimetype,statuscode,length";
                query["collapse"] = "digest";
                query["pageSize"] = "1";
                query["gzip"]     = "false";

                if (!opts.AllHttpStatus)
                {
                    query["filter"] = "statuscode:200";
                }

                if (opts.From.IsLong())
                {
                    query["from"] = opts.From.Trim();
                }

                if (opts.To.IsLong())
                {
                    query["to"] = opts.To.Trim();
                }

                //if(opts.ListOnly)
                //    query["output"] = "json";

                if (opts.Limit.IsInteger())
                {
                    query["limit"] = opts.Limit.Trim();
                }


                builder.Query = query.ToString();
                resultUrl     = builder.ToString();

                if (!String.IsNullOrWhiteSpace(opts.OnlyFilter))
                {
                    resultUrl = builder.ToString() + "&filter=original:" + opts.OnlyFilter;
                }
                if (!String.IsNullOrWhiteSpace(opts.ExcludeFilter))
                {
                    resultUrl = builder.ToString() + "&filter=!original:" + opts.ExcludeFilter;
                }

                //resultUrl = builder.ToString() + "&collapse=timestamp:" + opts.Collapse.ToString();
            }

            return(resultUrl);
        }
Beispiel #56
0
        public Uri Build()
        {
            var queryString   = string.Join("&", queryParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray());
            var uriWithParams = new System.UriBuilder(uri)
            {
                Query = (uri.Query + "&" + queryString).TrimStart('&', '?')
            }.Uri;

            return(uriWithParams);
        }
Beispiel #57
0
        private string GetCallBackUrl()
        {
            var callBackUri = new System.UriBuilder(this.Request.Url.AbsoluteUri)
            {
                Path  = this.Url.Action("OAuthCallBack"),
                Query = null,
            };

            return(callBackUri.ToString());
        }
        public RedirectResult Oauth(string Mrfid)
        {
            var redirect_uri = new System.UriBuilder(Request.Url.AbsoluteUri)
            {
                Path  = Url.Action("linkedin", "linkedin"),
                Query = null,
            }.Uri.AbsoluteUri + "?mrfid=" + Mrfid;;

            return(Redirect(string.Format("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=81744zy6azsoyl&redirect_uri={0}&state={1}&scope=r_basicprofile,w_share", redirect_uri, Guid.NewGuid())));
        }
Beispiel #59
0
        internal Uri GetUri()
        {
            var uriBuilder = new SystemUriBuilder(
                this.MockedUri.Scheme,
                this.MockedUri.Host,
                this.MockedUri.Port,
                this.MockedUri.AbsolutePath);

            return(uriBuilder.Uri);
        }
Beispiel #60
0
        public static void TestMain()
        {
            Uri    apiUri       = new Uri("https://myhost.com?api-version=1.0");
            string resourcePath = "MyResource";

            System.UriBuilder uriBuilder = new System.UriBuilder(apiUri);
            uriBuilder.Path += resourcePath;

            Console.WriteLine(uriBuilder.Uri.ToString());
        }