public void DirectUserToServiceProvider() { UriBuilder ub = new UriBuilder(provider.UserLoginEndpoint); try { QueryParameters oauthParams = new QueryParameters(); oauthParams.Add("client_id", provider.Consumerkey); oauthParams.Add("redirect_uri", connectionToken.ProviderCallbackUrl); oauthParams.Add("response_type", "code"); oauthParams.Add("scope", provider.GetScope()); //ub.SetQueryparameter("client_id", provider.Consumerkey); //ub.SetQueryparameter("redirect_uri", connectionToken.ProviderCallbackUrl); //ub.SetQueryparameter("response_type", "code"); //ub.SetQueryparameter("scope", provider.GetScope()); BeforeDirectingUserToServiceProvider(oauthParams); logger.Debug("Redirecting user for login to " + ub.ToString() + "?" + oauthParams.ToEncodedString()); SocialAuthUser.Redirect(ub.ToString() + "?" + oauthParams.ToEncodedString()); } catch (Exception ex) { logger.Error(ErrorMessages.UserLoginRedirectionError(ub.ToString()), ex); throw new OAuthException(ErrorMessages.UserLoginRedirectionError(ub.ToString()), ex); } }
protected void Page_Load(object sender, EventArgs e) { XmlDocument wsResponseXmlDoc = new XmlDocument(); //http://api.worldweatheronline.com/free/v2/weather.ashx?q=china&format=xml&num_of_days=5&key=x35ahuadjhmdp5rb75ddw2ha //id=jipx(spacetime0) UriBuilder url = new UriBuilder(); url.Scheme = "http";// Same as "http://" String key = System.Configuration.ConfigurationManager.AppSettings["key"]; url.Host = "api.worldweatheronline.com"; url.Path = "free/v1/weather.ashx"; url.Query = "q=china&format=xml&num_of_days=5&key=" + key; String cacheurl = File.ReadAllText("D:/New folder/Visual Studio 2015/Projects/WebApplication1/WebApplication1/cache.txt"); if (String.Compare(cacheurl, url.ToString()) == 0) { wsResponseXmlDoc = new XmlDocument(); wsResponseXmlDoc.Load("D:/New folder/Visual Studio 2015/Projects/WebApplication1/WebApplication1/WeatherServiceCache.xml"); //display the XML response String xmlString = wsResponseXmlDoc.InnerXml; Response.ContentType = "text/xml"; Response.Write(xmlString); } else { //Make a HTTP request to the global weather web service wsResponseXmlDoc = MakeRequest(url.ToString()); int count = 0; while (count != 3 && wsResponseXmlDoc == null) { wsResponseXmlDoc = MakeRequest(url.ToString()); count++; } if (wsResponseXmlDoc != null) { //display the XML response String xmlString = wsResponseXmlDoc.InnerXml; Response.ContentType = "text/xml"; Response.Write(xmlString); String folder = "D:/New folder/Visual Studio 2015/Projects/WebApplication1/WebApplication1"; File.WriteAllText(folder + @"/cache.txt", url.ToString()); wsResponseXmlDoc.Save("D:/New folder/Visual Studio 2015/Projects/WebApplication1/WebApplication1/WeatherServiceCache.xml"); } else { Response.ContentType = "text/html"; Response.Write("<h2> error accessing web service </h2>"); } } }
public static void GetEndpoints(this Session session, string address, bool useInt, bool useExt, string internalPath, string externalPath, out string internalURI, out string externalURI) { internalURI = String.Empty; externalURI = String.Empty; if (!useExt && !useInt) { session.SendError("No endpoints were set."); } else { try { var uriBuilder = new UriBuilder(address); if (useExt) { uriBuilder.Path = externalPath; externalURI = uriBuilder.ToString(); } if (useInt) { uriBuilder.Path = internalPath; internalURI = uriBuilder.ToString(); } } catch { session.SendError("The web service address was invalid."); } } }
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 void SubmitScore() { var userId = User.Identity.GetUserId(); var score = scoreRepo.Find(userId); if (score == null) throw new Exception("Score for user '" + userId + "' not found"); var ltiRequest = ltiRequestsRepo.Find(userId); if (ltiRequest == null) throw new Exception("LtiRequest for user '" + userId + "' not found"); var consumerSecret = consumersRepo.Find(ltiRequest.ConsumerKey).Secret; // TODO: fix outcome address in local edx (no localhost and no https) var uri = new UriBuilder(ltiRequest.LisOutcomeServiceUrl); if (uri.Host == "localhost") { uri.Host = "192.168.33.10"; uri.Port = 80; uri.Scheme = "http"; } var result = OutcomesClient.PostScore(uri.ToString(), ltiRequest.ConsumerKey, consumerSecret, ltiRequest.LisResultSourcedId, score.Value/100.0); if (!result.IsValid) throw new Exception(uri.ToString() + "\r\n\r\n" + result.Message); }
public void ToBcd_Test() { UriBuilder uri = new UriBuilder("http://a/b/c"); uri = uri.AddQuery("name", "z"); Assert.AreEqual("http://a:80/b/c?name=z", uri.ToString()); uri = uri.AddQuery("age", "12"); Assert.AreEqual("http://a:80/b/c?name=z&age=12", uri.ToString()); }
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); }
public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; System.UriBuilder searchBinding = new System.UriBuilder(); searchBinding.Scheme = "http"; searchBinding.Host = searchServer; searchBinding.Path = searchRoot; string searchQuery = searchQueryPrefix; for ( int currentArgument = 1; currentArgument < Arguments.Length; currentArgument++ ) { if ( currentArgument > 1 ) { searchQuery += "%20"; } searchQuery += Arguments[currentArgument].GetArgument(); } searchBinding.Query = searchQuery; _Terminal.WriteTo( new StringBuilder( searchBinding.ToString() + "\n\n" ), ConsoleProcessRedirection.OutputType.StandardOutput ); PageCommand pageRetriever = new PageCommand( _CommandProcessor, new NullTerminal() ); ICommandArgument[] showArguments = new ICommandArgument[2]; showArguments[0] = Arguments[0]; showArguments[1] = new CommandArgument( searchBinding.ToString() ); pageRetriever.PerformCommand( showArguments, out CommandResult ); string resultString = ( (StringBuilder) CommandResult.GetArgument() ).ToString(); string[] links = FindLinks( resultString ); foreach ( string link in links ) { _Terminal.WriteTo( new StringBuilder( link + "\n\n" ), ConsoleProcessRedirection.OutputType.StandardOutput ); } return 0; }
public void SetQueryTest() { UriBuilder uriBuilder = new UriBuilder("http://", "mccoysoftware.uk"); // Note the absence of a '?' character uriBuilder.SetQuery("Title=Mr&FirstName=Arthur&Surname=Dent"); Assert.AreEqual("http://mccoysoftware.uk/?Title=Mr&FirstName=Arthur&Surname=Dent", uriBuilder.ToString()); // Now WITH a '?' uriBuilder.SetQuery("?Title=Mr&FirstName=Ford&Surname=Prefect"); Assert.AreEqual("http://mccoysoftware.uk/?Title=Mr&FirstName=Ford&Surname=Prefect", uriBuilder.ToString()); }
public void RemoveQueryParamTest() { UriBuilder uriBuilder = new UriBuilder("http://", "mccoysoftware.uk"); uriBuilder.Query = "Title=Mr&FirstName=Arthur&Surname=Dent"; // First assert we know the starting string Assert.AreEqual("http://mccoysoftware.uk/?Title=Mr&FirstName=Arthur&Surname=Dent", uriBuilder.ToString()); // Now assert we can remove a parameter (from the middle) uriBuilder.RemoveQueryParam("FirstName"); Assert.AreEqual("http://mccoysoftware.uk/?Title=Mr&Surname=Dent", uriBuilder.ToString()); }
public void SetQueryParamTest() { UriBuilder uriBuilder = new UriBuilder("http://", "mccoysoftware.uk"); uriBuilder.SetQueryParam("FirstName", "Arthur"); Assert.AreEqual("http://mccoysoftware.uk/?FirstName=Arthur", uriBuilder.ToString()); uriBuilder.SetQueryParam("Surname", "Dent"); Assert.AreEqual("http://mccoysoftware.uk/?FirstName=Arthur&Surname=Dent", uriBuilder.ToString()); // It should be possible to overwrite the values set above uriBuilder.SetQueryParam("FirstName", "Ford"); uriBuilder.SetQueryParam("Surname", "Prefect"); Assert.AreEqual("http://mccoysoftware.uk/?FirstName=Ford&Surname=Prefect", uriBuilder.ToString()); }
protected override string GetActionUrl(UrlHelper urlHelper, object routeValues) { var urlString = urlHelper.RouteUrl(this.RouteName, routeValues, urlHelper.RequestContext.HttpContext.Request.Url.Scheme); var urlBuilder = new UriBuilder(urlString); if (!urlBuilder.Host.Contains(".")) // this should be overridable in future, but not now return urlBuilder.ToString(); Interlocked.Increment(ref currentIndex); Interlocked.CompareExchange(ref currentIndex, 1, 6); urlBuilder.Host = string.Format(subdomainPattern, currentIndex) + "." + urlBuilder.Host; return urlBuilder.ToString(); }
public Gmusicbrowser(string hostname, UInt16 port) { var uri = new UriBuilder (); Hostname = hostname; Port = port; uri.Host = hostname; uri.Port = port; uri.Scheme = "http"; try { new Uri (uri.ToString ()); // throw an exception if the URI is invalid } catch { throw new FormatException("Invalid hostname or port"); } gmbClient = new RestClient (uri.ToString()); }
public static void SubmitScore(Slide slide, string userId) { var ltiRequestsRepo = new LtiRequestsRepo(); var consumersRepo = new ConsumersRepo(); var visitsRepo = new VisitsRepo(); var ltiRequest = ltiRequestsRepo.Find(userId, slide.Id); if (ltiRequest == null) throw new Exception("LtiRequest for user '" + userId + "' not found"); var consumerSecret = consumersRepo.Find(ltiRequest.ConsumerKey).Secret; var score = visitsRepo.GetScore(slide.Id, userId); var uri = new UriBuilder(ltiRequest.LisOutcomeServiceUrl); if (uri.Host == "localhost") { uri.Host = "192.168.33.10"; uri.Port = 80; uri.Scheme = "http"; } var outputScore = score / (double)slide.MaxScore; /* Sometimes score is bigger then slide's MaxScore, i.e. in case of manual checking */ if (score > slide.MaxScore) outputScore = 1; var result = OutcomesClient.PostScore(uri.ToString(), ltiRequest.ConsumerKey, consumerSecret, ltiRequest.LisResultSourcedId, outputScore); if (!result.IsValid) throw new Exception(uri + "\r\n\r\n" + result.Message); }
public static string ReplacingQueryStringParameter(string currentPageUrl, string ParameterToReplace, string NewValue) { var myquery = AnalyseQueryString(currentPageUrl); myquery[ParameterToReplace] = NewValue; var resultQuery = new StringBuilder(); bool isFirst = true; foreach (KeyValuePair<string, string> pair in myquery) { if (!isFirst) { resultQuery.Append("&"); } resultQuery.Append(pair.Key); resultQuery.Append("="); resultQuery.Append(pair.Value); isFirst = false; } var Builder = new UriBuilder(currentPageUrl) { Query = resultQuery.ToString() }; return Builder.ToString(); }
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); }
private string GetRedirectUri() { var redirectUri = new UriBuilder(Request.Url); redirectUri.Path = Request.ApplicationPath + "OAuth/AuthorizationCodeCallback"; redirectUri.Query = null; return redirectUri.ToString(); }
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; }
public static void SubmitScore(Slide slide, string userId) { var ltiRequestsRepo = new LtiRequestsRepo(); var consumersRepo = new ConsumersRepo(); var visitersRepo = new VisitersRepo(); var ltiRequest = ltiRequestsRepo.Find(userId, slide.Id); if (ltiRequest == null) throw new Exception("LtiRequest for user '" + userId + "' not found"); var consumerSecret = consumersRepo.Find(ltiRequest.ConsumerKey).Secret; var score = visitersRepo.GetScore(slide.Id, userId); // TODO: fix outcome address in local edx (no localhost and no https) var uri = new UriBuilder(ltiRequest.LisOutcomeServiceUrl); if (uri.Host == "localhost") { uri.Host = "192.168.33.10"; uri.Port = 80; uri.Scheme = "http"; } var result = OutcomesClient.PostScore(uri.ToString(), ltiRequest.ConsumerKey, consumerSecret, ltiRequest.LisResultSourcedId, score / (double)slide.MaxScore); if (!result.IsValid) throw new Exception(uri + "\r\n\r\n" + result.Message); }
public string BuildAuthorizationRequestUrl(RequestToken requestToken, string callbackUrl) { var builder = new UriBuilder(_apiBaseUrl); builder.Path = builder.Path.TrimEnd('/') + "/" + PortalUserAuthorizePath.TrimStart('/'); builder.Query = string.Format("oauth_token={0}&oauth_callback={1}", requestToken.Value, callbackUrl); return builder.ToString(); }
public Task Invoke(IDictionary<string, object> env) { var request = new ServerRequest(env); var response = new Gate.Response(env); if (!request.Url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { var builder = new UriBuilder(request.Url); builder.Scheme = "https"; if (request.Url.IsDefaultPort) { builder.Port = -1; } response.SetHeader("Location", builder.ToString()); response.StatusCode = 302; return TaskAsyncHelper.Empty; } else { return _next(env); } }
public async Task<ActionResult> Get( string gw_address, int gw_port, string gw_id, string url, string mac) { LoginModel newItem = new LoginModel { gw_address = gw_address, gw_port = gw_port, gw_id = gw_id, url = url, mac = mac }; WifidogContext.LoginData.Add(newItem); await WifidogContext.SaveChangesAsync(); Response.Cookies.Append("loginmodelid", newItem.LoginModelId.ToString()); // Redirect to the basic auth web page UriBuilder uriBuilder = new UriBuilder() { Host = "authcloudportal.azurewebsites.net", Path = "basicauth/login", Query = string.Format("gw_address={0}&gw_port={1}&gw_id={2}&url={3}&loginmodelid={4}", gw_address, gw_port, gw_id, url, newItem.LoginModelId) }; return Redirect(uriBuilder.ToString()); }
/// <summary> /// Get all bulk activities status filtered by status and/or type. /// </summary> /// <param name="type">Bulk activity type</param> /// <param name="status">Bulk activity status</param> /// <returns>A list of StatusReport</returns> /// <exception cref="CtctException">CtctException.</exception> public IList<StatusReport> GetBulkActivitiesStatus(BulkActivityType type, BulkActivityStatus status) { string url = String.Concat(Settings.Endpoints.Default.BaseUrl, Settings.Endpoints.Default.Activities); var uriBuilder = new UriBuilder(url); var query = HttpUtility.ParseQueryString(uriBuilder.Query); if (type != BulkActivityType.ALL) { query["type"] = Enum.GetName(typeof(BulkActivityType), type); } if (status != BulkActivityStatus.ALL) { query["status"] = Enum.GetName(typeof(BulkActivityStatus), status); } uriBuilder.Query = query.ToString(); url = uriBuilder.ToString(); RawApiResponse response = RestClient.Get(url, UserServiceContext.AccessToken, UserServiceContext.ApiKey); try { var bulkStatusReport = response.Get<List<StatusReport>>(); return bulkStatusReport; } catch (Exception ex) { throw new CtctException(ex.Message, ex); } }
//Initialze Catapult specific data public static void Configure(IAppBuilder app) { var appSettings = ConfigurationManager.AppSettings; var catapult = Client.GetInstance(appSettings["userId"], appSettings["apiToken"], appSettings["apiSecret"]); var phoneNumber = appSettings["phoneNumberForCallbacks"]; app.Use(async (context, next) => { var builder = new UriBuilder(context.Request.Uri); builder.Path = "/"; builder.Query = ""; var baseUrl = builder.ToString(); baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); //remove last '/' if (string.IsNullOrEmpty(phoneNumber)) { //reserve a phone numbers for callbacks if need var numbers = await AvailableNumber.SearchLocal(catapult, new Dictionary<string, object> { { "state", "NC" }, { "city", "Cary" }, { "quantity", 1 } }); phoneNumber = numbers.First().Number; await PhoneNumber.Create(catapult, new Dictionary<string, object> { { "number", phoneNumber } }); var config = WebConfigurationManager.OpenWebConfiguration("~"); config.AppSettings.Settings.Add("phoneNumberForCallbacks", phoneNumber); config.Save(ConfigurationSaveMode.Minimal, false); ConfigurationManager.RefreshSection("appSettings"); } // make them alailvable from any request handlers context.Set("phoneNumberForCallbacks", phoneNumber); context.Set("catapultClient", catapult); context.Set("baseUrl", baseUrl); await next(); }); }
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)); }
public override string GetMediaUrl(MediaItem item, MediaUrlOptions options) { string mediaUrl = base.GetMediaUrl(item, options); if (string.IsNullOrEmpty(mediaUrl)) return mediaUrl; int versionNumber = item.InnerItem.Version.Number; string langIsoCode = item.InnerItem.Language.CultureInfo.TwoLetterISOLanguageName; string updatedDate = item.InnerItem.Statistics.Updated.ToString("s"); NameValueCollection parameters = new NameValueCollection { {"v", versionNumber.ToString()}, {"lang", langIsoCode}, {"modified", updatedDate} }; if (options.AlwaysIncludeServerUrl) { UriBuilder uriBuilder = new UriBuilder(mediaUrl); NameValueCollection queryString = HttpUtility.ParseQueryString(uriBuilder.Query); queryString.Add(parameters); uriBuilder.Query = ToQueryString(queryString); return uriBuilder.ToString(); } StringBuilder sb = new StringBuilder(mediaUrl); string seperator = "?"; if (mediaUrl.Contains(seperator)) seperator = "&"; foreach (string key in parameters.Keys) { sb.AppendFormat("{0}{1}={2}", seperator, key, parameters[key]); seperator = "&"; } return sb.ToString(); }
private void RegisterClasspath(CodeMemberMethod composeMethod, XmlElement classpathElement, IList assemblies) { XmlNodeList children = classpathElement.ChildNodes; for (int i = 0; i < children.Count ; i++) { if (children[i] is XmlElement) { XmlElement childElement = (XmlElement) children[i]; string fileName = childElement.GetAttribute(FILE); string urlSpec = childElement.GetAttribute(URL); UriBuilder url = null; if (urlSpec != null && urlSpec.Length > 0) { url = new UriBuilder(urlSpec); assemblies.Add(url.ToString()); } else { if (!File.Exists(fileName)) { throw new IOException(Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName + " doesn't exist"); } assemblies.Add(fileName); } } } }
public async Task Given_Remote_Host_Not_Listening_When_Sending_Then_Transport_Service_Throws_TransportException() { var endpoint = new UriBuilder { Scheme = "http", Host = "localhost", Port = 52180, Path = "/platibus.test/" }.Uri; var transportService = new HttpTransportService(endpoint, ReadOnlyEndpointCollection.Empty, new InMemoryMessageQueueingService(), null, new InMemorySubscriptionTrackingService()); var message = new Message(new MessageHeaders { {HeaderName.ContentType, "text/plain"}, {HeaderName.MessageId, Guid.NewGuid().ToString()}, {HeaderName.Destination, endpoint.ToString()} }, "Hello, world!"); Exception exception = null; try { await transportService.SendMessage(message); } catch (AggregateException ae) { exception = ae.InnerExceptions.FirstOrDefault(); } catch (Exception ex) { exception = ex; } Assert.That(exception, Is.Not.Null); Assert.That(exception, Is.InstanceOf<ConnectionRefusedException>()); }
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 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 = "不明路径"; } }
public List<ArticleInfo> ScrapePage(Section section, int page) { var builder = new UriBuilder(section.Host); builder.Path += section.RelativeUrl; var url = builder.ToString().AddQueryParameterToUrl("page", page); var docNode = Utilities.DownloadPage(url); var articleDivs = docNode.SelectNodes("//div[@class='category-headline-item']"); var result = new List<ArticleInfo>(); foreach (var articleDiv in articleDivs) { try { result.Add(ParseArticleInfoDiv(articleDiv)); } catch (CommonParsingException e) { } catch (Exception e) { e.Data["articleDiv"] = articleDiv.OuterHtml; _log.Error("An error occurred while parsing article info div.", e); } } return result; }
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")); }
public void ModifyResponseToRedirectToSessionAwareUrl(NancyContext context, SessionIdentificationData sessionIdentificationData, string parameterName) { if (context == null) throw new ArgumentNullException("context"); if (sessionIdentificationData == null) throw new ArgumentNullException("sessionIdentificationData"); if (string.IsNullOrWhiteSpace(parameterName)) throw new ArgumentNullException("parameterName"); if (context.Request == null) throw new ArgumentException("The specified context does not contain a request", "context"); if (context.Response == null) throw new ArgumentException("The specified context does not contain a response", "context"); var originalUri = (Uri) context.Request.Url; var uriBuilder = new UriBuilder(originalUri); var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query); queryParameters.Set(parameterName, sessionIdentificationData.ToString()); var newQueryString = string.Empty; if (queryParameters.Count > 0) { var newQueryBuilder = new StringBuilder(); foreach (var paramName in queryParameters.AllKeys) { newQueryBuilder.Append(string.Format("{0}={1}&", paramName, HttpUtility.UrlEncode(queryParameters[paramName]))); } newQueryString = newQueryBuilder.ToString().TrimEnd('&'); } uriBuilder.Query = newQueryString; var redirectUrl = uriBuilder.ToString(); context.Response.StatusCode = HttpStatusCode.Found; context.Response.Headers["Location"] = redirectUrl; }
private static string CreateHubUri(Uri connection) { UriBuilder uri = new System.UriBuilder(uri: connection); uri.Path += "stockshub/"; var hubUri = uri.ToString(); return(hubUri); }
// 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)); }
private string GetCallBackUrl() { var callBackUri = new System.UriBuilder(this.Request.Url.AbsoluteUri) { Path = this.Url.Action("OAuthCallBack"), Query = null, }; return(callBackUri.ToString()); }
// [ValidateAntiForgeryToken] public async Task <IActionResult> ExternalLoginConfirmation([FromBody] ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { //return View("ExternalLoginFailure"); return(BadRequest(Errors.AddErrorToModelState("", "", ModelState))); } var user = new AppUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { // 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 code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var urlBuilder = new System.UriBuilder(_configuration["SiteUrl"]) { Path = Url.Content("~/account/confirm-email"), Query = "userId=" + user.Id + "&code=" + code }; var callbackUrl = urlBuilder.ToString(); var response = await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); // await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return(RedirectToLocal(returnUrl)); } // if (result.Succeeded) // { // await _signInManager.SignInAsync(user, isPersistent: false); // _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); // return RedirectToLocal(returnUrl); // } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return(View(model)); }
/// <summary> /// full url path /// </summary> /// <param name="virtualPath"></param> /// <returns></returns> public string GetAbsoluteUrl(string virtualPath) { // http://benjii.me/2015/05/get-the-absolute-uri-from-asp-net-mvc-content-or-action/ var urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.Content(virtualPath), Query = null, }; return(urlBuilder.ToString()); }
IEnumerator loadAsset(string url) { string path = Application.absoluteURL + dir + url; path = Path.GetFullPath(path); System.UriBuilder uriBuilder = new System.UriBuilder(path); uriBuilder.Scheme = "file"; Debug.Log(uriBuilder.ToString()); WWW www = new WWW(uriBuilder.ToString()); //AssetBundle.LoadFromFileAsync("F:/New Unity Project (2)/Assets/AssetBundles/thirdpc"); yield return(www); AssetBundle ab = www.assetBundle; if (ab == null) { Debug.Log("加载失败"); } go = ab.LoadAsset(url); }
private void ConnectInternal(string address, int port) { string scheme = UseSecureClient ? "wss://" : "ws://"; Uri uri = new System.UriBuilder(scheme, address, port, "game").Uri; if (Mirror.LogFilter.Debug) { Debug.Log("attempting to start client on: " + uri.ToString()); } ClientInterface = new WebSocketClient(uri); ClientInterface.Connect(); }
public ActionResult Api(string id) { var urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.HttpRouteUrl("DefaultApi", new { controller = "Dummy", id = id }), Query = null, }; Uri uri = urlBuilder.Uri; string url = urlBuilder.ToString(); ViewBag.Url = url; ViewBag.Id = id; return(View()); }
public ActionResult ForgotPassword(FormCollection formCollection) { TempData["SuccessMsg"] = "<strong> Please check your email to reset your password.</strong>"; var email = formCollection.Get("txtUsername").ToString(); try { using (var context = new GameNepalEntities()) { var user = context.Users.Where(x => x.isActive && x.email.Equals(email)).FirstOrDefault(); if (user != null) { var token = GenerateToken(user.id); var hashedUserEmail = Helper.EncodeToBase64(user.email); var urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.Action("ValidateToken", "Home"), Query = "uid=" + hashedUserEmail + "&token=" + token, }; Uri uri = urlBuilder.Uri; string url = urlBuilder.ToString(); var message = "Dear " + user.firstname + ", <br/> To securely reset your password, please click the link below:<br/>" + "<a target='_blank' href= '" + url + "'> Click Here </a>" + "<br/> <br/> Or you can copy paste this text in a new tab. <br/> " + url + "<br/> <br/> <b> This link is only valid for 30 minutes from the time it is first generated.</b> If you do not reset your password " + "during this time, you will need to submit another password reset request."; Helper.Email(user.email, message); } } } catch (Exception e) { TempData["SuccessMsg"] = null; TempData["ForgotPwdErrorMsg"] = "<strong> Some error occurred processing your request.</strong>"; } return(View()); }
public async Task <TokenResponse> Refresh() { var payload = new QueryParameterCollection { { "grant_type", "refresh_token" }, { "client_id", ClientId }, { "client_secret", ClientSecret }, { "redirect_uri", RedirectUri }, { "scope", Scope }, { "resource", Resource }, { "refresh_token", RefreshToken } }; // Define required query params var requiredParams = new List <string>() { "client_id", "client_secret", "redirect_uri", "resource", "refresh_token" }; // Validate required values are included if (!payload.ValidateKeys(requiredParams)) { throw new MissingValueException($"One or more required parameters are missing or empty: {string.Join(",", requiredParams.ToArray())}"); } var uriBuilder = new System.UriBuilder($"https://login.microsoftonline.com/{Tenant}/oauth2/token"); var result = await _httpClient.PostAsync(uriBuilder.ToString(), payload.ToFormUrlEncodedContent()); if (!result.IsSuccessStatusCode) { throw new Exception(await result.Content.ReadAsStringAsync()); } else { return(JsonConvert.DeserializeObject <TokenResponse>(await result.Content.ReadAsStringAsync())); } }
public string GetSPURL(HttpRequestBase request, UrlHelper url) { var urlBuilder = new System.UriBuilder(request.Url.AbsoluteUri) { Path = url.Action("ParseURL", "RESTEA"), Query = null, }; Uri uri = urlBuilder.Uri; string WholeURL = urlBuilder.ToString(); if (WholeURL != null) { return(WholeURL); } else { throw new Exception("SP Url value is null"); } }
public ActionResult LogOut(string state) { var redirectUrl = new System.UriBuilder(this.Request.Url.AbsoluteUri) { Path = this.Url.Action("Index"), Query = null, }; var model = this.Session[state] as TestEnvironmentModel; var token = this.Session["token"] as string; var nonce = this.GetLogoutNonce(token, model, redirectUrl.ToString()); var parameters = HttpUtility.ParseQueryString(string.Empty); parameters.Add("nonce", nonce); var uri = new UriBuilder(model.LogoutUrl); uri.Query = parameters.ToString(); FormsAuthentication.SignOut(); return(this.Redirect(uri.ToString())); }
private async Task SendForgotPasswordEmail(AppUser user) { var code = await _userManager.GeneratePasswordResetTokenAsync(user); var urlBuilder = new System.UriBuilder(Request.GetRawUrl()) { 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 />" + "Admin"; var response = await _emailSender.SendEmailAsync(user.Email, "Reset Your Password", resetPasswordText); }
private async Task <IActionResult> SendConfirmationEmail(AppUser user, bool isResend) { // 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(_configuration["SiteUrl"]) { 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 />" + "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, please ignore and delete this message.<br /><br />" + "Thank you.<br /><br />" + "Site Admin<br /><br />"; if (isResend) { confirmText += "(This is confirmation email has been resent upon request.)"; } var response = await _emailSender.SendEmailAsync(user.Email, "Confirm your account", confirmText); return(new OkObjectResult(null)); }
public ActionResult Login(LoginModel model, string returnUrl) { try { AntiForgery.Validate(); } catch (HttpAntiForgeryException) { var relayState = ProcessOktaRelayState(Request.Form); if (relayState == null) { return(View(model)); } Session["RelayState"] = relayState; return(View(model)); } // Immediately return if we have an invalid ModelState if (!ModelState.IsValid) { ModelState.AddModelError("", "The user name or password provided is incorrect."); return(View(model)); } #region if we have a returnUrl, turn it into an absolute URL if (returnUrl != null) { var uri = new System.UriBuilder(HttpContext.Request.Url.AbsoluteUri); if (returnUrl.Contains('?')) { var parts = returnUrl.Split('?'); uri.Path = parts[0]; // FIXME: That this has the entire query string in it. uri.Query = parts[1]; } else { uri.Path = returnUrl; uri.Query = null; } returnUrl = uri.ToString(); } #endregion // Store the relayState in the HttpContext to "pass" it to the OktaMembershipProvider if (Session["RelayState"] != null) { returnUrl = (string)Session["RelayState"]; } if (returnUrl != null) { HttpContext.Items["relayState"] = returnUrl; } var userValid = WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe); AuthResponse response = MoveOktaResponseFromHttpContextToSession(model.UserName); // See if the username/password pair was valid. // This will be "false" if there is an MFA step, so we will check for that next. if (userValid) { MigrateShoppingCart(model.UserName); return(RedirectToOktaOrHome(model.UserName)); } else if (response != null && response.Status != null) { if (response.Status == AuthStatus.MfaEnroll) { return(RedirectToLocal("/Mfa/Add")); } else if (response.Status == AuthStatus.MfaRequired) { return(RedirectToLocal("/Mfa/Verify")); } else if (response.Status == AuthStatus.PasswordExpired) { return(RedirectToLocal("/Account/PasswordExpired")); } else if (response.Status == AuthStatus.PasswordReset) { // /Account/PasswordReset } } else if (HttpContext.Items.Contains("authnError")) { var reason = (string)HttpContext.Items["authnError"]; ModelState.AddModelError("", reason); return(View(model)); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Error logging in."); return(View(model)); }
public ActionResult CGCDocumentEdit(DocumentEditViewModel viewModel) { string uploadDir = "~/documents/cgc/"; string path = String.Empty; CropGermplasmCommitteeDocument document = new CropGermplasmCommitteeDocument(); ResultContainer resultContainer = new ResultContainer(); try { document.ID = viewModel.ID; document.Committee.ID = viewModel.CommitteeID; document.Title = viewModel.Title; document.DocumentYear = viewModel.Year; document.CategoryCode = viewModel.CategoryCode; document.URL = viewModel.URL; if (viewModel.DocumentUpload != null && viewModel.DocumentUpload.ContentLength > 0) { if (document.CategoryTitle == "CVS") { uploadDir = uploadDir + "cvs"; } else { if (document.CategoryTitle == "MIN") { uploadDir = uploadDir + "committee"; } } //NEEDED? //path = Path.Combine(Server.MapPath(uploadDir), Path.GetFileName(viewModel.DocumentUpload.FileName)); var documentPath = Path.Combine(Server.MapPath(uploadDir), viewModel.DocumentUpload.FileName); var documentUrl = Path.Combine(uploadDir, viewModel.DocumentUpload.FileName); viewModel.DocumentUpload.SaveAs(documentPath); var urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.Content(documentUrl), Query = null, }; Uri uri = urlBuilder.Uri; document.URL = urlBuilder.ToString(); } if (viewModel.ID > 0) { resultContainer = _cgcRepository.UpdateDocument(document); } else { resultContainer = _cgcRepository.InsertDocument(document); } return(RedirectToAction("CGCDocumentView", "Admin", new { id = resultContainer.EntityID })); } catch (Exception ex) { Log.Error(ex, ex.Message); string actionName = this.ControllerContext.RouteData.Values["action"].ToString(); string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString(); string errorText = "<label>Controller:</label>" + controllerName; errorText = errorText + "<br><label>Action:</label>" + actionName; errorText = errorText + "<br><label>Details:</label>" + ex.TargetSite + ex.Message; Session["ERROR_TEXT"] = errorText; return(RedirectToAction("InternalServerError", "Error")); } }
public string GenerateQuotationToPDF(BookingQuoteInfoModel bookingQuoteInfo) { int count = 0; string temp = ""; List <BookingVehicleInfoModel> tempVehicles = bookingQuoteInfo.BookingVehicleInfo; bookingQuoteInfo.BookingVehicleInfo = new List <BookingVehicleInfoModel>(); List <BookingVehicleInfoModel> vehicles = tempVehicles.AsEnumerable() .Select(row => row) .OrderBy(x => x.BusType) .ToList(); for (int i = 0; i < vehicles.Count; i++) { if (i != 0) { if (temp == vehicles[i].BusType) { count = count + 1; } else { bookingQuoteInfo.BookingVehicleInfo.Add(new BookingVehicleInfoModel() { BusType = vehicles[i].BusType, Quantity = count }); temp = vehicles[i].BusType; count = 1; } } else { temp = vehicles[i].BusType; count = count + 1; } } bookingQuoteInfo.BookingVehicleInfo.Add(new BookingVehicleInfoModel() { BusType = temp, Quantity = count }); if (bookingQuoteInfo.IsTrailerRequired) { count = 0; temp = ""; List <BookingTrailerInfoModel> tempTrailers = bookingQuoteInfo.BookingTrailerInfo; bookingQuoteInfo.BookingTrailerInfo = new List <BookingTrailerInfoModel>(); List <BookingTrailerInfoModel> trailers = tempTrailers.AsEnumerable() .Select(row => row) .OrderBy(x => x.TrailerType) .ToList(); for (int i = 0; i < trailers.Count; i++) { if (i != 0) { if (temp == trailers[i].TrailerType) { count = count + 1; } else { bookingQuoteInfo.BookingTrailerInfo.Add(new BookingTrailerInfoModel() { TrailerType = trailers[i].TrailerType, Quantity = count }); temp = trailers[i].TrailerType; count = 1; } } else { temp = trailers[i].TrailerType; count = count + 1; } } bookingQuoteInfo.BookingTrailerInfo.Add(new BookingTrailerInfoModel() { TrailerType = temp, Quantity = count }); } if (bookingQuoteInfo.CompTelephoneExtension != string.Empty) { bookingQuoteInfo.CompTelephoneNumber = string.Empty; bookingQuoteInfo.CompTelephoneNumber = bookingQuoteInfo.CompTelephoneNumber + bookingQuoteInfo.CompTelephoneExtension; } string extension = ".pdf"; string fileName = ConfigurationSettings.CompanyName + "_Quotation_" + bookingQuoteInfo.AlternateID.ToString() + "_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + extension; try { Rotativa.ViewAsPdf actionResult = new Rotativa.ViewAsPdf("ExportQuotationToPDF", bookingQuoteInfo); byte[] byteArray = actionResult.BuildPdf(ControllerContext); FileStream fileStream = new FileStream(Server.MapPath("~/PDF/" + fileName), FileMode.Create, FileAccess.Write); fileStream.Write(byteArray, 0, byteArray.Length); fileStream.Close(); } catch (Exception ex) { throw ex; } bookingQuoteInfo.QuotationFileName = fileName; Models.CompanyConfigurationInfo settings = ConfigurationSettings; new Task(() => { DBHelper.UpdateQuotationFileName(fileName, bookingQuoteInfo.ID, settings.ConnectionKey); }).Start(); try { if (bookingQuoteInfo.EmailAddress != null && bookingQuoteInfo.EmailAddress != string.Empty) { new Task(() => { EmailHelper.SendQuotationConfirmation(bookingQuoteInfo, settings); }).Start(); } } catch (Exception) { //ignore } UriBuilder urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.Content("~/PDF/" + fileName), Query = null, }; string url = urlBuilder.ToString(); return(url); }
/// <summary> /// Processes the payment after a customer submits valid data through the payment form. /// </summary> public PaymentResultInfo ProcessPayment(IDictionary <string, object> paymentData) { // Build Novalnet payport request // Get unique id (16 digit unique number) string uniqid = NovalnetHelper.GetUniqueid(); var addressInfo = OrderAddressInfoProvider.GetAddressInfo(Order.OrderBillingAddress.AddressID); // Encrypted vendor parameters Dictionary <string, string> vendorDetails = NovalnetHelper.GetVendorCredentials(); string vendor = vendorDetails["vendor"]; string password = vendorDetails["password"]; string testMode = (SettingsKeyInfoProvider.GetValue("test_mode", SiteContext.CurrentSiteID) == "True") ? "1" : "0"; int amount = NovalnetHelper.GetOrderAmount(Order.OrderGrandTotal); Dictionary <string, string> secureData = new Dictionary <string, string>(); secureData.Add("authCode", NovalnetHelper.EncryptString(vendorDetails["authCode"], password, uniqid)); secureData.Add("product", NovalnetHelper.EncryptString(vendorDetails["product"], password, uniqid)); secureData.Add("tariff", NovalnetHelper.EncryptString(vendorDetails["tariff"], password, uniqid)); secureData.Add("amount", NovalnetHelper.EncryptString(Convert.ToString(amount), password, uniqid)); secureData.Add("testMode", NovalnetHelper.EncryptString(testMode, password, uniqid)); string hashVal = NovalnetHelper.GetHash(secureData, uniqid, password); // Shop configuration parameters int country = addressInfo.AddressCountryID; CMS.Globalization.CountryInfo entity = CMS.Globalization.CountryInfoProvider.GetCountryInfo(country); string countryCode = entity.CountryTwoLetterCode; string culture = NovalnetHelper.GetLanguage(Order.OrderCulture); var urlBuilder = new System.UriBuilder(HttpContext.Current.Request.Url.AbsoluteUri) { Path = (HttpContext.Current.Handler as Page).ResolveUrl("~/NovalnetResponseHandler.ashx"), Query = null, }; string url = urlBuilder.ToString(); string sessionVal = NovalnetHelper.GetSessionValue(); var parameter = new StringBuilder(); // Prepare vendor parameters parameter.AppendFormat("&vendor={0}", vendorDetails["vendor"]); parameter.AppendFormat("&auth_code={0}", NovalnetHelper.EncryptString(vendorDetails["authCode"], password, uniqid)); parameter.AppendFormat("&product={0}", NovalnetHelper.EncryptString(vendorDetails["product"], password, uniqid)); parameter.AppendFormat("&tariff={0}", NovalnetHelper.EncryptString(vendorDetails["tariff"], password, uniqid)); parameter.AppendFormat("&test_mode={0}", NovalnetHelper.EncryptString(testMode, password, uniqid)); parameter.AppendFormat("&hash={0}", hashVal); parameter.AppendFormat("&uniqid={0}", uniqid); parameter.AppendFormat("&implementation={0}", "ENC"); parameter.AppendFormat("&return_url={0}", url); parameter.AppendFormat("&error_return_url={0}", url); parameter.AppendFormat("&input1={0}", "reference1"); parameter.AppendFormat("&inputval1={0}", sessionVal); parameter.AppendFormat("&hfooter={0}", "1"); parameter.AppendFormat("&skip_cfm={0}", "1"); parameter.AppendFormat("&skip_suc={0}", "1"); parameter.AppendFormat("&thide={0}", "1"); parameter.AppendFormat("&purl={0}", "1"); if (!string.IsNullOrEmpty(SettingsKeyInfoProvider.GetValue("referrer_id", SiteContext.CurrentSiteID))) { parameter.AppendFormat("&referrer_id={0}", SettingsKeyInfoProvider.GetValue("referrer_id", SiteContext.CurrentSiteID)); } // Prepare customer parameters parameter.AppendFormat("&gender={0}", "u"); parameter.AppendFormat("&first_name={0}", ShoppingCartInfoObj.Customer.CustomerFirstName); parameter.AppendFormat("&last_name={0}", ShoppingCartInfoObj.Customer.CustomerLastName); parameter.AppendFormat("&email={0}", ShoppingCartInfoObj.Customer.CustomerEmail); parameter.AppendFormat("&customer_no={0}", mOrder.OrderCustomerID.ToString()); if (!string.IsNullOrEmpty(addressInfo.AddressLine1) && !string.IsNullOrEmpty(addressInfo.AddressLine2)) { parameter.AppendFormat("&house_no={0}", addressInfo.AddressLine1); parameter.AppendFormat("&street={0}", addressInfo.AddressLine2); } else { parameter.AppendFormat("&street={0}", addressInfo.AddressLine1); parameter.AppendFormat("&search_in_street={0}", "1"); } parameter.AppendFormat("&country_code={0}", countryCode); parameter.AppendFormat("&city={0}", addressInfo.AddressCity); parameter.AppendFormat("&zip={0}", addressInfo.AddressZip); // Prepare orderdetails parameter parameter.AppendFormat("&lang={0}", culture); parameter.AppendFormat("&order_no={0}", OrderId.ToString()); parameter.AppendFormat("&amount={0}", NovalnetHelper.EncryptString(amount.ToString(), password, uniqid)); parameter.AppendFormat("¤cy={0}", CurrencyInfoProvider.GetCurrencyInfo(Order.OrderCurrencyID).CurrencyCode); //Prepare paymentdetails parameter if ((!string.IsNullOrEmpty(SettingsKeyInfoProvider.GetValue("on_hold_limit", SiteContext.CurrentSiteID))) && (amount >= Convert.ToInt64(SettingsKeyInfoProvider.GetValue("on_hold_limit", SiteContext.CurrentSiteID)))) { parameter.AppendFormat("&on_hold={0}", "1"); } if (Convert.ToBoolean(SettingsKeyInfoProvider.GetValue("cc3d", SiteContext.CurrentSiteID))) { parameter.AppendFormat("&cc_3d={0}", "1"); } if (!string.IsNullOrEmpty(SettingsKeyInfoProvider.GetValue("invoice_due_date", SiteContext.CurrentSiteID))) { parameter.AppendFormat("&due_date={0}", SettingsKeyInfoProvider.GetValue("invoice_due_date", SiteContext.CurrentSiteID)); } if (!string.IsNullOrEmpty(SettingsKeyInfoProvider.GetValue("sepa_due_date", SiteContext.CurrentSiteID))) { parameter.AppendFormat("&sepa_due_date={0}", SettingsKeyInfoProvider.GetValue("sepa_due_date", SiteContext.CurrentSiteID)); } if (!string.IsNullOrEmpty(SettingsKeyInfoProvider.GetValue("slip_expiry_date", SiteContext.CurrentSiteID))) { var now = DateTime.Now; var due_date = now.AddDays(Convert.ToInt32(SettingsKeyInfoProvider.GetValue("slip_expiry_date", SiteContext.CurrentSiteID))).ToString("yyyy-MM-dd"); parameter.AppendFormat("&cashpayment_due_date={0}", due_date); } // Get payport response Dictionary <string, string> responseVal = NovalnetHelper.SendRequest(parameter.ToString()); if (responseVal == null || (Convert.ToInt32(responseVal["status"]) != 100) || string.IsNullOrEmpty(responseVal["url"])) { PaymentResult.PaymentIsFailed = true; if (responseVal != null) { ErrorMessage = responseVal["status_desc"]; PaymentResult.PaymentDescription = ErrorMessage; } UpdateOrderPaymentResult(); NovalnetHelper.LogEventError(ErrorMessage, Order.OrderGUID.ToString()); return(PaymentResult); } // Customers are redirected to this URL to finish the payment after they successfully submit the payment form PaymentResult.PaymentApprovalUrl = responseVal["url"]; NovalnetHelper.LogEventInfo(Order.OrderID.ToString(), "Successfully Redirected to Novalnet Payment Gateway Url"); // Saves the payment result to the related order // Automatically sets the PaymentResult time stamp (date) and payment method properties UpdateOrderPaymentResult(); // Returns the partially set payment results. // The customer finishes the payment on an external page, so the example assumes that a HTTP handler (IPN) // later processes the gateway's reply, and calls the provider's 'ProcessDirectPaymentReply' method. return(PaymentResult); }
private static void ExportDocument(JArray array, HashSet<string> crawled, string href) { if (crawled.Add(href) == false) return; Console.WriteLine("Reading {0}", href); var uri = new UriBuilder("http", "groups.google.com", 80, href).Uri; var linkReader = new SgmlReader { Href = uri.ToString() }; var linkDoc = new XmlDocument(); linkDoc.Load(linkReader); var layout = linkDoc.SelectSingleNode("//div[@class='layout']"); var title = layout.SelectSingleNode(".//h2").InnerText; var name = Path.GetFileName(uri.LocalPath).Replace("-", "_"); AddDocumentsFromLinks(array, crawled, layout.SelectNodes(".//a")); Console.WriteLine("Writing {0}", title); var index = new JObject(new JProperty("Html", FixLinks(layout.InnerXml)), new JProperty("Name", title)); array.Add(new JObject( new JProperty("DocId", "raven_documentation/" + name), new JProperty("Document", index), new JProperty("Type", "raven documentation"), new JProperty("Metadata", new JObject(new JProperty("Raven-View-Template", "/raven/JSONTemplates/documentation.html"))) )); }