public static string EncodeUri(Uri uri) { if (!uri.IsAbsoluteUri) { var uriString = uri.IsWellFormedOriginalString() ? uri.ToString() : Uri.EscapeUriString(uri.ToString()); return EscapeReservedCspChars(uriString); } var host = uri.Host; var encodedHost = EncodeHostname(host); var needsReplacement = !host.Equals(encodedHost); var authority = uri.GetLeftPart(UriPartial.Authority); if (needsReplacement) { authority = authority.Replace(host, encodedHost); } if (uri.PathAndQuery.Equals("/")) { return authority; } return authority + EscapeReservedCspChars(uri.PathAndQuery); }
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 async void OnMessage(IMessage message) { try { if (!message.IsFromMyself && !message.IsHistorical) { var match = regex.Match(message.FullBody); if (regex.IsMatch(message.FullBody)) { var uri = new Uri(message.FullBody); if (uri.IsWellFormedOriginalString()) { var reply = this.MakeReply(await this.QueryAsync(uri)); if (!String.IsNullOrWhiteSpace(reply)) { // TODO: gotta get new lines sorted out await this.backend.SendMessageAsync(message.ReplyTo, reply); } } } } } catch(Exception e) { Console.Error.WriteLine(e); // TODO: handle better } }
public bool checkConfig() { try { Uri uri = new Uri(Attr.EMDRServer); if (!uri.IsWellFormedOriginalString()) { return false; } } catch (Exception) { return false; } try { var conn = new SqlConnectionStringBuilder(Attr.DataSource); } catch (Exception) { return false; } if ( Attr.TrimHistDays < 0 || Attr.TrimHistDays > 1000000 || Attr.TrimOrdersDays < 0 || Attr.TrimOrdersDays > 1000000) { return false; } return true; }
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 = "不明路径"; } }
protected internal virtual bool IsWellFormedOriginalString(Uri uri) { // well formed according to RFC2396 and RFC2732 // see Uri.IsWellFormedOriginalString for some docs // Though this class does not seem to do anything. Even null arguments aren't checked :/ return(uri.IsWellFormedOriginalString()); }
public bool AdvanceNext() { var page = new Uri(_domain, _currentLocation); var doc = _web.Load(page.ToString()); string location = _ScrapeNextLink(doc); _currentLocation = new Uri(location, UriKind.Relative); return !String.IsNullOrEmpty(location) && _currentLocation.IsWellFormedOriginalString(); }
public static void GetDomain(string fromUrl, out string domain, out string subDomain) { domain = ""; subDomain = ""; try { if (fromUrl.IndexOf("的名片") > -1) { subDomain = fromUrl; domain = "名片"; } else { fromUrl = new UriBuilder(fromUrl).ToString(); Uri uri = new Uri(fromUrl); if (uri.IsWellFormedOriginalString()) { if (uri.IsFile) { subDomain = domain = "客户端本地文件路径"; } else { string authority = uri.Authority; string[] strArray = uri.Authority.Split(new char[] { '.' }); if (strArray.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 (strArray.Length < 2) { domain = "不明路径"; subDomain = "不明路径"; } } } else if (uri.IsFile) { subDomain = domain = "客户端本地文件路径"; } else { subDomain = domain = "不明路径"; } } } catch { subDomain = domain = "不明路径"; } }
static public int IsWellFormedOriginalString(IntPtr l) { try { System.Uri self = (System.Uri)checkSelf(l); var ret = self.IsWellFormedOriginalString(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
private HtmlDocument _GetCurrentDocument() { // Form the page URI Uri page = new Uri(_domain, _currentLocation); HtmlDocument doc = null; // If we have a well formed URI then load the page and return it if (page.IsWellFormedOriginalString()) { doc = _web.Load(page.ToString()); } return doc; }
static int IsWellFormedOriginalString(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); System.Uri obj = (System.Uri)ToLua.CheckObject <System.Uri>(L, 1); bool o = obj.IsWellFormedOriginalString(); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
/// <summary> /// Checks a uri returns a 200 response /// </summary> /// <param name="uri">The <see cref="System.Uri"/> to test</param> /// <returns>True if a 200 response is received. False otherwise.</returns> protected bool TryUri(System.Uri uri) { try { if (!uri.IsWellFormedOriginalString()) { // TODO: Fix or throw on bad uri } var client = httpClient ?? (httpClient = new HttpClient()); var response = httpClient.GetAsync(uri).Result; return(HttpStatusCode.OK == response.StatusCode); } catch (System.Exception ex) { return(false); } }
/// <summary> /// Internal method for rendering links /// </summary> public static string RenderLink(BBCodeNode Node, bool ThrowOnError, object LookupTable) { if ((Node.Attribute ?? "").Trim() == "") if (Node.Children.Length != 0 && (Node.Children[0] as BBCodeTextNode) == null) if (ThrowOnError) throw new HtmlRenderException("[url] tag does not contain a URL attribute"); else return Error(Node, LookupTable); else { // support self-links such as [url]http://google.com[/url] Node = ((BBCodeNode)Node.Clone()); // Nodes are mutable, and we don't want to mess with the original Node. Node.Attribute = Node.Children[0].ToString(); } Uri src = null; try { src = new Uri(Node.Attribute); } catch (UriFormatException) { if (ThrowOnError) throw; return Error(Node, LookupTable); } if (!src.IsWellFormedOriginalString()) if (ThrowOnError) throw new HtmlRenderException("URL in [url] tag not well formed or relative"); else return Error(Node, LookupTable); if (!src.Scheme.Contains("http")) if (ThrowOnError) throw new HtmlRenderException("URL scheme must be either HTTP or HTTPS"); else return Error(Node, LookupTable); return "<a href=\"" + HttpUtility.HtmlEncode(src.ToString()) + "\">" + Node.Children.ToHtml() + "</a>"; }
/// <summary> /// Internal method for rendering images /// </summary> public static string RenderImage(BBCodeNode Node, bool ThrowOnError, object LookupTable) { if (Node.Children.Length != 1) if (ThrowOnError) throw new HtmlRenderException("[img] tag does not to contain image URL"); else return Error(Node, LookupTable); if ((Node.Children[0] as BBCodeTextNode) == null) if (ThrowOnError) throw new HtmlRenderException("[img] tag does not to contain image URL"); else return Error(Node, LookupTable); Uri src = null; try { src = new Uri(Node.Children[0].ToString(), UriKind.Absolute); } catch (UriFormatException) { if (ThrowOnError) throw; return Error(Node, LookupTable); } if (!src.IsWellFormedOriginalString()) if (ThrowOnError) throw new HtmlRenderException("Image URL in [img] tag not well formed or relative"); else return Error(Node, LookupTable); if (!src.Scheme.Contains("http")) if (ThrowOnError) throw new HtmlRenderException("Image URL scheme must be either HTTP or HTTPS"); else return Error(Node, LookupTable); return "<img src=\"" + HttpUtility.HtmlEncode(src.ToString()) + "\" alt=\"" + HttpUtility.HtmlEncode(src.ToString()) + "\" />"; }
private static bool IsValidRedirectDomain(string redirectDomain) { if (!redirectDomain.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && !redirectDomain.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { return false; } try { var redirectUri = new Uri(redirectDomain, UriKind.Absolute); return redirectUri.IsWellFormedOriginalString(); } catch (FormatException) { return false; } }
/// <summary>Indicates whether a URI is well-formed.</summary> /// <returns>true if <paramref name="uri" /> is well-formed; otherwise, false.</returns> /// <param name="uri">The URI to check.</param> protected internal virtual bool IsWellFormedOriginalString(System.Uri uri) { return(uri.IsWellFormedOriginalString()); }
public void Filex_Methods () { Uri uri = new Uri ("filex:///readme.txt"); Assert.AreEqual ("readme.txt", uri.GetComponents (UriComponents.Path, UriFormat.SafeUnescaped), "GetComponents"); Assert.IsTrue (uri.IsBaseOf (uri), "IsBaseOf"); Assert.IsTrue (uri.IsWellFormedOriginalString (), "IsWellFormedOriginalString"); // ??? our parser doesn't seems to be called :( }
public void ProcessExtraPages(int pageHighest) { int num = 0; if (num > pageHighest) { num = pageHighest; } do { num += 40; Uri argUri = new Uri(this.threadURL + "&s=" + num.ToString()); string argDestFilename = "s_" + num.ToString() + "_" + this.destFile; if (argUri.IsWellFormedOriginalString()) { this.watchThreadManager.AddURL(argUri, Path.Combine(this.destFolder, num.ToString()), argDestFilename, this.downloadImages, this.downloadLinkTypes, Convert.ToInt32(this.updateInterval), this.username, this.password, this.threadName, true); } } while (num <= pageHighest); }
/// <summary> /// Starts the actual service /// </summary> /// <param name="fallen8"> Fallen-8. </param> private void StartService(Fallen8 fallen8) { #region configuration var configs = new Dictionary<String, String>(); foreach (String key in ConfigurationManager.AppSettings) { var value = ConfigurationManager.AppSettings[key]; configs.Add(key, value); } String adminIpAddress; configs.TryGetValue("AdminIPAddress", out adminIpAddress); UInt16 adminPort = 2323; String adminPortString; if(configs.TryGetValue("AdminPort", out adminPortString)) { adminPort = Convert.ToUInt16(adminPortString); } String adminUriPattern; configs.TryGetValue("AdminUriPattern", out adminUriPattern); String restServiceAddress; configs.TryGetValue("RESTServicePattern", out restServiceAddress); #endregion var address = String.IsNullOrWhiteSpace(adminIpAddress) ? IPAddress.Any.ToString() : adminIpAddress; var port = adminPort; var uriPattern = String.IsNullOrWhiteSpace(adminUriPattern) ? "Admin" : adminUriPattern; _uri = new Uri("http://" + address + ":" + port + "/" + uriPattern); if (!_uri.IsWellFormedOriginalString()) throw new Exception("The URI pattern is not well formed!"); Service = new AdminService(fallen8); _host = new ServiceHost(Service, _uri) { CloseTimeout = new TimeSpan(0, 0, 0, 0, 50) }; _restServiceAddress = String.IsNullOrWhiteSpace(restServiceAddress) ? "REST" : restServiceAddress; try { var binding = new WebHttpBinding { MaxBufferSize = 268435456, MaxReceivedMessageSize = 268435456, SendTimeout = new TimeSpan(1, 0, 0), ReceiveTimeout = new TimeSpan(1, 0, 0) }; var readerQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 2147483647, MaxStringContentLength = 2147483647, MaxBytesPerRead = 2147483647, MaxNameTableCharCount = 2147483647, MaxArrayLength = 2147483647 }; binding.ReaderQuotas = readerQuotas; var se = _host.AddServiceEndpoint(typeof (IAdminService), binding, _restServiceAddress); var webBehav = new WebHttpBehavior { HelpEnabled = true }; se.Behaviors.Add(webBehav); ((ServiceBehaviorAttribute) _host.Description.Behaviors[typeof (ServiceBehaviorAttribute)]). InstanceContextMode = InstanceContextMode.Single; } catch (Exception) { _host.Abort(); throw; } }
private void btnAddClicked(object sender, RoutedEventArgs e) { try { Uri argUri = new Uri(this.txtURL.Text); if (argUri.IsWellFormedOriginalString()) { if (!this.theWatchManager.AddURL(argUri)) { this.winAddAdvanced = new windowAddAdvanced(argUri); this.winAddAdvanced.RegisterWatchThreadManager(ref this.theWatchManager); this.winAddAdvanced.Show(); } if (Properties.Settings.Default.AutoSaveOnAdd) { this.wts.Serialize(this.theWatchManager, this.theDownloadManager); } } else { BrushConverter converter = new BrushConverter(); this.txtURL.Background = converter.ConvertFromString("RED") as SolidColorBrush; } } catch (Exception) { BrushConverter converter2 = new BrushConverter(); this.txtURL.Background = converter2.ConvertFromString("RED") as SolidColorBrush; } }
public void Generic_Methods () { Uri uri = new Uri ("generic://www.mono-project.com/"); Assert.AreEqual (String.Empty, uri.GetComponents (UriComponents.Path, UriFormat.SafeUnescaped), "GetComponents"); Assert.IsTrue (uri.IsBaseOf (uri), "IsBaseOf"); Assert.IsTrue (uri.IsWellFormedOriginalString (), "IsWellFormedOriginalString"); }
private static IEnumerable<ServerInfo> ParseServerUris(IEnumerable<string> serverStrings) { var results = new List<ServerInfo>(); int id = 0; foreach (string server in serverStrings) { id++; Uri uri; try { uri = new Uri("bnet://" + server); } catch (UriFormatException) { uri = null; } if (uri == null || !uri.IsWellFormedOriginalString() || string.IsNullOrEmpty(uri.UserInfo) || uri.UserInfo.IndexOf(':') > -1) { Console.WriteLine("Invalid server: " + server); return null; } int port = uri.IsDefaultPort ? 2302 : uri.Port; results.Add( new ServerInfo { ServerId = id, ServerName = uri.DnsSafeHost + ":" + port, LoginCredentials = new BattlEyeLoginCredentials { Host = uri.DnsSafeHost, Port = port, Password = uri.UserInfo } }); } if (results.Count > 0) { return results; } return null; }
/// <summary> /// Start the intro service /// </summary> /// <param name="fallen8"> Fallen-8 instance </param> private void StartService(Fallen8 fallen8) { _uri = new Uri("http://" + _address + ":" + _port + "/" + _uriPattern); if (!_uri.IsWellFormedOriginalString()) throw new Exception("The URI Pattern is not well formed!"); _service = new IntroService(fallen8); _host = new ServiceHost(_service, _uri) { CloseTimeout = new TimeSpan(0, 0, 0, 0, 50) }; _restServiceAddress = "REST"; try { var binding = new WebHttpBinding { MaxBufferSize = 268435456, MaxReceivedMessageSize = 268435456, SendTimeout = new TimeSpan(1, 0, 0), ReceiveTimeout = new TimeSpan(1, 0, 0) }; var readerQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 2147483647, MaxStringContentLength = 2147483647, MaxBytesPerRead = 2147483647, MaxNameTableCharCount = 2147483647, MaxArrayLength = 2147483647 }; binding.ReaderQuotas = readerQuotas; var se = _host.AddServiceEndpoint(typeof(IIntroService), binding, _restServiceAddress); var webBehav = new WebHttpBehavior { HelpEnabled = true }; se.Behaviors.Add(webBehav); ((ServiceBehaviorAttribute)_host.Description.Behaviors[typeof(ServiceBehaviorAttribute)]). InstanceContextMode = InstanceContextMode.Single; } catch (CommunicationException) { _host.Abort(); throw; } }
public Stream LoadPage(Uri pageUri, bool authentification = true) { if (pageUri.IsWellFormedOriginalString()) { HttpWebRequest request; if (authentification && siteNeedAuthentification && !isAlreadyAuthenticate) { request = (HttpWebRequest)WebRequest.Create(pageUri); PrepareRequest(request, cookies); request.Method = WebRequestMethods.Http.Post; request.AllowWriteStreamBuffering = true; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = loginBytes.Length; Stream newStream = request.GetRequestStream(); newStream.Write(loginBytes, 0, loginBytes.Length); newStream.Close(); // Just eat the response var result = request.GetResponse().GetResponseStream(); new StreamReader(result).ReadToEnd(); isAlreadyAuthenticate = true; } request = (HttpWebRequest)WebRequest.Create(pageUri); PrepareRequest(request, cookies); return request.GetResponse().GetResponseStream(); } else { Logger.Warning("The web documentation page {0} is not a valid Uri", pageUri); return null; } }
public void NewsX_Methods () { Uri uri = new Uri ("newsx://go-mono.com/"); Assert.AreEqual ("//go-mono.com/", uri.GetComponents (UriComponents.Path, UriFormat.SafeUnescaped), "GetComponents"); Assert.IsTrue (uri.IsBaseOf (uri), "IsBaseOf"); Assert.IsTrue (uri.IsWellFormedOriginalString (), "IsWellFormedOriginalString"); // ??? our parser doesn't seems to be called :( }
public DataSettings ChangePanoramaPublishUri(Uri newUri) { if (!newUri.IsWellFormedOriginalString()) // https://msdn.microsoft.com/en-us/library/system.uri.iswellformedoriginalstring throw new ArgumentException(string.Format(Resources.DataSettings_ChangePanoramaPublishUri_The_URI__0__is_not_well_formed_, newUri)); return ChangeProp(ImClone(this), im => im.PanoramaPublishUri = newUri); }
public void UrlIsWellFormedAndPointsToTheCorrectServer() { var urlList = new List<string>(); //Fetching Parent node Urls urlList.AddRange(HPFortifyXMLMapping.Select(x => x.ArticleUrl)); //Fetching Child urls var subcategoryUrl = (from query in HPFortifyXMLMapping from subcategory in query.SubCategories select subcategory.ArticleUrl).ToList(); //Merging both Url list to make processing easier urlList.AddRange(subcategoryUrl); foreach(var url in urlList) { var tempUrl = new System.Uri(url); Assert.IsTrue(tempUrl.Scheme =="https"); Assert.IsTrue(tempUrl.Host=="vulnerabilities.teammentor.net"); Assert.IsTrue(tempUrl.IsWellFormedOriginalString()); } }
/// <summary> /// 从适配的url还原为原图的url 来自taobao datahelper /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetRestoreImgUrl(string url) { if (!string.IsNullOrEmpty(url) && url.StartsWith("//")) { url = "https:" + url; } Uri uri = null; try { uri = new Uri(url); } catch (Exception) { return url; } if (!uri.IsWellFormedOriginalString()) { return url; } if (uri.Scheme != "http" && uri.Scheme != "https") { return url; } string host = uri.Host.ToLower(); if (host.IndexOf(".alicdn.com") == -1 && host.IndexOf(".mmcdn.cn") == -1 && host.IndexOf(".taobaocdn.com") == -1) { return url; } string checkString = null; if (uri.Segments != null && uri.Segments.Length != 0) { checkString = uri.Segments.Last(); } else { return url; } checkString = checkString.ToLower(); // 默认头像不能改大小 if (checkString.IndexOf("avatar") != -1) { return url; } int nIndex = -1; if (checkString.EndsWith(".jpg")) { while (true) { int nIndexPoint = checkString.IndexOf(".png_"); if (nIndexPoint != -1) { nIndex = nIndexPoint + 4; break; } nIndexPoint = checkString.IndexOf(".jpg_"); if (nIndexPoint != -1) { nIndex = nIndexPoint + 4; break; } nIndexPoint = checkString.IndexOf(".jpeg_"); if (nIndexPoint != -1) { nIndex = nIndexPoint + 5; break; } nIndexPoint = checkString.IndexOf(".gif_"); if (nIndexPoint != -1) { nIndex = nIndexPoint + 4; break; } nIndexPoint = checkString.IndexOf(".ss2_"); if (nIndexPoint != -1) { nIndex = nIndexPoint + 4; break; } break; } if (nIndex == -1) { return url; } string path = string.Empty; for (int i = 0; i < uri.Segments.Length - 1; i++) { path += uri.Segments[i]; } var fileName = uri.Segments.Last().Substring(0, nIndex); var fileArray = fileName.Split('.'); if (fileArray.Length > 2)// 多个.xxx后缀 { fileName = "" + fileArray[0];// +"."+ fileArray[1]; var fileEnds = new List<string>() { "jpg", "png", "gif", "jpeg", "ss2" }; for (int i = 1; i < fileArray.Length; i++) { fileName += "." + fileArray[i]; if (fileEnds.Contains(fileArray[i].ToLower())) { break; } } } path += fileName; string result = string.Format("{0}://{1}{2}{3}", uri.Scheme, uri.Authority, path, uri.Query); //System.Diagnostics.Debug.WriteLine(result); return result; } else { return url; } }
public WebPage(Uri address) { _logger = ObjectLocator.LocateObject<ILog>(); WebPageAddress = address; DOM = new HtmlDocument(); if(!address.IsWellFormedOriginalString()) { _logger.Info("WebSite address is not well formed."); return; } _logger.Info(String.Format("Using Scheme: {0}", address.Scheme)); String scheme = address.Scheme; if (scheme.Equals("file")) { _logger.Info(String.Format("Loading site from file")); try { using (var filestream = File.Open(address.AbsoluteUri, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { _logger.Info(String.Format("file loaded")); DOM.Load(filestream); _logger.Info(String.Format("DOM loaded :)")); } Title = GetPageTitle(); } catch (IOException ioException) { _logger.Info(String.Format("Unable to load file: {0}", address.AbsoluteUri), ioException); Title = "404"; } } else { try { using (var response = WebRequest.Create(address).GetResponse()) using (var s = response.GetResponseStream()) { _logger.Info(String.Format("webpage loaded")); DOM.Load(s); _logger.Info(String.Format("DOM loaded :)")); } Title = GetPageTitle(); } catch (WebException webException) { _logger.Info(String.Format("Unable to load webpage: {0}", address.AbsoluteUri), webException); Title = "404"; } } PathWithoutQuery= address.AbsoluteUri.Split('?')[0]; String fn = PathWithoutQuery.Substring(PathWithoutQuery.LastIndexOf('/')); WebPageFileName = fn == "/" ? "index.html" : fn; SourceCode = GetSource(DOM); }
public void TestUTF8Strings () { string [] tests = { "file:///tmp/x (%232).jpg", "file:///tmp/ü (%232).jpg" }; foreach (string test in tests) { Uri uri = new Uri (test); Assert.IsFalse (uri.IsWellFormedOriginalString (), "IsWellFormedOriginalString/" + test); Assert.AreEqual (test, uri.OriginalString, "OriginalString/" + test); Assert.AreEqual (test, uri.ToString (), "ToString/" + test); } }
protected void StartService() { Dictionary<string, string> configs = ConfigHelper.GetPluginSpecificConfig (PluginName); // wenn ein zweiter Port vorhanden ist, kann eine zweite Instanz gestartet werden int instances = configs.ContainsKey ("2ndPort") ? 2 : 1; string[] prefixes = new string[] { "", "2nd" }; // TODO: Dynamisch Anzahl und Art der Prefixes herausfinden; momentan sind die Werte fix (max 2 Prefixes/Instanzen, einmal "" und einmal "2nd") try { for (int instance = 1; instance <= instances; instance++) { String authMethod = ConfigHelper.GetInstanceParam (configs, "AuthenticationMethod", prefixes, instance); ServiceSecurity serviceSecurity = new ServiceSecurity (authMethod); Uri uri = new Uri (serviceSecurity.HTTP_S + "://" + _address + ":" + _port + "/" + _uriPattern + "/REST"); if (!uri.IsWellFormedOriginalString ()) { throw new Exception ("The URI Pattern is not well formed!"); } _uris.Add (uri); ServiceHost host = new ServiceHost (_service, uri) { CloseTimeout = new TimeSpan (0, 0, 0, 0, 50) }; _hosts.Add (host); var binding = new WebHttpBinding { MaxReceivedMessageSize = 268435456, SendTimeout = new TimeSpan (1, 0, 0), ReceiveTimeout = new TimeSpan (1, 0, 0), // für Security: Anhand des Binding-Namens wird eruiert, welche ConfigSection & Prefix für diese ServiceBinding-Instanz genutzt werden soll Name = PluginName + "." + prefixes [instance - 1] }; binding.Security.Mode = serviceSecurity.BindingSecurityMode; binding.Security.Transport.ClientCredentialType = serviceSecurity.BindingClientCredentialType; var readerQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 2147483647, MaxStringContentLength = 2147483647, MaxBytesPerRead = 2147483647, MaxNameTableCharCount = 2147483647, MaxArrayLength = 2147483647 }; binding.ReaderQuotas = readerQuotas; var se = host.AddServiceEndpoint (RESTServiceInterfaceType, binding, uri); var webBehav = new WebHttpBehavior { FaultExceptionEnabled = true, HelpEnabled = true }; se.Behaviors.Add (webBehav); // this adds a additional instanceId header to every response se.Behaviors.Add (new FaultTolerantServiceBehavior ()); ((ServiceBehaviorAttribute)host.Description.Behaviors [typeof(ServiceBehaviorAttribute)]).InstanceContextMode = InstanceContextMode.Single; } } catch (Exception) { _hosts.ForEach (h => h.Abort ()); throw; } }
public static string ConstructBNetConnectionString( string user, string pwd, string host, string port, string db) { Uri uri; try { string uriString = string.Format("mysql://{0}:{1}", host, port); uri = new Uri(uriString); } catch (UriFormatException) { uri = null; } if (uri == null || !uri.IsWellFormedOriginalString() || string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(pwd) || string.IsNullOrWhiteSpace(db)) { return null; } var connString = string.Format( "server='{2}';port={3};database='{4}';User Id='{0}';Password='******';" + "Check Parameters=false;Persist Security Info=False;Allow Zero Datetime=True;Convert Zero Datetime=True;", user, pwd, host, port, db); return ConstructBNetEntityConnectionString(connString); }
protected internal virtual bool IsWellFormedOriginalString (Uri uri) { // well formed according to RFC2396 and RFC2732 // see Uri.IsWellFormedOriginalString for some docs // Though this class does not seem to do anything. Even null arguments aren't checked :/ return uri.IsWellFormedOriginalString (); }
public void Ldapx_Methods () { Uri uri = new Uri ("ldapx://www.mono-project.com/"); Assert.AreEqual (String.Empty, uri.GetComponents (UriComponents.Path, UriFormat.SafeUnescaped), "GetComponents"); Assert.IsTrue (uri.IsBaseOf (uri), "IsBaseOf"); Assert.IsTrue (uri.IsWellFormedOriginalString (), "IsWellFormedOriginalString"); // ??? our parser doesn't seems to be called :( }
/// <summary> /// Method used to upload videos to a specific user account in Azure Video Indexer. /// Once a video is successfully uploaded, VI automatically indexes it to extract insights. /// When uploading your video based on the URL (preferred) the endpoint must be secured with TLS 1.2 (or higher). /// The upload size with the URL option is limited to 30GB. /// The upload size with the byte array option is limited to 2GB. /// Video Indexer has a max duration limit of 4 hours for a single file. /// Docs: https://docs.microsoft.com/en-us/azure/media-services/video-indexer/upload-index-videos. /// </summary> /// <param name="name">The video's name. A name of the video must be no greater than 80 characters.</param> /// <param name="ispublic">Set to true for public videos, false for private.</param> /// <param name="desc">Description of the video.</param> /// <param name="videoUrl">The location of the video file. For the public url upload method, the URL needs to be encoded.</param> /// <param name="method">Specifies which method to use. See enum comments for details on available options.</param> /// <returns>HTTP request result.</returns> public async Task <string> UploadVideoAsync(string name, bool ispublic, string desc, System.Uri videoUrl, UploadMethod method) { // Validate parameters first if (name?.Length == 0) { throw new ArgumentException(VideoIndexerErrorMessageEmptyVideoName); } if (videoUrl != null && videoUrl.IsWellFormedOriginalString()) { throw new ArgumentException(VideoIndexerErrorMessageInvalidUrl); } MultipartFormDataContent content = new MultipartFormDataContent(); // The parameters of the video. This is only a partial list for now. For the full list, see: // https://api-portal.videoindexer.ai/docs/services/Operations/operations/Upload-Video. string queryParams = CreateQueryString( new Dictionary <string, string>() { // Required. Should be given as parameter in URL query string or in Authorization header as Bearer token, // and match the authorization scope of the call (Account, with Write). // Note that Access tokens expire within 1 hour. { "accessToken", this.accountAccessToken }, // The name of the video. { "name", name }, // The video description. { "description", desc }, // The video privacy mode. Allowed values: Private/Public. { "privacy", ispublic ? "public" : "private" }, // A partition to partition videos by (used for searching a specific partition). // TODO: Allow parameter to set the partition. Fixed for now. { "partition", "partition" }, }); switch (method) { case UploadMethod.LocalFile: // TODO: Implement gradual multipart upload to allow for larger files than 2GB. // FileStream video = File.OpenRead(videoUrl.ToString()); // byte[] buffer =new byte[video.Length]; // video.Read(buffer, 0, buffer.Length); // This is limited to 4.2GB files, but VI doesn't allow for byte array uploads bigger than 2GB. byte[] videodata = File.ReadAllBytes(videoUrl?.LocalPath); content.Add(new ByteArrayContent(videodata)); break; case UploadMethod.PublicUrl: queryParams += $"&videoUrl={videoUrl}"; break; case UploadMethod.SendToBlobStorage: break; default: break; } Uri requestUri = new Uri($"{VideoIndexerApiUrl}/{this.accountLocation}/Accounts/{this.accountId}/Videos?{queryParams}"); var uploadRequestResult = await client.PostAsync(requestUri, content).ConfigureAwait(false); content.Dispose(); return(await uploadRequestResult.Content.ReadAsStringAsync().ConfigureAwait(false)); }