private void LogOff <T>(T param, InvokeResult <LogOffRet> result) where T : LogOffParam { if (param is LogOffUserParam) { SPParam theSPParam = new ObjectToken { ApplicationIdFrom = param.ApplicationIdFrom, ApplicationIdTo = param.ApplicationIdTo, Token = param.Token }.ToSPParam(); BuilderFactory.DefaultBulder().ExecuteSPNoneQuery("SP_Cer_SignOut", theSPParam); if (theSPParam.ErrorCode == 0) { //浏览器类 Redirect r = Global.redirects.FirstOrDefault(item => item.ApplicationIdFrom == param.ApplicationIdFrom && item.ApplicationIdTo == param.ApplicationIdTo && item.Tag == "SignOut"); if (r != null) { theSPParam.MixInWithDictionary(param.ToStringObjectDictionary()); result.ret.RedirectUrl = r.Url.ReplaceWithKeys(theSPParam); } } else { result.Success = false; result.ErrorMessage = theSPParam.ErrorMessage; } } }
public async Task <DBServiceResult> UpdateRedirect(string shortUrl, Redirect updatedRedirectItem) { var rItem = await GetRedirectByHash(shortUrl, true, false).FirstOrDefaultAsync(); if (rItem == null) { return(DBServiceResult.NotFound); } else { // Only if the new redirect has the same destination // URL, update info if (rItem.DestinationURL.Equals(updatedRedirectItem.DestinationURL)) { // This line can raise a validation error that is // sent to the user as a 400 BadRequest rItem.ExpiresOn = updatedRedirectItem.ExpiresOn; rItem.Name = updatedRedirectItem.Name; await _context.SaveChangesAsync(); return(DBServiceResult.Successful); } // Could not update as DestinationURL changed else { return(DBServiceResult.NotAllowed); } } }
public async Task <AcsRequest> GetAcsRequestAsync(Redirect redirect) { Dictionary <string, string> dict = redirect.Parameter .ToDictionary(x => x.Name, x => x.Value); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, redirect.Url) { Content = new FormUrlEncodedContent(dict) }; LogRequest(request); HttpResponseMessage response = await client.SendAsync(request); string html = await response.Content.ReadAsStringAsync(); HtmlDocument htmlDoc = new HtmlDocument(html); return(new AcsRequest { FormActionUrl = htmlDoc.GetAttribute("form[name$=\"simulationForm\"]", "action"), Md = htmlDoc.GetValue("input[name$=\"MD\"]"), PaRes = htmlDoc.GetValue("input[name$=\"PaRes\"]"), Ndcid = htmlDoc.GetValue("input[name$=\"ndcid\"]"), ReturnCode = "000.000.000" }); }
public IHandlerBuilder?Edit([FromPath] int number, Customer customer) { using var context = Database.Create(); var existing = context.Customers .Where(c => c.Number == number) .FirstOrDefault(); if (existing == null) { return(null); } existing.Number = customer.Number; existing.Name = customer.Name.Trim(); existing.FirstName = OrNull(customer.FirstName); existing.Salutation = customer.Salutation; existing.Title = OrNull(customer.Title); existing.Phone = OrNull(customer.Phone); existing.Mail = OrNull(customer.Mail); existing.Street = OrNull(customer.Street); existing.Zip = OrNull(customer.Zip); existing.City = OrNull(customer.City); existing.Notes = OrNull(customer.Notes); existing.Modified = DateTime.UtcNow; context.SaveChanges(); return(Redirect.To($"{{controller}}/details/{customer.Number}/", true)); }
public void OnRedirectDeleted(Redirect redirect) { if (RedirectDeleted != null) { RedirectDeleted(new SingleItemEventArgs <Redirect>(redirect)); } }
protected void Submit_Click(object sender, EventArgs e) { if (Page.IsValid) { var redirect = new Redirect(); redirect.RequestedUrl = new Uri(this.pattern.Text, UriKind.RelativeOrAbsolute); redirect.DestinationUrl = new Uri(this.destination.Text, UriKind.RelativeOrAbsolute); redirect.StatusCode = Int32.Parse(this.type.SelectedValue, CultureInfo.InvariantCulture); redirect.Comment = this.comment.Text; if (!String.IsNullOrEmpty(this.redirectId.Value)) { redirect.RedirectId = Int32.Parse(this.redirectId.Value, CultureInfo.InvariantCulture); new SqlServerRedirectsRepository(ConfigurationManager.ConnectionStrings["RedirectsWriter"].ConnectionString).SaveRedirect(redirect); } else { new SqlServerRedirectsRepository(ConfigurationManager.ConnectionStrings["RedirectsWriter"].ConnectionString).SaveRedirect(redirect); } // Go back to the list where the edited redirect will be shown switch (this.type.SelectedValue) { case "1": new HttpStatus().SeeOther(new Uri("../shorturls.aspx", UriKind.Relative)); break; case "2": new HttpStatus().SeeOther(new Uri("../moved.aspx", UriKind.Relative)); break; } } }
protected override void Format57Handler(LoginClient client, ClientFormat57 format) { if (format.Type == 0x00) { var redirect = new Redirect { Serial = client.Serial, Salt = client.Encryption.Parameters.Salt, Seed = client.Encryption.Parameters.Seed, Name = "socket[" + client.Serial + "]" }; ServerContext.GlobalRedirects.Add(redirect); client.Send(new ServerFormat03 { EndPoint = new IPEndPoint(Address, 2610), Redirect = redirect }); } if (format.Type == 0x01) { client.Send(new ServerFormat56 { Size = MServerTable.Size, Data = MServerTable.Data }); } }
public void LoginAsAisling(LoginClient client, Aisling _aisling) { if (_aisling != null) { var redirect = new Redirect { Serial = Convert.ToString(client.Serial), Salt = Encoding.UTF8.GetString(client.Encryption.Parameters.Salt), Seed = Convert.ToString(client.Encryption.Parameters.Seed), Name = _aisling.Username }; if (_aisling.Username.Equals(ServerContextBase.GlobalConfig.GameMaster, StringComparison.OrdinalIgnoreCase)) { _aisling.GameMaster = true; } _aisling.Redirect = redirect; StorageManager.AislingBucket.Save(_aisling); client.SendMessageBox(0x00, "\0"); client.Send(new ServerFormat03 { EndPoint = new IPEndPoint(Address, ServerContextBase.DefaultPort), Redirect = redirect }); } }
public void LoginAsAisling(LoginClient client, Aisling aisling) { if (aisling != null) { if (!ServerContext.GlobalMapCache.ContainsKey(aisling.AreaId)) { client.SendMessageBox(0x03, $"There is no map configured for {aisling.AreaId}\0"); return; } var redirect = new Redirect { Serial = Convert.ToString(client.Serial), Salt = Encoding.UTF8.GetString(client.Encryption.Parameters.Salt), Seed = Convert.ToString(client.Encryption.Parameters.Seed), Name = aisling.Username, }; ServerContext.Redirects.Add(redirect.Name.ToLower()); client.SendMessageBox(0x00, "\0"); client.Send(new ServerFormat03 { EndPoint = new IPEndPoint(Address, ServerContext.Config.SERVER_PORT), Redirect = redirect }); } }
public void WarnsForAbsoluteRedirectFromPath() { // Given IDocument redirected = new TestDocument(new MetadataItems { { Keys.RedirectFrom, new List <FilePath> { new FilePath("/foo/bar") } } }) { Source = new FilePath("/") }; IDocument notRedirected = new TestDocument(); IExecutionContext context = new TestExecutionContext(); Redirect redirect = new Redirect(); ThrowOnTraceEventType(null); // When List <IDocument> results = redirect.Execute(new[] { redirected, notRedirected }, context).ToList(); // Make sure to materialize the result list // Then Assert.IsTrue(Listener.Messages.ToList().Single(x => x.Key == TraceEventType.Warning).Value.StartsWith("The redirect path must be relative")); Assert.AreEqual(0, results.Count); }
private static ModuleList GetModules() => new ModuleList { { GetDocuments, new ModuleCollection { new Documents(Blog.RenderPages), new Concat { new Documents(Blog.Posts) } } }, { GenerateRedirects, new Execute(ctx => { Redirect redirect = new Redirect() .WithMetaRefreshPages(ctx.Bool(BlogKeys.MetaRefreshRedirects)); if (ctx.Bool(BlogKeys.NetlifyRedirects)) { redirect.WithAdditionalOutput("_redirects", redirects => string.Join(Environment.NewLine, redirects.Select(r => $"/{r.Key} {r.Value}"))); } return(redirect); }) }, { WriteFiles, new WriteFiles() } };
public IRedirect ProcessRedirection(string url) { var redirectResponse = new Redirect(); // Check that we've received the url parameter if (string.IsNullOrEmpty(url)) { redirectResponse.ErrorMessage = string.Format("Url parameter was missing or malformed - ({0}).", url); return(redirectResponse); } // Check that url is valid as we don't want a broken redirect var uri = new Uri(url); redirectResponse.Allowed = true; redirectResponse.Url = uri; if (_siteConfiguration.SecureMode) { // Secure mode activated if (!uri.Host.EndsWith(_siteConfiguration.WebsiteDomain) || !uri.IsAbsoluteUri) { redirectResponse.Allowed = false; redirectResponse.Url = null; redirectResponse.ErrorMessage = string.Format( "Potentially dangerous redirect detected and blocked. Submitted url ({0}) did not match allowed domain list or was malformed.", url); } } return(redirectResponse); }
public void OnRedirectDeleted(Redirect redirect) { if (RedirectDeleted != null) { RedirectDeleted(new SingleItemEventArgs<Redirect>(redirect)); } }
public IHandlerBuilder?Activate([FromPath] int id, IRequest request) { var user = AccessControl.GetAccount(request); if (!user.Admin) { throw new ProviderException(ResponseStatus.Forbidden, "Your are not allowed to activate this user."); } using var context = Database.Create(); var account = context.Accounts .Where(c => c.ID == id) .FirstOrDefault(); if (account == null) { return(null); } account.Active = true; context.SaveChanges(); return(Redirect.To($"{{controller}}/details/{id}/", true)); }
/// <summary> /// Initializes a new instance of the <see cref="RedirectMetadata"/> class. /// </summary> /// <param name="redirect">The redirect to copy</param> public RedirectMetadata(Redirect redirect) { RedirectId = redirect.RedirectId; Name = redirect.Name; Target = redirect.Target; Description = redirect.Description; }
protected override void Format57Handler(LoginClient client, ClientFormat57 format) { if (format.Type == 0x00) { var redirect = new Redirect { Serial = Convert.ToString(client.Serial), Salt = Encoding.UTF8.GetString(client.Encryption.Parameters.Salt), Seed = Convert.ToString(client.Encryption.Parameters.Seed), Name = "socket[" + client.Serial + "]" }; client.Send(new ServerFormat03 { EndPoint = new IPEndPoint(MServerTable.Servers[0].Address, MServerTable.Servers[0].Port), Redirect = redirect }); } else { client.Send(new ServerFormat56 { Size = MServerTable.Size, Data = MServerTable.Data }); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: var email = UserManager.Users.Single(item => item.Email == model.Email); var userRole = email.Roles.First(); var singleRole = RoleManager.Roles.Single(item => item.Id == userRole.RoleId); Redirect redirect = new Redirect(); string redirectedPage = redirect.LoginRedirect(singleRole); return(RedirectToLocal(redirectedPage)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public void Redirect_to_destination() { var destination = new Input1(); Redirect <StubRedirectable> .To(destination) .RedirectTo.AssertWasRedirectedTo(destination); }
public JsonResult AddRedirect(String source, String destination, Boolean isPermanent, Boolean rootMatching) { var result = new JsonResult(); try { var redirect = new Redirect { Source = source, Destination = destination, IsPermanent = isPermanent, RootMatching = rootMatching, DateModified = DateTime.UtcNow, IsActive = true }; Context.Redirects.Add(redirect); Context.SaveChanges(); result.Data = new { id = redirect.RedirectId, success = true }; CachedObjects.GetRedirectsList(true); return(result); } catch { result.Data = new { success = false }; return(result); } }
/// <summary> /// Execute the handler, and return an updated redirect /// </summary> /// <param name="redirect">The redirect.</param> /// <returns> /// The same redirect, which may have been updated /// </returns> /// <exception cref="System.ArgumentNullException">redirect</exception> /// <exception cref="System.NullReferenceException">redirect.DestinationUrl cannot be null</exception> public Redirect HandleRedirect(Redirect redirect) { if (redirect == null) { throw new ArgumentNullException("redirect"); } if (redirect.DestinationUrl == null) { throw new ArgumentException("redirect.DestinationUrl cannot be null"); } try { // Generate redirect headers and end this response to ensure they're followed switch (redirect.StatusCode) { case 301: new HttpStatus().MovedPermanently(redirect.DestinationUrl); break; case 303: new HttpStatus().SeeOther(redirect.DestinationUrl); break; } } catch (ThreadAbortException) { Thread.ResetAbort(); } return(redirect); }
public IResponse?Handle(IRequest request) { var current = request.Target.Current; if (current != null) { if (Handlers.ContainsKey(current)) { request.Target.Advance(); return(Handlers[current].Handle(request)); } } else { // force a trailing slash to prevent duplicate content if (!request.Target.Path.TrailingSlash) { return(Redirect.To($"{request.Target.Path}/") .Build(this) .Handle(request)); } if (Index != null) { return(Index.Handle(request)); } } if (Fallback != null) { return(Fallback.Handle(request)); } return(null); }
public async Task <ActionResult <RedirectDTO> > PutRedirect(string shortUrl, Redirect redirect) { var couldPut = await _dbService.UpdateRedirect(shortUrl, redirect); if (couldPut == DBServiceResult.Successful) { return(NoContent()); } else if (couldPut == DBServiceResult.NotAllowed) { return(BadRequest(new { errors = new { destinationURL = new string [] { "The destination of the URL cannot be changed." } }, type = "https://tools.ietf.org/html/rfc7231#section-6.5.8", title = "Vaidation error occurred", status = 400 })); } else { // Create a new redirect object at the given shortUrl // At this point, we do not need to check for duplicates await _dbService.AddRedirectWithHashAsync(shortUrl, redirect); return(CreatedHelper(redirect)); } }
public static ContentPage ResolveByContext(EbMobileVisualization vis, EbDataRow row, EbMobilePage page) { ContentPage renderer = null; EbMobileContainer container = page.Container; try { if (container is EbMobileForm form) { if (vis.FormMode == WebFormDVModes.New_Mode) { string msg = GetFormRenderInvalidateMsg(page.NetworkMode); if (msg != null && !form.RenderAsFilterDialog) { renderer = new Redirect(msg, MessageType.disconnected); } else { renderer = new FormRender(page, vis.LinkFormParameters, row); } } else { EbMobileDataColToControlMap map = vis.FormId; if (map == null) { EbLog.Info("form id must be set"); throw new Exception("Form rendering exited! due to null value for 'FormId'"); } else { int id = Convert.ToInt32(row[map.ColumnName]); if (id <= 0) { EbLog.Info($"formid has invalid value {id}, switching to new mode"); renderer = new FormRender(page, vis.LinkFormParameters, row); } else { EbLog.Info($"formid has value {id}, rendering edit mode"); renderer = new FormRender(page, id); } } } } else if (container is EbMobileVisualization) { renderer = new LinkedListRender(page, vis, row); } else if (container is EbMobileDashBoard) { renderer = new DashBoardRender(page); } } catch (Exception ex) { EbLog.Error(ex.Message); } return(renderer); }
public void WithAdditionalOutput() { // Given TestDocument redirected1 = new TestDocument(new MetadataItems { { Keys.RedirectFrom, new List <FilePath> { new FilePath("foo.html") } }, { Keys.RelativeFilePath, new FilePath("foo2.html") } }); redirected1.AddTypeConversion <FilePath, string>(x => x.FullPath); TestDocument redirected2 = new TestDocument(new MetadataItems { { Keys.RedirectFrom, new List <FilePath> { new FilePath("bar/baz.html") } } }); redirected2.AddTypeConversion <FilePath, string>(x => x.FullPath); IExecutionContext context = new TestExecutionContext(); Redirect redirect = new Redirect().WithAdditionalOutput(new FilePath("a/b"), x => string.Join("|", x.Select(y => $"{y.Key} {y.Value}"))); // When List <IDocument> results = redirect.Execute(new[] { redirected1, redirected2 }, context).ToList(); // Make sure to materialize the result list // Then CollectionAssert.AreEquivalent(new[] { "foo.html", "bar/baz.html", "a/b" }, results.Select(x => x.Get <FilePath>(Keys.WritePath).FullPath)); Assert.IsTrue(results.Single(x => x.Get <FilePath>(Keys.WritePath).FullPath == "a/b").Content.Contains("foo.html /foo2.html")); }
public void CanParseRedirect() { var configuration = TestData.TestData.DefaultConfiguration; var redirectParser = new RedirectParser( configuration, new UrlParser(), new UrlFormatter()); var redirect = new Redirect { OldUrl = "/old-url/#anchor", NewUrl = "/new-url/#anchor" }; var parsedRedirect = redirectParser.ParseRedirect( redirect); Assert.IsNotNull(redirect); Assert.AreEqual( "http://www.test.local/old-url", parsedRedirect.OldUrl.Formatted); Assert.AreEqual( "http://www.test.local/new-url#anchor", parsedRedirect.NewUrl.Formatted); }
/// <summary> /// سعی در ورود به سیستم /// </summary> void doLogin() { var result = _appContextService.LoginCurrentUser(LoginPageData.UserName, LoginPageData.Password); // آیا کاربر اعتبارسنجی شده است؟ if (result) { // ثبت نام کاربری او در فایل کانفیگ برنامه _configSetGet.SetConfigData("LastLoginName", LoginPageData.UserName); // هدایت به صفحه خوش آمد گویی به همراه ارسال كوئري استرينگ Redirect.ToWelcomePage(queryStringData: "... Hello World ..."); } else { // نمایش خطایی به کاربر در صورت عدم ورود اطلاعات صحیح یا معتبر new SendMsg().ShowMsg(new AlertConfirmBoxModel { ErrorTitle = "خطا", Errors = new List <string> { "لطفا مجددا سعی نمائید." }, ShowCancel = Visibility.Collapsed, ShowConfirm = Visibility.Visible }); } }
public async Task <IActionResult> Edit(long id, [Bind("Name,OldUrl,NewUrl,IsActive,Id,CreateDate,CreatedBy,UpdateDate,UpdatedBy,AppTenantId")] Redirect redirect) { if (id != redirect.Id) { return(NotFound()); } if (ModelState.IsValid) { try { redirect.UpdateDate = DateTime.Now; redirect.AppTenantId = tenant.AppTenantId; redirect.UpdatedBy = User.Identity.Name ?? "username"; _context.Update(redirect); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RedirectExists(redirect.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } redirect.AppTenantId = tenant.AppTenantId; return(View(redirect)); }
public Redirect Create(RedirectDto redirect) { String path; do { path = Utils.RandomHex.GetRandomHexNumber(8).ToLower(); }while (PathExists(path)); var hashedPass = BCrypt.Net.BCrypt.HashPassword(redirect.Password); DateTime?fullTime; if (redirect.TTL is null) { fullTime = null; } else { fullTime = DateTime.UtcNow.AddHours(redirect.TTL.Value.Hour).AddMinutes(redirect.TTL.Value.Minute); } var newRedir = new Redirect { ExpirationTime = fullTime, Password = hashedPass, URL = redirect.URL, Path = path }; _redirects.InsertOne(newRedir); _logger.LogInformation($"Inserted redirect: {JsonConvert.SerializeObject(newRedir)}"); return(newRedir); }
public static Redirect ToRedirectAction(this RedirectItem redirectItem) { if (redirectItem == null) { return(null); } var redirectAction = new Redirect { Name = redirectItem.Name }; GetBaseRewriteUrlItem(redirectItem.BaseRedirectItem.BaseRewriteUrlItem, redirectAction); var baseAppendQueryString = redirectItem.BaseRedirectItem.BaseAppendQuerystringItem; GetBaseAppendQueryStringItem(baseAppendQueryString, redirectAction); var stopProcessingItem = redirectItem.BaseRedirectItem.BaseStopProcessingItem; GetStopProcessing(stopProcessingItem, redirectAction); var redirectTypeItem = redirectItem.BaseRedirectItem.BaseRedirectTypeItem; GetStatusCode(redirectTypeItem, redirectAction); var httpCacheabilityTypeItem = redirectItem.BaseRedirectItem.BaseCacheItem; GetCacheability(httpCacheabilityTypeItem, redirectAction); return(redirectAction); }
public void WithAdditionalOutputWithoutMetaRefresh() { // Given IDocument redirected1 = new TestDocument(new MetadataItems { { Keys.RedirectFrom, new List <FilePath> { new FilePath("foo.html") } }, { Keys.RelativeFilePath, new FilePath("foo2.html") } }); IDocument redirected2 = new TestDocument(new MetadataItems { { Keys.RedirectFrom, new List <FilePath> { new FilePath("bar/baz.html") } } }); IExecutionContext context = new TestExecutionContext(); Redirect redirect = new Redirect() .WithAdditionalOutput(new FilePath("a/b"), x => string.Join("|", x.Select(y => $"{y.Key} {y.Value}"))) .WithMetaRefreshPages(false); // When List <IDocument> results = redirect.Execute(new[] { redirected1, redirected2 }, context).ToList(); // Make sure to materialize the result list // Then CollectionAssert.AreEquivalent(new[] { "a/b" }, results.Select(x => x.Get <FilePath>(Keys.WritePath).FullPath)); }
public JsonResult AddRedirect(String source, String destination, Boolean isPermanent, Boolean rootMatching) { var result = new JsonResult(); try { var redirect = new Redirect { Source = source, Destination = destination, IsPermanent = isPermanent, RootMatching = rootMatching, DateModified = DateTime.UtcNow, IsActive = true }; Context.Redirects.Add(redirect); Context.SaveChanges(); result.Data = new { id = redirect.RedirectId, success = true }; CachedObjects.GetRedirectsList(true); return result; } catch { result.Data = new { success = false }; return result; } }
public async Task Fdownl() { var attachment = Context.Message.Attachments.FirstOrDefault(); if (attachment == null) { await ReplyAsync("I could not find an attachment within your message."); return; } var httpClient = new HttpClient(); using var downloadResponse = await httpClient.GetAsync(attachment.Url, HttpCompletionOption.ResponseHeadersRead); if (!downloadResponse.IsSuccessStatusCode) { await ReplyAsync("Discord is having problems with their CDN I guess :("); return; } using var content = await downloadResponse.Content.ReadAsStreamAsync(); var form = new MultipartFormDataContent(); form.Add(new StringContent("604800"), "lifetime"); var coupon = _configuration.GetValue <string>("FDownlCoupon"); if (!string.IsNullOrEmpty(coupon)) { form.Add(new StringContent(coupon), "code"); } form.Add(new StreamContent(content), "files", attachment.Filename); var message = await ReplyAsync("Uploading..."); var uploadResponse = await httpClient.PostAsync("https://s1.fdow.nl/upload", form); await message.DeleteAsync(); if (!uploadResponse.IsSuccessStatusCode) { await ReplyAsync("Upload failed :("); return; } dynamic result = JsonConvert.DeserializeObject(await uploadResponse.Content.ReadAsStringAsync()); if ((int)result.code != 0) { await ReplyAsync($"The server returned the following error:\n```\n{result.error}\n```"); return; } var redirect = new Redirect { RandomId = (string)result.id, RedirectUrl = attachment.Url }; await _context.Redirects.AddAsync(redirect); await _context.SaveChangesAsync(); await ReplyAsync($"Success! Your file is now accessible at:\nhttps://imaginaryctf.org/f/{(string)result.id}"); }
public static void Main() { var redirect = new Redirect (); redirect.PostRedirect (new Redirect.RedirectTest { Flags = PuppyFlags.None, Code = HttpStatusCode.TemporaryRedirect }); }
/// <summary> /// Checks if such redirect doesn't exists yet and creates new redirect entity. /// </summary> /// <param name="pageUrl">The page URL.</param> /// <param name="redirectUrl">The redirect URL.</param> /// <returns> /// New created redirect entity or null, if such redirect already exists /// </returns> public Redirect CreateRedirectEntity(string pageUrl, string redirectUrl) { ValidateRedirectExists(pageUrl); ValidateForCircularLoop(pageUrl, redirectUrl); var redirect = new Redirect { PageUrl = pageUrl, RedirectUrl = redirectUrl }; return redirect; }
public void DestinationQueryStringPreservedIfPresent() { var redirect = new Redirect() { RequestedUrl = new Uri("http://www.example.org/page1.html"), DestinationUrl = new Uri("http://www.example.org/page2.html?test=test") }; var handler = new PreserveQueryStringHandler(); redirect = handler.HandleRedirect(redirect); Assert.AreEqual(new Uri("http://www.example.org/page2.html?test=test"), redirect.DestinationUrl); }
public void NoQueryStringDoesNothing() { var url = new Uri("http://www.example.org/page1.html"); var redirect = new Redirect() {RequestedUrl = url, DestinationUrl = url}; var handler = new PreserveQueryStringHandler(); redirect = handler.HandleRedirect(redirect); Assert.AreEqual(url, redirect.DestinationUrl); }
public void AbsoluteUrlIsNotConverted() { var original = new Uri("http://www.example.org/folder/page1.html"); var baseUrl = new Uri("http://example.org"); var redirect = new Redirect() { RequestedUrl = baseUrl, DestinationUrl = original }; var handler = new ConvertToAbsoluteUrlHandler(); handler.HandleRedirect(redirect); Assert.AreEqual(original, redirect.DestinationUrl); }
public void RelativeUrlIsConverted() { var relative = new Uri("/folder/page1.html", UriKind.Relative); var baseUrl = new Uri("http://example.org"); var redirect = new Redirect() {RequestedUrl = baseUrl, DestinationUrl = relative}; var handler = new ConvertToAbsoluteUrlHandler(); handler.HandleRedirect(redirect); Assert.AreEqual(new Uri("http://example.org/folder/page1.html"), redirect.DestinationUrl); }
static void Main(string[] args) { var requestAnalyzer = new RequestAnalyzer(); var download = new Download(); var redirect = new Redirect(); var board = new SilkveilBoard(requestAnalyzer, download, redirect); using (var stream = new MemoryStream()) { board.Start(stream); } Console.Read(); }
/// <summary> /// Add or update a redirect in the repository. /// </summary> /// <param name="redirect">The redirect.</param> /// <exception cref="System.ArgumentNullException"></exception> public void SaveRedirect(Redirect redirect) { if (redirect == null) throw new ArgumentNullException(nameof(redirect)); var values = new SqlParameter[5]; values[0] = new SqlParameter("@pattern", redirect.RequestedUrl.ToString()); values[1] = new SqlParameter("@destination", redirect.DestinationUrl.ToString()); values[2] = new SqlParameter("@type", redirect.StatusCode); values[3] = new SqlParameter("@comment", redirect.Comment); if (redirect.RedirectId.HasValue) { values[4] = new SqlParameter("@redirectId", redirect.RedirectId.Value); SqlHelper.ExecuteNonQuery(_connectionString, CommandType.StoredProcedure, "usp_Redirect_Update", values); } else { SqlHelper.ExecuteNonQuery(_connectionString, CommandType.StoredProcedure, "usp_Redirect_Insert", values); } }
public void Delete(Redirect redirect) { session.Delete(redirect); }
public static IRedirect Redirect(string context, string @event) { var redirect = new Redirect(UrlGenerator.GetUrlFor(context, @event)); return redirect; }
public Redirect SaveRedirect(ViewModels.SiteSettings.SiteSettingRedirectViewModel model, bool createIfNotExists = false) { var isRedirectInternal = urlService.ValidateInternalUrl(model.RedirectUrl); if (!isRedirectInternal && urlService.ValidateInternalUrl(urlService.FixUrl(model.RedirectUrl))) { isRedirectInternal = true; } model.PageUrl = urlService.FixUrl(model.PageUrl); if (isRedirectInternal) { model.RedirectUrl = urlService.FixUrl(model.RedirectUrl); } // Validate request if (!urlService.ValidateInternalUrl(model.PageUrl)) { var message = PagesGlobalization.SaveRedirect_InvalidPageUrl_Message; var logMessage = string.Format("Invalid page url {0}.", model.PageUrl); throw new ValidationException(() => message, logMessage); } if (!urlService.ValidateExternalUrl(model.RedirectUrl)) { var message = PagesGlobalization.SaveRedirect_InvalidRedirectUrl_Message; var logMessage = string.Format("Invalid redirect url {0}.", model.RedirectUrl); throw new ValidationException(() => message, logMessage); } // Validate for url patterns string patternsValidationMessage; if (!urlService.ValidateUrlPatterns(model.PageUrl, out patternsValidationMessage)) { var logMessage = string.Format("{0}. URL: {1}.", patternsValidationMessage, model.PageUrl); throw new ValidationException(() => patternsValidationMessage, logMessage); } if (isRedirectInternal && !urlService.ValidateUrlPatterns(model.RedirectUrl, out patternsValidationMessage, PagesGlobalization.SaveRedirect_RedirectUrl_Name)) { var logMessage = string.Format("{0}. URL: {1}.", patternsValidationMessage, model.PageUrl); throw new ValidationException(() => patternsValidationMessage, logMessage); } ValidateRedirectExists(model.PageUrl, model.Id); ValidateForCircularLoop(model.PageUrl, model.RedirectUrl, model.Id); Redirect redirect = null; var isNew = model.Id.HasDefaultValue(); if (!isNew) { redirect = repository.FirstOrDefault<Redirect>(model.Id); isNew = redirect == null; if (isNew && !createIfNotExists) { throw new EntityNotFoundException(typeof(Redirect), model.Id); } } if (isNew) { redirect = new Redirect { Id = model.Id }; } if (model.Version > 0) { redirect.Version = model.Version; } redirect.PageUrl = model.PageUrl; redirect.RedirectUrl = model.RedirectUrl; repository.Save(redirect); unitOfWork.Commit(); // Notify. if (isNew) { Events.PageEvents.Instance.OnRedirectCreated(redirect); } else { Events.PageEvents.Instance.OnRedirectUpdated(redirect); } return redirect; }
public void Save(Redirect redirect) { session.SaveOrUpdate(redirect); }