public string Add(UrlInfo info) { string h_result = CheckInfo(info); if (Exist(info.HtUrl, info.HtULCase)) return "url已经存在!"; if (h_result != "") return h_result; IDataParameter[] m_parameters = new SqlParameter[4]; m_parameters[0] = new SqlParameter("@htUrl", SqlDbType.NVarChar, 2000); m_parameters[0].Value = info.HtUrl.Trim(); m_parameters[1] = new SqlParameter("@htTitle", SqlDbType.NVarChar, 200); m_parameters[1].Value = info.HtTitle; m_parameters[2] = new SqlParameter("@htSumary", SqlDbType.NVarChar, 1000); m_parameters[2].Value = info.HtSummary; m_parameters[3] = new SqlParameter("@HtULCase", SqlDbType.Bit); m_parameters[3].Value = info.HtULCase; int m_returnCount; //执行结果等于1表示添加成功 m_returnCount = KeleyiSQLHelper.HoverTreeSql.RunProcedureWithReturn("p_HoverTreeSCJ_URLs_Add", m_parameters); if (m_returnCount == 1) return string.Empty; else return "添加失败 "; }
private List<UrlInfo> GetUrlInfoList() { List<UrlInfo> list = new List<UrlInfo>(); UrlInfo info = null; bool first = true; foreach (string key in UrlTracerContain.Total.Keys) { double cost = UrlTracerContain.Cost[key]; info = new UrlInfo(); info.Path = key; info.Total = UrlTracerContain.Total[key]; if (UrlTracerContain.Failures.ContainsKey(key)) { info.Failures = UrlTracerContain.Failures[key]; } else { info.Failures = 0; } info.Max = Math.Round(UrlTracerContain.Max[key],1); info.Min = Math.Round(UrlTracerContain.Min[key],1); double avg = cost / info.Total; info.Avg = Math.Round(avg, 1); info.ReqSize = UrlTracerContain.ReqSize[key]; if (first) { info.Link = "<a target=\"_blank\" href=\"" + GetCatLink() + "\" target=\"_self\">CAT</a>"; } first = false; list.Add(info); } return list; }
public string CreateRedirect(string url, string safeUrl, int ttl) { var urlInfo = new UrlInfo { OriginalUrl = url, SafeUrl = safeUrl, ExpiresAt = SystemInfo.SystemClock().AddSeconds(ttl), }; do { urlInfo.Id = uniqueIdGenerator.Generate(); if (repository.GetUrlInfo(urlInfo.Id) != null) continue; try { repository.AddUrlInfo(urlInfo); repository.SaveChanges(); return urlInfo.Id; } catch (Exception) { // get another unique id and try again } } while (true); }
public Controller CreateController(UrlInfo urlInfo) { IWindsorContainer container = WindsorContainerAccessorUtil.ObtainContainer(); IControllerTree tree; try { tree = (IControllerTree) container["rails.controllertree"]; } catch(ComponentNotFoundException) { throw new RailsException("ControllerTree not found. Check whether RailsFacility is properly configured/registered"); } Type implType = tree.GetController(urlInfo.Area, urlInfo.Controller); if (implType == null) implType = tree.GetController("", "rescues"); if (implType == null) throw new ControllerNotFoundException(urlInfo); return (Controller) container[implType]; }
public void RedirectToUrlDoesNotTouchUrl() { UrlInfo url = new UrlInfo("area", "home", "index", "", ".castle"); StubResponse response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.RedirectToUrl("/uol/com/folha"); Assert.AreEqual("/uol/com/folha", response.RedirectedTo); }
/// <summary> /// Initializes a new instance of the <see cref="ResponseAdapter"/> class. /// </summary> /// <param name="response">The response.</param> /// <param name="currentUrl">The current URL.</param> /// <param name="urlBuilder">The URL builder.</param> /// <param name="serverUtility">The server utility.</param> /// <param name="routeMatch">The route match.</param> /// <param name="referrer">The referrer.</param> public ResponseAdapter(HttpResponse response, UrlInfo currentUrl, IUrlBuilder urlBuilder, IServerUtility serverUtility, RouteMatch routeMatch, string referrer) : base(currentUrl, urlBuilder, serverUtility, routeMatch, referrer) { this.response = response; }
private static void Test_UrlInfo() { var model = new UrlInfo { Url = "http:www.baidu.com", UrlMd5 = "atSDsdfsfsfsdsffw", ShortVal = "adEwF", Comment = "百度", State = 1, CreateTime = DateTime.Now }; var urlInfoDao=new UrlInfoDao(); var isOkDelete = urlInfoDao.DeleteById(1); var id = urlInfoDao.Add(model); var isOkUpdate = urlInfoDao.UpdateById(new UrlInfo() {Comment = "百度update"}, id); var model01 = urlInfoDao.FindById(id); var whereModel = new UrlInfo { Id = id }; var model02 = urlInfoDao.FindList(whereModel, "id=@id", 1); //--- //--- //todo where--比较推荐的写法--可以提高程序的可读性 var where = new WhereEntity<UrlInfo>() { Model = new UrlInfo() { Id = id }, Sql = "id=@id", OrderBy = "id" }; // var model03 = urlInfoDao.FindListByPage(where.Model, where.Sql, where.OrderBy, 0, 10); var count = urlInfoDao.Count(where.Model, where.Sql); }
// public int Count(UrlInfo whereModel, string where) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(*) from UrlInfo "); strSql.AppendFormat("where 1=1 and {0} ", where); var result = _dbHelper.Count(strSql.ToString(), whereModel); return result; }
public void ReturnsSafeUrlExactlyOnExpirationDate() { var sut = new UrlInfo { OriginalUrl = "a", SafeUrl = "b", ExpiresAt = new DateTime(2000, 1, 2, 3, 4, 5) }; var result = sut.GetUrl(new DateTime(2000, 1, 2, 3, 4, 5)); Assert.AreEqual("b", result); }
public TreeViewModel() { MainUrl = new UrlInfo(); AddUrl = new UrlInfo(); EditUrl = new UrlInfo(); RemoveUrl = new UrlInfo(); ExpandUrl = new UrlInfo(); }
public void EnQueue(UrlInfo target) { lock (this.SyncObject) { this.InnerQueue.Enqueue(target); this.AutoResetEvent.Set(); } }
public static SearchQuery Parse(UrlInfo urlInfo) { List<string> tags = new List<string>(); foreach (string tagText in urlInfo.TagFilter) { tags.Add(tagText); } return new SearchQuery(tags); }
public ActionResult UrlInfo(long? id, string other) { if (id == null) id = 0; Models.UrlInfo Tmodel=new UrlInfo(urlinfoRY,SiteRY,QuestionRY); Tmodel.urlinfo = Tmodel.getquestionurlbyid(id.Value); return Content(Tmodel.urlinfo); }
public void Net_UrlInfo_ToString() { var MyRoot = "http://testURL"; var MyController = "MyController"; var MyAction = "MyAction"; var TestItem = new UrlInfo(MyRoot, MyController, MyAction); // Check formatting Assert.IsTrue(TestItem.ToString().ToLowerInvariant() == String.Format("{0}:80/{1}/{2}", MyRoot, MyController, MyAction).ToLowerInvariant()); }
public void UrlInfo_Uri(string url, string expectedProtocol, int expectedPort) { var authInfo = new AuthInfo("user", "pw", "account"); var urlInfo = new UrlInfo(new Uri(url)); var settings = new SnowflakeClientSettings(authInfo, null, urlInfo); Assert.AreEqual(url.Replace(expectedProtocol + "://", ""), settings.UrlInfo.Host); Assert.AreEqual(expectedPort, settings.UrlInfo.Port); Assert.AreEqual(expectedProtocol, settings.UrlInfo.Protocol); }
public void RedirectToUrlWithQueryStringAsDict() { UrlInfo url = new UrlInfo("area", "home", "index", "", ".castle"); StubResponse response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.RedirectToUrl("/uol/com/folha", DictHelper.Create("id=1", "name=john doe")); Assert.AreEqual("/uol/com/folha?id=1&name=john+doe", response.RedirectedTo); response.RedirectToUrl("/uol/com/folha?something=1", DictHelper.Create("id=1", "name=john doe")); Assert.AreEqual("/uol/com/folha?something=1&id=1&name=john+doe", response.RedirectedTo); }
private static async Task <Attempt <UrlInfo> > DetectCollisionAsync(ILogger logger, IContent content, string url, string culture, IUmbracoContext umbracoContext, IPublishedRouter publishedRouter, ILocalizedTextService textService, IVariationContextAccessor variationContextAccessor, UriUtility uriUtility) { // test for collisions on the 'main' URL var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri == false) { uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl); } uri = uriUtility.UriToUmbraco(uri); IPublishedRequestBuilder builder = await publishedRouter.CreateRequestAsync(uri); IPublishedRequest pcr = await publishedRouter.RouteRequestAsync(builder, new RouteRequestOptions(RouteDirection.Outbound)); if (!pcr.HasPublishedContent()) { const string logMsg = nameof(DetectCollisionAsync) + " did not resolve a content item for original url: {Url}, translated to {TranslatedUrl} and culture: {Culture}"; logger.LogDebug(logMsg, url, uri, culture); var urlInfo = UrlInfo.Message(textService.Localize("content", "routeErrorCannotRoute"), culture); return(Attempt.Succeed(urlInfo)); } if (pcr.IgnorePublishedContentCollisions) { return(Attempt <UrlInfo> .Fail()); } if (pcr.PublishedContent.Id != content.Id) { IPublishedContent o = pcr.PublishedContent; var l = new List <string>(); while (o != null) { l.Add(o.Name(variationContextAccessor)); o = o.Parent; } l.Reverse(); var s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent.Id + ")"; var urlInfo = UrlInfo.Message(textService.Localize("content", "routeError", new[] { s }), culture); return(Attempt.Succeed(urlInfo)); } // no collision return(Attempt <UrlInfo> .Fail()); }
// public int Add(UrlInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into UrlInfo ( "); strSql.Append("url,urlMd5,shortVal,comment,state,createTime,isDel)"); strSql.Append(" values ("); strSql.Append("@url,@urlMd5,@shortVal,@comment,@state,@createTime,@isDel)"); // var id = _dbHelper.InsertReturnId(strSql.ToString(), model); return id; }
/// <summary> /// Instantiates a new web request wrapping the http request provided. /// </summary> /// <param name="request">The underlying http request to wrap.</param> public AspNetRequest(HttpRequest request) { _underlyingRequest = request; _urlInfo = new UrlInfo(request.Url); _cookies = new AspNetRequestCookieCollection(request.Cookies); // setup the request params ImmutableDictionary <string, string> .Builder parms = ImmutableDictionary.CreateBuilder <string, string>(); ImmutableList <string> .Builder flags = ImmutableList.CreateBuilder <string>(); // import the querystring for (int i = 0; i < _underlyingRequest.QueryString.Count; i++) { string key = _underlyingRequest.QueryString.GetKey(i); string[] values = _underlyingRequest.QueryString.GetValues(i); // check for valueless parameters and use as flags if (values != null) { if (key == null) { flags.InsertRange(0, values); } else { parms.Add(key, values[0]); } } } // import the post values foreach (string key in _underlyingRequest.Form.Keys) { // check for null in form keys (can happen in some POST scenarios) if (key != null) { parms.Add(key, _underlyingRequest.Form.Get(key)); } } if (_underlyingRequest.ContentLength > 0 && _underlyingRequest.Files.Count == 0) { using (TextReader reader = new StreamReader(_underlyingRequest.InputStream)) { _payload = reader.ReadToEnd(); } } ImmutableDictionary <string, string> .Builder headers = ImmutableDictionary.CreateBuilder <string, string>(); foreach (string key in _underlyingRequest.Headers.AllKeys) { headers.Add(key, _underlyingRequest.Headers[key]); } _flags = flags.ToImmutable(); _params = parms.ToImmutable(); _headers = headers.ToImmutable(); }
/// <summary> /// GET请求 /// </summary> /// <param name="url"></param> /// <param name="encode"></param> /// <returns></returns> public static string Get(string url, string head, Encoding encode) { UrlInfo urlInfo = ParseURL(url); string strRequest = Format("GET {0}?{1} HTTP/1.1\r\nHost:{2}:{3}\r\nConnection:Close\r\n\r\n", urlInfo.File, urlInfo.Body, urlInfo.Host, urlInfo.Port.ToString()); if (IsNullOrEmpty(head)) { strRequest = Format("GET {0}?{1} HTTP/1.1\r\nHost:{2}:{3}\r\n{4}\r\n\r\n", urlInfo.File, urlInfo.Body, urlInfo.Host, urlInfo.Port.ToString(), head); } return(GetResponse(urlInfo.Host, urlInfo.Port, strRequest, encode)); }
/// <summary> /// POST请求 /// </summary> /// <param name="url"></param> /// <param name="encode"></param> /// <returns></returns> public static string Post(string url, string head, Encoding encode) { UrlInfo urlInfo = ParseURL(url); string strRequest = Format("POST {0} HTTP/1.1\r\nHost:{1}:{2}\r\nContent-Length:{3}\r\nContent-Type:application/x-www-form-urlencoded\r\nConnection:Close\r\n\r\n{4}", urlInfo.File, urlInfo.Host, urlInfo.Port.ToString(), urlInfo.Body.Length, urlInfo.Body); if (!IsNullOrEmpty(head)) { strRequest = Format("POST {0} HTTP/1.1\r\nHost:{1}:{2}\r\nContent-Length:{3}\r\n{5}\r\n{4}", urlInfo.File, urlInfo.Host, urlInfo.Port.ToString(), urlInfo.Body.Length, urlInfo.Body, head); } return(GetResponse(urlInfo.Host, urlInfo.Port, strRequest, encode)); }
void SetUrlId(int id) { textBox_id.Text = id.ToString(); _info = HtUrl.Get(id); textBox_url.Text = _info.HtUrl; textBox_title.Text = _info.HtTitle; textBox_summary.Text = _info.HtSummary; checkBox_ulCase.Checked = _info.HtULCase; }
private void button3_Click(object sender, EventArgs e) { UrlInfo ui = listBox1.SelectedItem as UrlInfo; if (ui != null) { _urlInfos.Remove(ui); listBox1.Items.Remove(ui); saveUrls(); } }
private void button2_Click(object sender, EventArgs e) { UrlInfo ui = new UrlInfo(); ui.Comment = textBox2.Text; ui.Url = textBox1.Text; _urlInfos.Add(ui); listBox1.Items.Add(ui); listBox1.SelectedItem = ui; saveUrls(); }
public void RedirectToUrlWithQueryStringAsDict() { var url = new UrlInfo("area", "home", "index", "", ".castle"); var response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.RedirectToUrl("/uol/com/folha", DictHelper.Create("id=1", "name=john doe")); Assert.AreEqual("/uol/com/folha?id=1&name=john+doe", response.RedirectedTo); response.RedirectToUrl("/uol/com/folha?something=1", DictHelper.Create("id=1", "name=john doe")); Assert.AreEqual("/uol/com/folha?something=1&id=1&name=john+doe", response.RedirectedTo); }
public RequestBuilder(UrlInfo urlInfo) { this._urlInfo = urlInfo; this._jsonSerializerOptions = new JsonSerializerOptions() { IgnoreNullValues = true }; this._clientInfo = new ClientAppInfo(); }
public void TestScanMovieDetails() { UrlInfo urlInfo = new UrlInfo() { EntryType = JavlibEntryType.Movie, ExactUrl = "?v=javme5yc4ufdfdfd" }; Movie movie = new Movie(); _javScrapeService.ScanMovieDetails(urlInfo, movie); _output.WriteLine(movie.ToString()); }
// public IList<UrlInfo> FindList(UrlInfo whereModel, string where, int top) { StringBuilder strSql = new StringBuilder(); strSql.Append("select "); strSql.Append("id,url,urlMd5,shortVal,comment,state,createTime,isDel "); strSql.Append("from UrlInfo "); strSql.AppendFormat("where 1=1 and {0} ", where); strSql.AppendFormat("limit {0} ", top); var result = _dbHelper.FindList<UrlInfo>(strSql.ToString(), whereModel); return result; }
public void SupportsAbsolutePaths() { var url = new UrlInfo("localhost", "", "", "https", 443, "", "area", "controller", "action", ".castle", ""); Assert.AreEqual("https://localhost/area/controller/new.castle", urlBuilder.BuildUrl(url, DictHelper.Create("action=new", "absolute=true"))); url = new UrlInfo("localhost", "", "/app", "https", 443, "", "area", "controller", "action", ".castle", ""); Assert.AreEqual("https://localhost/app/area/controller/new.castle", urlBuilder.BuildUrl(url, DictHelper.Create("action=new", "absolute=true"))); }
/// <summary> /// Extracts the database component from the specified <see cref="UrlInfo"/>. /// </summary> /// <param name="url">The URL.</param> /// <returns>Database name.</returns> public static string GetDatabase(this UrlInfo url) { var resource = url.Resource; int position = resource.IndexOf(SchemaSeparator); if (position < 0) { return(url.Resource.TryCutSuffix(SchemaSeparatorString)); } return(resource.Substring(0, position)); }
private static void AssertArguments <T>(UrlInfo current, T parameters) where T : class { if (current == null) { throw new ArgumentNullException("current"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } }
public void UrlInfo_Props() { var urlInfo = new UrlInfo() { Host = "account-url.snowflakecomputing.com" }; var settings = new SnowflakeClientSettings(new AuthInfo("user", "pw", "account"), null, urlInfo); Assert.AreEqual("account-url.snowflakecomputing.com", settings.UrlInfo.Host); Assert.AreEqual("https", settings.UrlInfo.Protocol); Assert.AreEqual(443, settings.UrlInfo.Port); }
public void RedirectUsingRoute_SpecifyingParameters() { engine.Add(new PatternRoute("/something/<param1>/admin/[controller]/[action]/[id]")); var match = new RouteMatch(); var url = new UrlInfo("area", "home", "index", "", ".castle"); var response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, match); response.RedirectUsingRoute("cart", "checkout", DictHelper.Create("param1=Marge")); Assert.AreEqual("/something/Marge/admin/cart/checkout", response.RedirectedTo); }
private async Task <int> SaveToDbAndGetKey(UrlInfo input) { try { _dbContext.Urls.Add(input); await _dbContext.SaveChangesAsync(); } catch (Exception) { } return(input.Id); }
public void AddParsedLinksToDB(List <string> urls, int iteration) { foreach (string url in urls) { UrlInfo urlInfo = new UrlInfo() { Link = url, IterationId = iteration }; this.AddLinkToDB(urlInfo); } }
/// <summary> /// Initializes a new instance of the <see cref="DefaultEngineContext"/> class. /// </summary> /// <param name="container">The container.</param> /// <param name="urlInfo">Url information</param> /// <param name="context">The context.</param> /// <param name="server">The server.</param> /// <param name="request">The request.</param> /// <param name="response">The response.</param> /// <param name="trace">The trace.</param> /// <param name="session">The session.</param> public DefaultEngineContext(IMonoRailContainer container, UrlInfo urlInfo, HttpContext context, IServerUtility server, IRequest request, IResponse response, ITrace trace, IDictionary session) : base(container) { this.container = container; this.UnderlyingContext = context; this.UrlInfo = urlInfo; this.Request = request; this.Response = response; this.Session = session; this.Server = server; this.Trace = trace; }
/// <inheritdoc/> protected override string BuildConnectionString(UrlInfo url) { SqlHelper.ValidateConnectionUrl(url); string result = string.Format("Data Source = {0}", url.Resource); if (!string.IsNullOrEmpty(url.Password)) { result += String.Format("; Password = '******'", url.Password); } return(result); }
public ActionResult <UrlInfo> PostUrlInfo(UrlInfo urlInfo) { try { UrlHelper.GenerateShortUrl(urlInfo, _config.Value.UrlPrefix, _context, _config.Value.DaysUntilExpire, _logger); } catch (Exception ex) { _logger.LogError(ex.Message, null); } return(CreatedAtAction("GetUrlInfo", new { id = urlInfo.UrlInfoId }, urlInfo)); }
/// <inheritdoc/> protected override string BuildConnectionString(UrlInfo url) { SqlHelper.ValidateConnectionUrl(url); var result = $"Data Source = {url.Resource}"; if (!string.IsNullOrEmpty(url.Password)) { result += $"; Password = '******'"; } return(result); }
public void ParseLocalLinks(string input, string result) { // setup a mock URL provider which we'll use for testing var contentUrlProvider = new Mock <IUrlProvider>(); contentUrlProvider .Setup(x => x.GetUrl(It.IsAny <IPublishedContent>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>())) .Returns(UrlInfo.Url("/my-test-url")); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing); var publishedContent = new Mock <IPublishedContent>(); publishedContent.Setup(x => x.Id).Returns(1234); publishedContent.Setup(x => x.ContentType).Returns(contentType); var mediaType = new PublishedContentType(Guid.NewGuid(), 777, "image", PublishedItemType.Media, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing); var media = new Mock <IPublishedContent>(); media.Setup(x => x.ContentType).Returns(mediaType); var mediaUrlProvider = new Mock <IMediaUrlProvider>(); mediaUrlProvider.Setup(x => x.GetMediaUrl(It.IsAny <IPublishedContent>(), It.IsAny <string>(), It.IsAny <UrlMode>(), It.IsAny <string>(), It.IsAny <Uri>())) .Returns(UrlInfo.Url("/media/1001/my-image.jpg")); var umbracoContextAccessor = new TestUmbracoContextAccessor(); IUmbracoContextFactory umbracoContextFactory = TestUmbracoContextFactory.Create( umbracoContextAccessor: umbracoContextAccessor); var webRoutingSettings = new WebRoutingSettings(); var publishedUrlProvider = new UrlProvider( umbracoContextAccessor, Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(() => new[] { contentUrlProvider.Object }), new MediaUrlProviderCollection(() => new[] { mediaUrlProvider.Object }), Mock.Of <IVariationContextAccessor>()); using (UmbracoContextReference reference = umbracoContextFactory.EnsureUmbracoContext()) { var contentCache = Mock.Get(reference.UmbracoContext.Content); contentCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent.Object); contentCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent.Object); var mediaCache = Mock.Get(reference.UmbracoContext.Media); mediaCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(media.Object); mediaCache.Setup(x => x.GetById(It.IsAny <Guid>())).Returns(media.Object); var linkParser = new HtmlLocalLinkParser(umbracoContextAccessor, publishedUrlProvider); var output = linkParser.EnsureInternalLinks(input); Assert.AreEqual(result, output); } }
public void RedirectToSiteRootUsesAppVirtualDir() { UrlInfo url = new UrlInfo("area", "home", "index", "", ".castle"); StubResponse response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.RedirectToSiteRoot(); Assert.AreEqual("/", response.RedirectedTo); url = new UrlInfo("area", "home", "index", "/app", ".castle"); response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.RedirectToSiteRoot(); Assert.AreEqual("/app/", response.RedirectedTo); }
public void Redirect_ToControllerAction() { UrlInfo url = new UrlInfo("area", "home", "index", "", ".castle"); StubResponse response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.Redirect("cart", "view"); Assert.AreEqual("/area/cart/view.castle", response.RedirectedTo); url = new UrlInfo("", "home", "index", "", ".castle"); response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, new RouteMatch()); response.Redirect("cart", "view"); Assert.AreEqual("/cart/view.castle", response.RedirectedTo); }
public OwinRequest(IOwinRequest request) { _request = request; _urlInfo = new UrlInfo(request.Uri); _cookies = new OwinRequestCookieCollection(request.Cookies); // setup the request params ImmutableDictionary <string, string> .Builder parms = ImmutableDictionary.CreateBuilder <string, string>(); ImmutableList <string> .Builder flags = ImmutableList.CreateBuilder <string>(); // import the querystring foreach (KeyValuePair <string, string[]> entry in request.Query) { if (entry.Value != null) { if (entry.Key == null) { flags.InsertRange(0, entry.Value); } else { parms.Add(entry.Key, entry.Value[0]); } } } // import the post values IFormCollection form = request.Get <IFormCollection>("Microsoft.Owin.Form#collection"); if (form != null) { foreach (KeyValuePair <string, string[]> entry in form) { parms.Add(entry.Key, entry.Value[0]); } } // import the payload //_payload = request.Body.AsMemoryStream().AsText(); using (TextReader reader = new StreamReader(request.Body)) { _payload = reader.ReadToEnd(); } // import the headers ImmutableDictionary <string, string> .Builder headers = ImmutableDictionary.CreateBuilder <string, string>(); foreach (KeyValuePair <string, string[]> entry in request.Headers) { headers.Add(entry.Key, entry.Value[0]); } _flags = flags.ToImmutable(); _params = parms.ToImmutable(); _headers = headers.ToImmutable(); }
public void SupportsPathInfoAsDictionary() { var url = new UrlInfo("", "controller", "action", "", ".castle"); var parameters = new HybridDictionary(true); parameters["action"] = "new"; parameters["querystring"] = DictHelper.Create("id=1", "name=john doe"); Assert.AreEqual("/controller/new.castle?id=1&name=john+doe", urlBuilder.BuildUrl(url, parameters)); }
/// <summary> /// Construct a structure by copying informatio from the given ChapterInfo /// </summary> /// <param name="chapter">Structure to copy information from</param> public ChapterInfo(ChapterInfo chapter) { StartTime = chapter.StartTime; EndTime = chapter.EndTime; StartOffset = chapter.StartOffset; EndOffset = chapter.EndOffset; Title = chapter.Title; Subtitle = chapter.Subtitle; Url = chapter.Url; UniqueID = chapter.UniqueID; if (chapter.Url != null) { Url = new UrlInfo(chapter.Url); } if (chapter.Picture != null) { Picture = new PictureInfo(chapter.Picture); } }
/// <summary> /// Extracts the schema component from the specified <see cref="UrlInfo"/>. /// If schema is not specified returns <paramref name="defaultValue"/>. /// </summary> /// <param name="url">The URL.</param> /// <param name="defaultValue">The default schema name.</param> /// <returns>Schema name.</returns> public static string GetSchema(this UrlInfo url, string defaultValue) { var resource = url.Resource; int position = resource.IndexOf(SchemaSeparator); if (position < 0) { return(defaultValue); } var result = resource.Substring(position + 1).TryCutSuffix(SchemaSeparatorString); return(string.IsNullOrEmpty(result) ? defaultValue : result); }
public void UseBasePathWithQuerystring() { var url = new UrlInfo("area", "controller", "action", "/app", ".castle"); Assert.AreEqual("http://localhost/theArea/home/index.castle?key=value", urlBuilder.BuildUrl(url, DictHelper.Create( "basepath=http://localhost/theArea", "area=theArea", "controller=home", "action=index", "querystring=key=value"))); }
public string GetOriginalUrl(string abreviation) { using (var ctx = new UrlContext()) { UrlInfo url = ctx.UrlInfos.Where(u => u.Abreviation == abreviation).FirstOrDefault(); if (url == null) { throw new ArgumentException("Abbreviation was not found"); } return(url.OriginalUrl); } }
/// <summary> /// 转换为urlinfo对象 /// </summary> /// <returns></returns> public UrlInfo ToUrlInfo() { var ui = new UrlInfo { PsnUrl = PsnUrl, ReplacePath = LocalPath, MarkTxt = MarkTxt, LixianUrl = tb_lx.Text, IsLixian = !tb_lx.ReadOnly }; return(ui); }
public void ShouldTryToBuildUrlUsingMatchingRoutingRule() { engine.Add(new PatternRoute("/<area>/<controller>/something/<action>/[id]")); engine.Add(new PatternRoute("/<controller>/something/<action>/[id]")); UrlInfo url = new UrlInfo("", "controller", "action", "", ".castle"); HybridDictionary dict = new HybridDictionary(true); dict["controller"] = "cart"; dict["action"] = "new"; dict["params"] = DictHelper.Create("id=10"); Assert.AreEqual("/cart/something/new/10", urlBuilder.BuildUrl(url, dict)); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultRailsEngineContext"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="urlInfo">Url information</param> /// <param name="context">The context.</param> /// <param name="container">External container instance</param> public DefaultRailsEngineContext(IServiceContainer parent, UrlInfo urlInfo, HttpContext context, IServiceProvider container) : base(parent) { _urlInfo = urlInfo; _context = context; _request = new RequestAdapter(context.Request); _trace = new TraceAdapter(context.Trace); _server = new ServerUtilityAdapter(context.Server); _response = new ResponseAdapter(context.Response, this, ApplicationPath); _url = _context.Request.RawUrl; _cache = parent.GetService(typeof(ICacheProvider)) as ICacheProvider; this.container = container; }
public virtual void SetUp() { PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase); Helpers = new HelperDictionary(); var services = new StubMonoRailServices { UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine()), UrlTokenizer = new DefaultUrlTokenizer() }; var urlInfo = new UrlInfo( "example.org", "test", "/TestBrail", "http", 80, "http://test.example.org/test_area/test_controller/test_action.tdd", Area, ControllerName, Action, "tdd", "no.idea"); StubEngineContext = new StubEngineContext(new StubRequest(), new StubResponse(), services, urlInfo); StubEngineContext.AddService<IUrlBuilder>(services.UrlBuilder); StubEngineContext.AddService<IUrlTokenizer>(services.UrlTokenizer); ViewComponentFactory = new DefaultViewComponentFactory(); ViewComponentFactory.Service(StubEngineContext); ViewComponentFactory.Initialize(); StubEngineContext.AddService<IViewComponentFactory>(ViewComponentFactory); ControllerContext = new ControllerContext { Helpers = Helpers, PropertyBag = PropertyBag }; StubEngineContext.CurrentControllerContext = ControllerContext; Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(StubEngineContext); Helpers["formhelper"] = Helpers["form"] = new FormHelper(StubEngineContext); Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(StubEngineContext); Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(StubEngineContext); var loader = new FileAssemblyViewSourceLoader("Views"); _monoRailViewEngine = new NHamlMonoRailViewEngine(); _monoRailViewEngine.TemplateEngine.Options.TemplateCompiler = new CSharp3TemplateCompiler(); _monoRailViewEngine.SetViewSourceLoader(loader); _templateEngine = _monoRailViewEngine.TemplateEngine; _templateEngine.Options.TemplateBaseType = typeof( NHamlMonoRailView ); ViewComponentFactory.Inspect(GetType().Assembly); }
public void ShouldBeAbleToConstructAnAbsoluteURLWithAppVirtualDir() { engine.Add(new PatternRoute("/<area>/<controller>/something/<action>/[id]")); engine.Add(new PatternRoute("/<controller>/something/<action>/[id]")); UrlInfo url = new UrlInfo("domain.com", null, "someproject", "http", 80, "", "", "controller", "action", ".castle", null); HybridDictionary dict = new HybridDictionary(true); dict["absolute"] = "true"; dict["controller"] = "cart"; dict["action"] = "new"; dict["params"] = DictHelper.Create("id=10"); Assert.AreEqual("http://domain.com/someproject/cart/something/new/10", urlBuilder.BuildUrl(url, dict)); }
/// <summary> /// Pendent. /// </summary> /// <param name="container"></param> /// <param name="urlInfo"></param> /// <param name="context"></param> /// <param name="routeMatch"></param> /// <returns></returns> public IEngineContext Create(IMonoRailContainer container, UrlInfo urlInfo, HttpContext context, RouteMatch routeMatch) { var session = ResolveRequestSession(container, urlInfo, context); var urlBuilder = container.UrlBuilder; var serverUtility = new ServerUtilityAdapter(context.Server); var referrer = context.Request.Headers["Referer"]; return new DefaultEngineContext(container, urlInfo, context, serverUtility, new RequestAdapter(context.Request), new ResponseAdapter(context.Response, urlInfo, urlBuilder, serverUtility, routeMatch, referrer), new TraceAdapter(context.Trace), session); }
public ProfileData( string id, string name = null, string iconImageUrl = null, AccountStatus? status = null, string firstName = null, string lastName = null, string introduction = null, string braggingRights = null, string occupation = null, string greetingText = null, string nickName = null, RelationType? relationship = null, GenderType? genderType = null, LookingFor lookingFor = null, EmploymentInfo[] employments = null, EducationInfo[] educations = null, ContactInfo[] contactsInHome = null, ContactInfo[] contactsInWork = null, UrlInfo[] otherProfileUrls = null, UrlInfo[] contributeUrls = null, UrlInfo[] recommendedUrls = null, string[] placesLived = null, string[] otherNames = null, ProfileUpdateApiFlag loadedApiTypes = ProfileUpdateApiFlag.Unloaded, DateTime? lastUpdateLookupProfile = null, DateTime? lastUpdateProfileGet = null) { if (id == null) throw new ArgumentNullException("ProfileDataの引数idをnullにする事はできません。"); //idが数字になるならばProfileIdとして正しい。違うならばG+を始めていないアカウントのEMailAddressと見なす //また、スタブモード時は先頭に"Id"の2文字が入るため、テストコード用に先頭2文字を省いてParse()する。 double tmp; if (status == AccountStatus.Active && double.TryParse(id.Substring(2), out tmp) == false) throw new ArgumentException("ProfileDataの引数idがメアド状態で引数statusをActiveにする事はできません。"); LoadedApiTypes = loadedApiTypes; Status = status; Id = id; Name = name; FirstName = firstName; LastName = lastName; Introduction = introduction; BraggingRights = braggingRights; Occupation = occupation; GreetingText = greetingText; NickName = nickName; IconImageUrl = iconImageUrl; Relationship = relationship; Gender = genderType; LookingFor = lookingFor; Employments = employments; Educations = educations; ContactsInHome = contactsInHome; ContactsInWork = contactsInWork; OtherProfileUrls = otherProfileUrls; ContributeUrls = contributeUrls; RecommendedUrls = recommendedUrls; PlacesLived = placesLived; OtherNames = otherNames; LastUpdateLookupProfile = lastUpdateLookupProfile ?? DateTime.MinValue; LastUpdateProfileGet = lastUpdateProfileGet ?? DateTime.MinValue; }
/// <summary> /// 增加一条记录 /// </summary> /// <param name="urlinfo"></param> /// <returns></returns> public bool AddLog(UrlInfo urlinfo) { if (!UpdataLog(urlinfo)) { var psnrecord = new XElement("PsnRecord", new XElement("Names", urlinfo.MarkTxt), new XElement("PsnUrl", urlinfo.PsnUrl), new XElement("LocalUrl", urlinfo.ReplacePath), new XElement("isLixian", urlinfo.IsLixian), new XElement("LixianUrl", urlinfo.LixianUrl) ); _datas.Add(psnrecord); _datas.Save(Xmlpath); return true; } return false; }
/// <summary> /// 删除一条记录 /// </summary> /// <param name="urlinfo"></param> /// <returns></returns> public bool DelLog(UrlInfo urlinfo) { try { XElement log = (from el in _datas.Elements("PsnRecord") let xElement = el.Element("PsnUrl") where xElement != null && xElement.Value == urlinfo.PsnUrl select el).FirstOrDefault(); if (log != null) log.Remove(); _datas.Save(Xmlpath); return true; } catch { return false; } }
/// <summary> /// Creates a target rewrite path using the specified URL settings and entity ID. /// </summary> /// <param name="urlInfo">URL settings.</param> /// <param name="entityId">Entity ID.</param> /// <returns></returns> private string CreateRewritePath(UrlInfo urlInfo, string entityId) { var rewritePath = urlInfo.DetailPageUrl.Replace(_rewritePathIdToken, entityId); // Change absolute URL to relative URL if needed if (rewritePath.StartsWith("http", StringComparison.OrdinalIgnoreCase)) rewritePath = new Uri(rewritePath, UriKind.Absolute).PathAndQuery; // Ensure rewrite path references file with extension if (!rewritePath.Contains(".")) if (rewritePath.Contains("?")) rewritePath = rewritePath.Replace("?", ".aspx?"); else rewritePath += ".aspx"; return rewritePath; }
/// <summary> /// 更新某地址的链接数 /// </summary> /// <param name="ip">IP地址</param> /// <param name="Url">请求的url绝对地址</param> /// <param name="isadd">是否增加,否则就是减</param> public void UpdateUrlConnNums(string ip, string Url, bool isadd) { if (!this.monitorInfo.ContainsKey(ip)) { lock (lockupdateconnnums) { if (!this.monitorInfo.ContainsKey(ip)) { LinkModel model = new LinkModel(); model.ClientIP = ip; model.UrlInfoList = new Dictionary<string, UrlInfo>(); UrlInfo url = new UrlInfo(); url.ConnNums = 0; url.OperateNums = new Dictionary<string, long>(); model.UrlInfoList[Url] = url; this.monitorInfo[ip] = model; } } } if (this.monitorInfo.ContainsKey(ip)) { lock (lockupdateconnnums) { if (!this.monitorInfo[ip].UrlInfoList.ContainsKey(Url)) { UrlInfo url = new UrlInfo(); url.ConnNums = 0; url.OperateNums = new Dictionary<string, long>(); this.monitorInfo[ip].UrlInfoList[Url] = url; } if (isadd) this.monitorInfo[ip].UrlInfoList[Url].ConnNums += 1; else this.monitorInfo[ip].UrlInfoList[Url].ConnNums -= 1; //if (this.monitorInfo[ip].UrlInfoList[Url].ConnNums < 0) // this.monitorInfo[ip].UrlInfoList[Url].ConnNums = 0; } } }