示例#1
0
    /// <summary>
    /// Apply the changes and remain on this page
    /// </summary>
    public void btnApply_Click(object sender, System.EventArgs e)
    {
        if (SaveData())
            {
                //
                // Redirect back to this page in Edit mode
                //
                if (DataEntryMode == PageDataEntryMode.AddRow)
                {
                    UriBuilder EditUri = new UriBuilder(Request.Url);
                    EditUri.Query += string.Format("{0}={1}", "szh_id", m_szh_idCurrent);

                    //
                    // Redirect back to this page
                    // with the primary key information in the query string
                    //
                    Response.Redirect(EditUri.ToString());

                }
                else
                {
                    lblMessage.Text = "Sazeh saved";

                    LoadData();
                }
            }
            else
            {
                lblMessage.Text = "Error saving Sazeh";
                DataEntryMode = PageDataEntryMode.ErrorOccurred;
            }
    }
示例#2
0
    public MsiHackExtension()
    {
        /* Figure out where we are. */
        string strCodeBase = Assembly.GetExecutingAssembly().CodeBase;
        //Console.WriteLine("MsiHackExtension: strCodeBase={0}", strCodeBase);

        UriBuilder uri = new UriBuilder(strCodeBase);
        string strPath = Uri.UnescapeDataString(uri.Path);
        //Console.WriteLine("MsiHackExtension: strPath={0}", strPath);

        string strDir = Path.GetDirectoryName(strPath);
        //Console.WriteLine("MsiHackExtension: strDir={0}", strDir);

        string strHackDll = strDir + "\\MsiHack.dll";
        //Console.WriteLine("strHackDll={0}", strHackDll);

        try
        {
            IntPtr hHackDll = NativeMethods.LoadLibrary(strHackDll);
            Console.WriteLine("MsiHackExtension: Loaded {0} at {1}!", strHackDll, hHackDll.ToString("X"));
        }
        catch (Exception Xcpt)
        {
            Console.WriteLine("MsiHackExtension: Exception loading {0}: {1}", strHackDll, Xcpt);
        }
    }
示例#3
0
        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 = "����·��";
            }
        }
示例#4
0
文件: Uri.cs 项目: s7loves/pesta
        public Uri(UriBuilder builder)
        {
            scheme = builder.getScheme();
            authority = builder.getAuthority();
            path = builder.getPath();
            query = builder.getQuery();
            fragment = builder.getFragment();
            queryParameters = new Dictionary<string,List<string>>(builder.getQueryParameters());

            StringBuilder _out = new StringBuilder();

            if (!String.IsNullOrEmpty(scheme))
            {
                _out.Append(scheme).Append(':');
            }
            if (!String.IsNullOrEmpty(authority)) 
            {
                _out.Append("//").Append(authority);
            }
            if (!String.IsNullOrEmpty(path)) 
            {
                _out.Append(path);
            }
            if (!String.IsNullOrEmpty(query)) 
            {
                _out.Append('?').Append(query);
            }
            if (!String.IsNullOrEmpty(fragment)) 
            {
                _out.Append('#').Append(fragment);
            }
            text = _out.ToString();
        }
        public void TryReadQueryAsSucceeds()
        {
            object value;
            UriBuilder address = new UriBuilder("http://some.host");

            address.Query = "a=2";
            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject1), out value), "Expected 'true' reading valid data");
            SimpleObject1 so1 = (SimpleObject1)value;
            Assert.NotNull(so1);
            Assert.Equal(2, so1.a);

            address.Query = "b=true";
            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject2), out value), "Expected 'true' reading valid data");
            SimpleObject2 so2 = (SimpleObject2)value;
            Assert.NotNull(so2);
            Assert.True(so2.b, "Value should have been true");

            address.Query = "c=hello";
            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject3), out value), "Expected 'true' reading valid data");
            SimpleObject3 so3 = (SimpleObject3)value;
            Assert.NotNull(so3);
            Assert.Equal("hello", so3.c);

            address.Query = "c=";
            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject3), out value), "Expected 'true' reading valid data");
            so3 = (SimpleObject3)value;
            Assert.NotNull(so3);
            Assert.Equal("", so3.c);

            address.Query = "c=null";
            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject3), out value), "Expected 'true' reading valid data");
            so3 = (SimpleObject3)value;
            Assert.NotNull(so3);
            Assert.Equal("null", so3.c);
        }
示例#6
0
    protected void page_command(object sender, CommandEventArgs e)
    {
        int page = 1;

        switch (e.CommandName) {

            case "first": page = 1; break;
            case "prev": page = Convert.ToInt32(Request.QueryString["page"]) - 1; break;
            case "page": page = Convert.ToInt32(e.CommandArgument); break;
            case "next": page = Convert.ToInt32(Request.QueryString["page"]) + 1; break;
            case "last":
                int count = global::User.FindUsers(Request.QueryString["name"]).Count;
                page = Convert.ToInt32(Math.Ceiling((double)(count - 1) / (double)RESULTS));
                break;
        }

        UriBuilder u = new UriBuilder(Request.Url);
        NameValueCollection nv = new NameValueCollection(Request.QueryString);

        nv["page"] = page.ToString();

        StringBuilder sb = new StringBuilder();
        foreach (string k in nv.Keys)
            sb.AppendFormat("&{0}={1}", k, nv[k]);

        u.Query = sb.ToString();

        Response.Redirect(u.Uri.ToString());
    }
示例#7
0
    static void Main(string[] args)
    {
        Console.WriteLine("---------------------------------------------------------");
        Console.WriteLine("Preparing nServer...");

        // prepare primary endpoint URL
        UriBuilder uriBuilder = new UriBuilder("http",
            Server.Configurations.Server.Host,
            Server.Configurations.Server.Port);
        Console.WriteLine(String.Format("Setting up to listen for commands on {0}...", uriBuilder.Uri.ToString()));

        // register controllers
        Console.WriteLine("Registering all controllers...");
        Server.Controllers.ControllerManager.RegisterAllControllers();

        // start it up
        nServer server = new nServer(uriBuilder.Uri);
        nServer.CurrentInstance = server;
        server.IncomingRequest += RequestHandler.HandleIncomingRequest;
        server.Start();

        // ping to test it's alive and ready
        Console.WriteLine("Pinging to confirm success...");
        uriBuilder.Path = "server/ping";
        WebRequest request = WebRequest.Create(uriBuilder.Uri);
        WebResponse response = request.GetResponse();
        response.Close();

        Console.WriteLine("nServer ready to accept requests...");
        Console.WriteLine("---------------------------------------------------------");
    }
 /// <summary>
 /// Gets the assembly's location, i.e. containing directory.
 /// </summary>
 /// <param name="assembly">The assembly whose location to return.</param>
 /// <returns><see cref="System.String" /> representing the assembly location.</returns>
 public static string GetCodeBaseDirectory(this Assembly assembly)
 {
     string codeBase = Assembly.GetExecutingAssembly().CodeBase;
     UriBuilder uri = new UriBuilder(codeBase);
     string path = Uri.UnescapeDataString(uri.Path);
     return Path.GetDirectoryName(path);
 }
示例#9
0
        /// <summary>
        /// Start the Uri with the base uri
        /// </summary>
        /// <param name="etsyContext">the etsy context</param>
        /// <returns>the Uri builder</returns>
        public static UriBuilder Start(EtsyContext etsyContext)
        {
            UriBuilder instance = new UriBuilder(etsyContext);
            instance.Append(etsyContext.BaseUrl);

            return instance;
        }
示例#10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!YZAuthHelper.IsAuthenticated)
        {

            FormsAuthentication.RedirectToLoginPage();
            return;
        }
        UriBuilder uriBuilder = new UriBuilder(this.Request.Url);

        string host = this.Request.Headers["host"];
        if (!String.IsNullOrEmpty(host))
        {
            int index = host.LastIndexOf(':');
            if (index != -1)
            {
                string port = host.Substring(index + 1);
                uriBuilder.Port = Int32.Parse(port);
            }
        }
        Uri uri = uriBuilder.Uri;
        string url = uri.GetLeftPart(UriPartial.Authority);

        string virtualPath = HttpRuntime.AppDomainAppVirtualPath;
        if (virtualPath == "/")
            virtualPath = String.Empty;

        url = url + virtualPath + "/";
        string jscode = String.Format("var rootUrl='{0}';\n var userAccount = '{1}';", url, YZAuthHelper.LoginUserAccount);
        HtmlGenericControl js = new HtmlGenericControl("script");
        js.Attributes["type"] = "text/javascript";
        js.InnerHtml = jscode;
           // this.Page.Header.Controls.AddAt(0, js);
    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var httpsPort = Convert.ToInt32(ConfigurationManager.AppSettings["httpsPort"]);
            var httpPort = Convert.ToInt32(ConfigurationManager.AppSettings["httpPort"]);
            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;

            if (httpsPort > 0 && RequireSecure)
            {
                string url = null;
                if (httpsPort > 0)
                {
                    url = "https://" + request.Url.Host + request.RawUrl;

                    if (httpsPort != 443)
                    {
                        var builder = new UriBuilder(url) { Port = httpsPort };
                        url = builder.Uri.ToString();
                    }
                }
                if (httpsPort != request.Url.Port)
                {
                    filterContext.Result = new RedirectResult(url);
                }
            }
            // se for uma conexao segura e não está requerendo um SSL, retira o ssl e volta para http.
            else if (filterContext.HttpContext.Request.IsSecureConnection && !RequireSecure)
            {
                filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.Url.ToString().Replace("https:", "http:").Replace(httpsPort.ToString(), httpPort.ToString()));
                filterContext.Result.ExecuteResult(filterContext);
            }
            base.OnActionExecuting(filterContext);
    }
 public void UriBuilder_Ctor_NullParameter_ThrowsArgumentException()
 {
     Assert.Throws<ArgumentNullException>(() =>
    {
        UriBuilder builder = new UriBuilder((Uri)null);
    });
 }
示例#13
0
 // Originally: TcpChannelListener.FixIpv6Hostname
 private static void FixIpv6Hostname(UriBuilder uriBuilder, Uri originalUri)
 {
     if (originalUri.HostNameType == UriHostNameType.IPv6)
     {
         string ipv6Host = originalUri.DnsSafeHost;
         uriBuilder.Host = string.Concat("[", ipv6Host, "]");
     }
 }
示例#14
0
    public static string CurrentDirectory()
    {
        var assembly = typeof(AssemblyLocation).Assembly;
        var uri = new UriBuilder(assembly.CodeBase);
        var path = Uri.UnescapeDataString(uri.Path);

        return Path.GetDirectoryName(path);
    }
 static AssemblyLocation()
 {
     var assembly = typeof(AssemblyLocation).Assembly;
     var uri = new UriBuilder(assembly.CodeBase);
     var currentAssemblyPath = Uri.UnescapeDataString(uri.Path);
     CurrentDirectory = Path.GetDirectoryName(currentAssemblyPath);
     ExeFileName = Path.GetFileNameWithoutExtension(currentAssemblyPath);
 }
示例#16
0
 public static string FullLocalPath(this Assembly assembly)
 {
     var codeBase = assembly.CodeBase;
     var uri = new UriBuilder(codeBase);
     var root = Uri.UnescapeDataString(uri.Path);
     root = root.Replace("/", "\\");
     return root;
 }
示例#17
0
    public static string CurrentDirectory()
    {
        //Use codebase because location fails for unit tests.
        var assembly = typeof(AssemblyLocation).Assembly;
        var uri = new UriBuilder(assembly.CodeBase);
        var path = Uri.UnescapeDataString(uri.Path);

        return Path.GetDirectoryName(path);
    }
示例#18
0
 protected void Page_PreInit(object sender, EventArgs e)
 {
     if (Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
     {
         UriBuilder builder = new UriBuilder(Request.Url);
         builder.Host = Request.Url.Host.Substring(Request.Url.Host.IndexOf("www.") + 4);
         Response.Redirect(builder.ToString(), true);
     }
 }
示例#19
0
 public void UriBuilder_ChangeScheme_Refreshed()
 {
     UriBuilder builder = new UriBuilder(s_starterUri);
     Assert.Equal<String>(s_starterUri.Scheme, builder.Scheme);
     Assert.Equal<String>(s_starterUri.Scheme, builder.Uri.Scheme);
     String newValue = "newvalue";
     builder.Scheme = newValue;
     Assert.Equal<String>(newValue, builder.Scheme);
     Assert.Equal<String>(newValue, builder.Uri.Scheme);
 }
示例#20
0
 public void UriBuilder_ChangeHost_Refreshed()
 {
     UriBuilder builder = new UriBuilder(s_starterUri);
     Assert.Equal<String>(s_starterUri.Host, builder.Host);
     Assert.Equal<String>(s_starterUri.Host, builder.Uri.Host);
     String newValue = "newvalue";
     builder.Host = newValue;
     Assert.Equal<String>(newValue, builder.Host);
     Assert.Equal<String>(newValue, builder.Uri.Host);
 }
示例#21
0
 public void UriBuilder_ChangePassword_Refreshed()
 {
     UriBuilder builder = new UriBuilder(s_starterUri);
     Assert.Equal<String>(s_starterUri.UserInfo, builder.UserName + ":" + builder.Password);
     Assert.Equal<String>(s_starterUri.UserInfo, builder.Uri.UserInfo);
     String newValue = "newvalue";
     builder.Password = newValue;
     Assert.Equal<String>(newValue, builder.Password);
     Assert.Equal<String>(builder.UserName + ":" + newValue, builder.Uri.UserInfo);
 }
示例#22
0
 public void UriBuilder_ChangePort_Refreshed()
 {
     UriBuilder builder = new UriBuilder(s_starterUri);
     Assert.Equal<int>(s_starterUri.Port, builder.Port);
     Assert.Equal<int>(s_starterUri.Port, builder.Uri.Port);
     int newValue = 1010;
     builder.Port = newValue;
     Assert.Equal<int>(newValue, builder.Port);
     Assert.Equal<int>(newValue, builder.Uri.Port);
 }
示例#23
0
 public void UriBuilder_ChangePath_Refreshed()
 {
     UriBuilder builder = new UriBuilder(s_starterUri);
     Assert.Equal<String>(s_starterUri.AbsolutePath, builder.Path);
     Assert.Equal<String>(s_starterUri.AbsolutePath, builder.Uri.AbsolutePath);
     String newValue = "/newvalue";
     builder.Path = newValue;
     Assert.Equal<String>(newValue, builder.Path);
     Assert.Equal<String>(newValue, builder.Uri.AbsolutePath);
 }
示例#24
0
	protected void IdentityEndpoint20_NormalizeUri(object sender, IdentityEndpointNormalizationEventArgs e) {
		// This sample Provider has a custom policy for normalizing URIs, which is that the whole
		// path of the URI be lowercase except for the first letter of the username.
		UriBuilder normalized = new UriBuilder(e.UserSuppliedIdentifier);
		string username = Request.QueryString["username"].TrimEnd('/').ToLowerInvariant();
		username = username.Substring(0, 1).ToUpperInvariant() + username.Substring(1);
		normalized.Path = "/user/" + username;
		normalized.Scheme = "http"; // for a real Provider, this should be HTTPS if supported.
		e.NormalizedIdentifier = normalized.Uri;
	}
示例#25
0
    public static string CurrentDirectory()
    {
        //Use codebase because location fails for unit tests.
        // in unt tests returns a path like
        // C:\Users\Simon\AppData\Local\Temp\o2ehfpqw.x01\Fody.Tests\assembly\dl3\0e7cab25\21728d4f_da04cd01\Fody.dll
        // And that path contains only Fody.dll and no other assemblies
        var assembly = typeof(AssemblyLocation).Assembly;
        var uri = new UriBuilder(assembly.CodeBase);
        var path = Uri.UnescapeDataString(uri.Path);

        return Path.GetDirectoryName(path);
    }
示例#26
0
        private static Uri CreateBaseComparableUri(Uri uri)
        {
            Debug.Assert(uri != null, "uri != null");

            uri = new Uri(uri.OriginalString.ToUpper(CultureInfo.InvariantCulture), UriKind.RelativeOrAbsolute);

            UriBuilder builder = new UriBuilder(uri);
            builder.Host = "h";
            builder.Port = 80;
            builder.Scheme = "http";
            return builder.Uri;
        }
示例#27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string remoteIP = Request.ServerVariables["remote_addr"];
        string allowedIP = System.Configuration.ConfigurationSettings.AppSettings["AdminIPAddress"];

        if (remoteIP != allowedIP)
        {
            LocalConfiguration.Visible = false;
        }

        PageTitle.Text = ConfigurationManager.AppSettings["network"] + " Web Service";
        Page.Title = PageTitle.Text;

        // use UriBuilder to make a valid URL
        UriBuilder wsdl = new UriBuilder();
        wsdl.Scheme = Request.Url.Scheme;
        wsdl.Host = Request.Url.DnsSafeHost;
        /* UriBuilder is not aware of standard ports
         * if a port is added, then it will display
         * Co-PI say port :80 is not needed.
         * so below handles standard port cases
         */
        if (Request.Url.Scheme =="http") {
            if ( !(Request.Url.Port==80) ) wsdl.Port = Request.Url.Port;
        }
        else if (Request.Url.Scheme == "https")
        {
           if ( !(Request.Url.Port == 443)) wsdl.Port = Request.Url.Port;
        } else
        {
            wsdl.Port = Request.Url.Port;
        }

        serviceLocation.NavigateUrl = "~/" + ConfigurationManager.AppSettings["asmxPage"];
           wsdl.Path = serviceLocation.ResolveUrl(ConfigurationManager.AppSettings["asmxPage"]) ;
         serviceLocation.Text = wsdl.ToString();

         serviceLocation_1_1.NavigateUrl = "~/" + ConfigurationManager.AppSettings["asmxPage_1_1"];
        wsdl.Path = serviceLocation.ResolveUrl( serviceLocation_1_1.NavigateUrl);
        serviceLocation_1_1.Text = wsdl.ToString();

          Boolean OdGetValues = Boolean.Parse(ConfigurationManager.AppSettings["UseODForValues"]);
        if (!OdGetValues)
          {
          //HyperLinkGetValuesObject.Enabled = false;
          //HyperLinkGetValuesObject.Text = HyperLinkGetValuesObject.Text + " External or not implemented";
          //HyperLinkGetValues.Enabled = false;
          //HyperLinkGetValues.Text = HyperLinkGetValues.Text + " External or not implemented";
          }
        wsversion.Text = String.Format("Compile Date (UTC) {0}", AssemblyVersion);
    }
		WebProxyData ReadEnvVariables ()
		{
			string address = Environment.GetEnvironmentVariable ("http_proxy") ?? Environment.GetEnvironmentVariable ("HTTP_PROXY");

			if (address != null) {
				try {
					if (!address.StartsWith ("http://"))
						address = "http://" + address;

					Uri uri = new Uri (address);
					IPAddress ip;
					
					if (IPAddress.TryParse (uri.Host, out ip)) {
						if (IPAddress.Any.Equals (ip)) {
							UriBuilder builder = new UriBuilder (uri);
							builder.Host = "127.0.0.1";
							uri = builder.Uri;
						} else if (IPAddress.IPv6Any.Equals (ip)) {
							UriBuilder builder = new UriBuilder (uri);
							builder.Host = "[::1]";
							uri = builder.Uri;
						}
					}

					bool bBypassOnLocal = false;
					ArrayList al = new ArrayList ();
					string bypass = Environment.GetEnvironmentVariable ("no_proxy") ?? Environment.GetEnvironmentVariable ("NO_PROXY");
					
					if (bypass != null) {
						string[] bypassList = bypass.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
					
						foreach (string str in bypassList) {
							if (str != "*.local")
								al.Add (str);
							else
								bBypassOnLocal = true;
						}
					}

					return new WebProxyData {
						proxyAddress = uri,
						bypassOnLocal = bBypassOnLocal,
						bypassList = CreateBypassList (al)
					};
				} catch (UriFormatException) {
				}
			}

			return null;
		}
示例#29
0
    public static string CurrentDirectory()
    {
        //Use codebase because location fails for unit tests.
        var assembly = typeof(AssemblyLocation).Assembly;
        var uri = new UriBuilder(string.IsNullOrEmpty(assembly.CodeBase) ? assembly.Location : assembly.CodeBase);
        if (uri.ToString().Contains("#"))
        {
            throw new NotSupportedException("'#' character in path is not supported while building projects containing Fody.");
        }

        var path = Uri.UnescapeDataString(uri.Path);

        return Path.GetDirectoryName(path);
    }
示例#30
0
 public Global()
 {
     this.BeginRequest += delegate(Object sender, EventArgs e)
         {
             if (!this.Request.IsSecureConnection && Consts.URL_RequireSSL)
             {
                 UriBuilder secureLocation = new UriBuilder(Request.Url);
                 if (-1 != secureLocation.Port || 443 != Consts.URL_SecurePort)
                     secureLocation.Port = Consts.URL_SecurePort;
                 secureLocation.Scheme = "https";
                 Response.Redirect(secureLocation.Uri.ToString(), true);
             }
         };
 }
        public static IApplicationBuilder UseGrpcRegisterService(this IApplicationBuilder app, RpcServiceDiscoveryOptions serviceDiscoveryOption)
        {
            var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ??
                                      throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime));

            var serviceDiscovery = app.ApplicationServices.GetRequiredService <IServiceDiscovery>() ??
                                   throw new ArgumentException("Missing Dependency", nameof(IServiceDiscovery));

            if (string.IsNullOrEmpty(serviceDiscoveryOption.ServiceName))
            {
                throw new ArgumentException("service name must be configure", nameof(serviceDiscoveryOption.ServiceName));
            }

            IEnumerable <Uri> addresses = null;

            if (serviceDiscoveryOption.Endpoints != null && serviceDiscoveryOption.Endpoints.Length > 0)
            {
                addresses = serviceDiscoveryOption.Endpoints.Select(p => new Uri(p));
            }
            else
            {
                var features = app.Properties["server.Features"] as FeatureCollection;
                addresses = features.Get <IServerAddressesFeature>().Addresses.Select(p => new Uri(p)).ToArray();
            }
            // 以默认第一个地址开启rpc服务
            var grpcServer = InitializeGrpcServer(addresses.FirstOrDefault());

            foreach (var address in addresses)
            {
                UriBuilder myUri = new UriBuilder(address.Scheme, address.Host, address.Port);

                var serviceID = GetRpcServiceId(serviceDiscoveryOption.ServiceName, myUri.Uri);

                Uri healthCheck = null;
                if (!string.IsNullOrEmpty(serviceDiscoveryOption.HealthCheckTemplate))
                {
                    healthCheck = new Uri(myUri.Uri, serviceDiscoveryOption.HealthCheckTemplate);
                }

                var registryInformation = serviceDiscovery.RegisterServiceAsync(serviceDiscoveryOption.ServiceName,
                                                                                serviceDiscoveryOption.Version,
                                                                                myUri.Uri,
                                                                                healthCheckUri: healthCheck,
                                                                                tags: new[] { $"urlprefix-/{serviceDiscoveryOption.ServiceName}" }).Result;

                applicationLifetime.ApplicationStopping.Register(() =>
                {
                    try
                    {
                        grpcServer.ShutdownAsync().Wait();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"grpcServer had shutown {ex}");
                    }
                    serviceDiscovery.DeregisterServiceAsync(registryInformation.Id);
                });
            }

            return(app);
        }
示例#32
0
        public async Task DeleteAssignment(string validationRuleId, string assignmentId)
        {
            UriBuilder uriBuilder = this.client.GetUriBuilder(string.Format("/validation-rules/{0}/assignments/{1}", Uri.EscapeDataString(validationRuleId), Uri.EscapeDataString(assignmentId)));

            await this.client.DoDeleteRequest(uriBuilder.Uri).ConfigureAwait(false);
        }
示例#33
0
 public void Constructor_5()
 {
     b = new UriBuilder("http", "www.ximian.com", 80, "foo/bar/index.html", "#extras");
 }
示例#34
0
        private static void FillRequisites(string login)
        {
            string uri = UriBuilder.GetFillRequisitesByLoginUrl(login);

            new TesterClient(uri).FillRequisites();
        }
示例#35
0
        public async Task <DataModel.BusinessValidationRuleList> List(DataModel.Queries.BusinessValidationRuleFilter filter)
        {
            UriBuilder uriBuilder = UriBuilderExtension.WithQuery(this.client.GetUriBuilder("/validation-rules/"), filter);

            return(await this.client.DoGetRequest <DataModel.BusinessValidationRuleList>(uriBuilder.Uri).ConfigureAwait(false));
        }
示例#36
0
        public bool FTP(string server, int port, bool passive, string username, string password, string filename, int counter, string path, out string error, bool rename, bool useSftp, byte[] contents)
        {
            bool failed = false;

            if (contents == null)
            {
                var fi = new FileInfo(path);
                contents = Helper.ReadBytesWithRetry(fi);
            }

            if (useSftp)
            {
                return(Sftp(server, port, username, password, filename, counter, contents, out error, rename));
            }
            try
            {
                var urib = new UriBuilder(server);
                urib.Port = port;

                var target = urib.ToString();
                int i      = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                {
                    filename += ".tmp";
                }

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                //try uploading
                //directory tree
                var           filepath = filename.Trim('/').Split('/');
                var           rpath    = "";
                FtpWebRequest request;
                for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                {
                    rpath              += filepath[iDir] + "/";
                    request             = (FtpWebRequest)WebRequest.Create(target + rpath);
                    request.Credentials = new NetworkCredential(username, password);
                    request.Method      = WebRequestMethods.Ftp.MakeDirectory;
                    try { request.GetResponse(); }
                    catch
                    {
                        //directory exists
                    }
                }

                request             = (FtpWebRequest)WebRequest.Create(target + filename);
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive  = passive;
                //request.UseBinary = true;
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.ContentLength = contents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(contents, 0, contents.Length);
                requestStream.Close();

                var response = (FtpWebResponse)request.GetResponse();
                if (response.StatusCode != FtpStatusCode.ClosingData)
                {
                    Logger.LogError("FTP Failed: " + response.StatusDescription, "FTP");
                    failed = true;
                }

                response.Close();

                if (rename && !failed)
                {
                    //delete existing
                    request             = (FtpWebRequest)WebRequest.Create(target + filename.Substring(0, filename.Length - 4));
                    request.Credentials = new NetworkCredential(username, password);
                    request.UsePassive  = passive;
                    //request.UseBinary = true;
                    request.Method = WebRequestMethods.Ftp.DeleteFile;
                    filename       = "/" + filename;

                    try
                    {
                        response = (FtpWebResponse)request.GetResponse();
                        if (response.StatusCode != FtpStatusCode.ActionNotTakenFileUnavailable &&
                            response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            Logger.LogError("FTP Delete Failed: " + response.StatusDescription, "FTP");
                            failed = true;
                        }

                        response.Close();
                    }
                    catch
                    {
                        //Logger.LogException(ex, "FTP");
                        //ignore
                    }

                    //rename file
                    if (!failed)
                    {
                        request             = (FtpWebRequest)WebRequest.Create(target + filename);
                        request.Credentials = new NetworkCredential(username, password);
                        request.UsePassive  = passive;
                        //request.UseBinary = true;
                        request.Method = WebRequestMethods.Ftp.Rename;
                        filename       = "/" + filename;

                        request.RenameTo = filename.Substring(0, filename.Length - 4);

                        response = (FtpWebResponse)request.GetResponse();
                        if (response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            Logger.LogError("FTP Rename Failed: " + response.StatusDescription, "FTP");
                            failed = true;
                        }
                        response.Close();
                    }
                }
                if (!failed)
                {
                    Logger.LogMessage("FTP'd " + filename + " to " + server + ":" + port, "FTP");
                }
                error = failed ? "FTP Failed. Check Log" : "";
            }
            catch (Exception ex)
            {
                error  = ex.Message;
                failed = true;
            }
            return(!failed);
        }
示例#37
0
        public object Get(ShareGetRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/share GET url='{0}'", request.url));

            var AppSettings = System.Configuration.ConfigurationManager.AppSettings;

            var redirect = new UriBuilder(context.BaseUrl);

            redirect.Path = "geobrowser";
            string redirectUrl = redirect.Uri.AbsoluteUri + (!string.IsNullOrEmpty(request.id) ? "/?id=" + request.id : "/") + "#!";

            var   pathUrl = new Uri(request.url).LocalPath.Replace(new Uri(context.BaseUrl).LocalPath, "");
            Match match   = Regex.Match(pathUrl, @"(\/?.*)search(\/?.*)");

            if (match.Success)
            {
                var resultType = match.Groups[1].Value.Trim('/');
                if (resultType.Equals(EntityType.GetEntityType(typeof(Series)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(Series)).Keyword;
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(DataPackage)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(DataPackage)).Keyword;
                }
                else if (resultType.Contains(EntityType.GetEntityType(typeof(DataPackage)).Keyword))
                {
                    redirectUrl += "resultType=" + "data";//in this case it is a search (over a data package) so we use data keyword
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(WpsJob)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(WpsJob)).Keyword;
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(WpsProvider)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(WpsProvider)).Keyword;
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(WpsProcessOffering)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(WpsProcessOffering)).Keyword;
                }
                else
                {
                    if (CatalogueFactory.IsCatalogUrl(new Uri(request.url)) || request.url.StartsWith(AppSettings["RecastBaseUrl"]))
                    {
                        redirectUrl += "resultType=" + "data";
                    }
                    else
                    {
                        try {
                            var settings = MasterCatalogue.OpenSearchFactorySettings;
                            var os       = new GenericOpenSearchable(new OpenSearchUrl(request.url), settings);
                            redirectUrl += "resultType=" + "data";
                        } catch (Exception) {
                            redirectUrl += "resultType=" + "na";
                        }
                    }
                }
                redirectUrl += "&url=" + HttpUtility.UrlEncode(request.url);
            }
            else
            {
                context.LogError(this, "Wrong format shared url");
                throw new Exception("Wrong format shared url");
            }

            var        keyword    = match.Groups[1].Value.StartsWith("/") ? match.Groups[1].Value.Substring(1) : match.Groups[1].Value;
            EntityType entityType = EntityType.GetEntityTypeFromKeyword(keyword);

            context.Close();

            return(new HttpResult()
            {
                StatusCode = System.Net.HttpStatusCode.Redirect, Headers = { { HttpHeaders.Location, redirectUrl } }
            });
        }
示例#38
0
文件: HTTP.cs 项目: yunhuios/xenadmin
        /// <summary>
        /// Build a URI from a hostname, a path, and some query arguments
        /// </summary>
        /// <param name="args">An even-length array, alternating argument names and values</param>
        /// <returns></returns>
        public static Uri BuildUri(string hostname, string path, params object[] args)
        {
            // The last argument may be an object[] in its own right, in which case we need
            // to flatten the array.
            List <object> flatargs = new List <object>();

            foreach (object arg in args)
            {
                if (arg is IEnumerable <object> )
                {
                    flatargs.AddRange((IEnumerable <object>)arg);
                }
                else
                {
                    flatargs.Add(arg);
                }
            }

            UriBuilder uri = new UriBuilder();

            uri.Scheme = "https";
            uri.Port   = DEFAULT_HTTPS_PORT;
            uri.Host   = hostname;
            uri.Path   = path;

            StringBuilder query = new StringBuilder();

            for (int i = 0; i < flatargs.Count - 1; i += 2)
            {
                string kv;

                // If the argument is null, don't include it in the URL
                if (flatargs[i + 1] == null)
                {
                    continue;
                }

                // bools are special because some xapi calls use presence/absence and some
                // use "b=true" (not "True") and "b=false". But all accept "b=true" or absent.
                if (flatargs[i + 1] is bool)
                {
                    if (!((bool)flatargs[i + 1]))
                    {
                        continue;
                    }
                    kv = flatargs[i] + "=true";
                }
                else
                {
                    kv = flatargs[i] + "=" + Uri.EscapeDataString(flatargs[i + 1].ToString());
                }

                if (query.Length != 0)
                {
                    query.Append('&');
                }
                query.Append(kv);
            }
            uri.Query = query.ToString();

            return(uri.Uri);
        }
        public async Task CreateUpdateReset()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var intialPortalDelegationSettings = await testBase.client.DelegationSettings.GetAsync(
                    testBase.rgName,
                    testBase.serviceName);

                try
                {
                    string delegationServer = TestUtilities.GenerateName("delegationServer");
                    string urlParameter     = new UriBuilder("https", delegationServer, 443).Uri.ToString();

                    var portalDelegationSettingsParams = new PortalDelegationSettings()
                    {
                        Subscriptions    = new SubscriptionsDelegationSettingsProperties(true),
                        UserRegistration = new RegistrationDelegationSettingsProperties(true),
                        Url           = urlParameter,
                        ValidationKey = PortalDelegationSettings.GenerateValidationKey()
                    };
                    var portalDelegationSettings = testBase.client.DelegationSettings.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        portalDelegationSettingsParams);
                    Assert.NotNull(portalDelegationSettings);
                    Assert.Equal(urlParameter, portalDelegationSettings.Url);
                    // validation key is generated brand new on playback mode and hence validation fails
                    //Assert.Equal(portalDelegationSettingsParams.ValidationKey, portalDelegationSettings.ValidationKey);
                    Assert.True(portalDelegationSettings.UserRegistration.Enabled);
                    Assert.True(portalDelegationSettings.Subscriptions.Enabled);

                    // check settings
                    var delegationsTag = await testBase.client.DelegationSettings.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(delegationsTag);
                    Assert.NotNull(delegationsTag.ETag);

                    // update the delegation settings
                    portalDelegationSettings.Subscriptions.Enabled    = false;
                    portalDelegationSettings.UserRegistration.Enabled = false;
                    portalDelegationSettings.Url           = null;
                    portalDelegationSettings.ValidationKey = null;

                    await testBase.client.DelegationSettings.UpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        portalDelegationSettings,
                        delegationsTag.ETag);

                    // get the delegation settings
                    portalDelegationSettings = await testBase.client.DelegationSettings.GetAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(portalDelegationSettings);
                    Assert.Null(portalDelegationSettings.Url);
                    Assert.Null(portalDelegationSettings.ValidationKey);
                    Assert.False(portalDelegationSettings.UserRegistration.Enabled);
                    Assert.False(portalDelegationSettings.Subscriptions.Enabled);
                }
                finally
                {
                    // due to bug in the api
                    intialPortalDelegationSettings.ValidationKey = null;
                    testBase.client.DelegationSettings.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        intialPortalDelegationSettings,
                        "*");
                }
            }
        }
示例#40
0
        public async Task <IActionResult> PayButtonHandle([FromForm] PayButtonViewModel model, CancellationToken cancellationToken)
        {
            var store = await _StoreRepository.FindStore(model.StoreId);

            if (store == null)
            {
                ModelState.AddModelError("Store", "Invalid store");
            }
            else
            {
                var storeBlob = store.GetStoreBlob();
                if (!storeBlob.AnyoneCanInvoice)
                {
                    ModelState.AddModelError("Store", "Store has not enabled Pay Button");
                }
            }

            if (model == null || (model.Price is decimal v ? v <= 0 : false))
            {
                ModelState.AddModelError("Price", "Price must be greater than 0");
            }

            if (!ModelState.IsValid)
            {
                return(View());
            }

            DataWrapper <InvoiceResponse> invoice = null;

            try
            {
                invoice = await _InvoiceController.CreateInvoiceCore(new BitpayCreateInvoiceRequest()
                {
                    Price                = model.Price,
                    Currency             = model.Currency,
                    ItemDesc             = model.CheckoutDesc,
                    OrderId              = model.OrderId,
                    NotificationEmail    = model.NotifyEmail,
                    NotificationURL      = model.ServerIpn,
                    RedirectURL          = model.BrowserRedirect,
                    FullNotifications    = true,
                    DefaultPaymentMethod = model.DefaultPaymentMethod
                }, store, HttpContext.Request.GetAbsoluteRoot(), cancellationToken : cancellationToken);
            }
            catch (BitpayHttpException e)
            {
                ModelState.AddModelError("Store", e.Message);
                if (model.JsonResponse)
                {
                    return(BadRequest(ModelState));
                }

                return(View());
            }

            if (model.JsonResponse)
            {
                return(Json(new
                {
                    InvoiceId = invoice.Data.Id,
                    InvoiceUrl = invoice.Data.Url
                }));
            }

            if (string.IsNullOrEmpty(model.CheckoutQueryString))
            {
                return(Redirect(invoice.Data.Url));
            }

            var additionalParamValues = HttpUtility.ParseQueryString(model.CheckoutQueryString);
            var uriBuilder            = new UriBuilder(invoice.Data.Url);
            var paramValues           = HttpUtility.ParseQueryString(uriBuilder.Query);

            paramValues.Add(additionalParamValues);
            uriBuilder.Query = paramValues.ToString();
            return(Redirect(uriBuilder.Uri.AbsoluteUri));
        }
        public async System.Threading.Tasks.Task <ICustomActivityResult> Execute()
        {
            HttpClient client = new HttpClient();

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            UriBuilder UriBuilder = new UriBuilder(endPoint);

            UriBuilder.Path  = "/santaba/rest" + uriBuilderPath;
            UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray);
            HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString());

            string data = postData;

            if (string.IsNullOrEmpty(postData) == false)
            {
                if (omitJsonEmptyorNull)
                {
                    data = AyehuHelper.omitJsonEmptyorNull(postData);
                }
                myHttpRequestMessage.Content = new StringContent(data, Encoding.UTF8, contentType);
            }

            var epoch           = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
            var authHeaderValue = string.Format("LMv1 {0}:{1}:{2}", accessid, GenerateSignature(epoch, httpMethod, data, uriBuilderPath, password1), epoch);

            client.DefaultRequestHeaders.Add("Authorization", authHeaderValue);
            client.DefaultRequestHeaders.Add("X-Version", "2");

            HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result;

            switch (response.StatusCode)
            {
            case HttpStatusCode.NoContent:
            case HttpStatusCode.Created:
            case HttpStatusCode.Accepted:
            case HttpStatusCode.OK:
            {
                if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
                {
                    return(this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath));
                }
                else
                {
                    return(this.GenerateActivityResult("Success"));
                }
            }

            default:
            {
                if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
                {
                    throw new Exception(response.Content.ReadAsStringAsync().Result);
                }
                else if (string.IsNullOrEmpty(response.ReasonPhrase) == false)
                {
                    throw new Exception(response.ReasonPhrase);
                }
                else
                {
                    throw new Exception(response.StatusCode.ToString());
                }
            }
            }
        }
        public async System.Threading.Tasks.Task <ICustomActivityResult> Execute()
        {
            HttpClient client = new HttpClient();

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            UriBuilder UriBuilder = new UriBuilder(endPoint);

            UriBuilder.Path  = uriBuilderPath;
            UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray);
            HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString());

            if (contentType == "application/x-www-form-urlencoded")
            {
                myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData);
            }
            else
            if (string.IsNullOrEmpty(postData) == false)
            {
                if (omitJsonEmptyorNull)
                {
                    myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json");
                }
                else
                {
                    myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType);
                }
            }


            foreach (KeyValuePair <string, string> headeritem in headers)
            {
                client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value);
            }

            HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result;

            switch (response.StatusCode)
            {
            case HttpStatusCode.NoContent:
            case HttpStatusCode.Created:
            case HttpStatusCode.Accepted:
            case HttpStatusCode.OK:
            {
                if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
                {
                    return(this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath));
                }
                else
                {
                    return(this.GenerateActivityResult("Success"));
                }
            }

            default:
            {
                if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
                {
                    throw new Exception(response.Content.ReadAsStringAsync().Result);
                }
                else if (string.IsNullOrEmpty(response.ReasonPhrase) == false)
                {
                    throw new Exception(response.ReasonPhrase);
                }
                else
                {
                    throw new Exception(response.StatusCode.ToString());
                }
            }
            }
        }
        /// <summary>
        /// Checks if it is necessary to redirect to SharePoint for user to authenticate.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
        /// <returns>Redirection status.</returns>
        public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            redirectUrl = null;

            if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
            {
                return(RedirectionStatus.Ok);
            }

            const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";

            if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
            {
                return(RedirectionStatus.CanNotRedirect);
            }

            Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);

            if (spHostUrl == null)
            {
                return(RedirectionStatus.CanNotRedirect);
            }

            if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
            {
                return(RedirectionStatus.CanNotRedirect);
            }

            Uri requestUrl = httpContext.Request.Url;

            var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);

            // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
            queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
            queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
            queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
            queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
            queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);

            // Adds SPHasRedirectedToSharePoint=1.
            queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");

            UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);

            returnUrlBuilder.Query = queryNameValueCollection.ToString();

            // Inserts StandardTokens.
            const string StandardTokens  = "{StandardTokens}";
            string       returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;

            returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");

            // Constructs redirect url.
            string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));

            redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);

            return(RedirectionStatus.ShouldRedirect);
        }
示例#44
0
        private static void IncludeInStatistics(string login)
        {
            string uri = UriBuilder.GetChangeStatisticsFlagByLoginUrl(login, true);

            new TesterClient(uri).ChangeStatisticsFlag();
        }
示例#45
0
        public async Task <DataModel.BusinessValidationRuleAssignmentList> ListAssignments(string validationRuleId, DataModel.Queries.BusinessValidationRuleAssignmentFilter filter)
        {
            UriBuilder uriBuilder = UriBuilderExtension.WithQuery(this.client.GetUriBuilder(string.Format("/validation-rules/{0}/assignments", Uri.EscapeDataString(validationRuleId))), filter);

            return(await this.client.DoGetRequest <DataModel.BusinessValidationRuleAssignmentList>(uriBuilder.Uri).ConfigureAwait(false));
        }
示例#46
0
        public void Constructor_StringStringInt()
        {
            UriBuilder ub = new UriBuilder("http", "www.mono-project.com", 80);

            Assert.AreEqual("http://www.mono-project.com/", ub.Uri.AbsoluteUri, "Uri.AbsoluteUri");
        }
示例#47
0
        private static void ExcludeFromStatistics(string login)
        {
            string uri = UriBuilder.GetChangeStatisticsFlagByLoginUrl(login, false);

            new TesterClient(uri).ChangeStatisticsFlag();
        }
示例#48
0
        public async Task <IActionResult> Maintenance(MaintenanceViewModel vm, string command)
        {
            if (!ModelState.IsValid)
            {
                return(View(vm));
            }
            vm.SetConfiguredSSH(_Options.SSHSettings);
            if (command == "changedomain")
            {
                if (string.IsNullOrWhiteSpace(vm.DNSDomain))
                {
                    ModelState.AddModelError(nameof(vm.DNSDomain), $"Required field");
                    return(View(vm));
                }
                vm.DNSDomain = vm.DNSDomain.Trim().ToLowerInvariant();
                if (vm.DNSDomain.Equals(this.Request.Host.Host, StringComparison.OrdinalIgnoreCase))
                {
                    return(View(vm));
                }
                if (IPAddress.TryParse(vm.DNSDomain, out var unused))
                {
                    ModelState.AddModelError(nameof(vm.DNSDomain), $"This should be a domain name");
                    return(View(vm));
                }
                if (vm.DNSDomain.Equals(this.Request.Host.Host, StringComparison.InvariantCultureIgnoreCase))
                {
                    ModelState.AddModelError(nameof(vm.DNSDomain), $"The server is already set to use this domain");
                    return(View(vm));
                }
                var builder = new UriBuilder();
                using (var client = new HttpClient(new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                }))
                {
                    try
                    {
                        builder.Scheme = this.Request.Scheme;
                        builder.Host   = vm.DNSDomain;
                        var addresses1 = GetAddressAsync(this.Request.Host.Host);
                        var addresses2 = GetAddressAsync(vm.DNSDomain);
                        await Task.WhenAll(addresses1, addresses2);

                        var addressesSet     = addresses1.GetAwaiter().GetResult().Select(c => c.ToString()).ToHashSet();
                        var hasCommonAddress = addresses2.GetAwaiter().GetResult().Select(c => c.ToString()).Any(s => addressesSet.Contains(s));
                        if (!hasCommonAddress)
                        {
                            ModelState.AddModelError(nameof(vm.DNSDomain), $"Invalid host ({vm.DNSDomain} is not pointing to this BTCPay instance)");
                            return(View(vm));
                        }
                    }
                    catch (Exception ex)
                    {
                        var messages = new List <object>();
                        messages.Add(ex.Message);
                        if (ex.InnerException != null)
                        {
                            messages.Add(ex.InnerException.Message);
                        }
                        ModelState.AddModelError(nameof(vm.DNSDomain), $"Invalid domain ({string.Join(", ", messages.ToArray())})");
                        return(View(vm));
                    }
                }

                var error = RunSSH(vm, $"changedomain.sh {vm.DNSDomain}");
                if (error != null)
                {
                    return(error);
                }

                builder.Path  = null;
                builder.Query = null;
                StatusMessage = $"Domain name changing... the server will restart, please use \"{builder.Uri.AbsoluteUri}\"";
            }
            else if (command == "update")
            {
                var error = RunSSH(vm, $"btcpay-update.sh");
                if (error != null)
                {
                    return(error);
                }
                StatusMessage = $"The server might restart soon if an update is available...";
            }
            else
            {
                return(NotFound());
            }
            return(RedirectToAction(nameof(Maintenance)));
        }
示例#49
0
        public static void SwitchOnStock(string login)
        {
            string uri = UriBuilder.GetSwitchOnStockByLoginUrl(login);

            new TesterClient(uri).SwitchOnStock();
        }
        internal static Uri GetNextPageLink(Uri requestUri, IEnumerable <KeyValuePair <string, string> > queryParameters, int pageSize)
        {
            Contract.Assert(requestUri != null);
            Contract.Assert(queryParameters != null);
            Contract.Assert(requestUri.IsAbsoluteUri);

            StringBuilder queryBuilder = new StringBuilder();

            int nextPageSkip = pageSize;

            foreach (KeyValuePair <string, string> kvp in queryParameters)
            {
                string key   = kvp.Key;
                string value = kvp.Value;
                switch (key)
                {
                case "$top":
                    int top;
                    if (Int32.TryParse(value, out top))
                    {
                        // There is no next page if the $top query option's value is less than or equal to the page size.
                        Contract.Assert(top > pageSize);
                        // We decrease top by the pageSize because that's the number of results we're returning in the current page
                        value = (top - pageSize).ToString(CultureInfo.InvariantCulture);
                    }
                    break;

                case "$skip":
                    int skip;
                    if (Int32.TryParse(value, out skip))
                    {
                        // We increase skip by the pageSize because that's the number of results we're returning in the current page
                        nextPageSkip += skip;
                    }
                    continue;

                default:
                    break;
                }

                if (key.Length > 0 && key[0] == '$')
                {
                    // $ is a legal first character in query keys
                    key = '$' + Uri.EscapeDataString(key.Substring(1));
                }
                else
                {
                    key = Uri.EscapeDataString(key);
                }
                value = Uri.EscapeDataString(value);

                queryBuilder.Append(key);
                queryBuilder.Append('=');
                queryBuilder.Append(value);
                queryBuilder.Append('&');
            }

            queryBuilder.AppendFormat("$skip={0}", nextPageSkip);

            UriBuilder uriBuilder = new UriBuilder(requestUri)
            {
                Query = queryBuilder.ToString()
            };

            return(uriBuilder.Uri);
        }
示例#51
0
 public void GetReady()
 {
     b = new UriBuilder("http", "www.ximian.com", 80, "foo/bar/index.html");
 }
        /// <summary>
        /// Add links to Download Station
        /// </summary>
        /// <param name="links">Links to Download</param>
        /// <returns>Success?</returns>
        public static bool AddLinksToDownloadStation(List<string> links)
        {
            DownloadStation ds = null;
                                    
            try
            {
                UriBuilder uriBuilder = new UriBuilder(Properties.Settings.Default.Address);
                                
                ds = new DownloadStation(uriBuilder.Uri, Properties.Settings.Default.Username, Encoding.UTF8.GetString(Convert.FromBase64String(Properties.Settings.Default.Password)));
                         
                links.RemoveAll(str => String.IsNullOrEmpty(str.Trim()));

                Dictionary<string, List<string>> validHostLinks = new Dictionary<string, List<string>>();
                List<string> corruptedLinks = new List<string>();   
                Uri currentLink = null;
                int validHostLinkCount = 0;
                int totalLinkCount = 0;
                string balloonMsg;

                foreach (string link in links)
                {
                    try
                    {
                        currentLink = new Uri(link);
                           
                        if (!validHostLinks.ContainsKey(currentLink.Host))
                        {
                            validHostLinks.Add(currentLink.Host, new List<string>());
                        }
                            
                        validHostLinks[currentLink.Host].Add(link);
                    }
                    catch
                    {
                        corruptedLinks.Add(link);
                    }                        
                }

                if (validHostLinks.Keys.Count > 1)
                {                        
                    frmSettings.Instance.Invoke((MethodInvoker)(() =>
                    {
                        // Run on UI thread
                        frmSelectHoster.Instance.SelectHoster(validHostLinks);
                    }
                    ));
                }

                // Get total link count
                foreach (var validHostLink in validHostLinks)
                {
                    totalLinkCount += validHostLink.Value.Count;
                }


                if (validHostLinks.Count > 0)
                {
                    balloonMsg = "Adding " + totalLinkCount + " links(s) (" + (validHostLinks.Count > 1 ? validHostLinks.Count + " Hosts)" : validHostLinks.First().Key + ")");

                    Adapter.ShowBalloonTip(balloonMsg, ToolTipIcon.Info, 30000);

                    // Login to Download Station
                    if (ds.Login())
                    {

                        foreach (var validHostLink in validHostLinks)
                        {
                            validHostLinkCount += validHostLink.Value.Count;

                            List<List<string>> portions = CreateLinkPortions(validHostLink.Value);

                            foreach (List<string> partionLinks in portions)
                            {
                                // Add links to Download Station
                                SynologyRestDAL.TResult<object> result = ds.CreateTask(string.Join(",", partionLinks.ToArray()));

                                if (!result.Success)
                                {
                                    if (result.Error.Code == 406)
                                    {
                                        throw new Exception("Couldn't add link(s). You have to choose a download folder for your Download Station.");
                                    }
                                    else
                                    {
                                        throw new Exception("While adding link(s) the error code " + result.Error.Code + " occurred");
                                    }
                                }
                            }
                        }

                        balloonMsg = totalLinkCount + " link(s) added (" + (validHostLinks.Count > 1 ? validHostLinks.Count + " Hosts)" : validHostLinks.First().Key + ")");

                        if (corruptedLinks.Count > 0)
                        {
                            balloonMsg += "\r\n" + corruptedLinks.Count + " links(s) were corrupted";
                        }

                        Adapter.ShowBalloonTip(balloonMsg, ToolTipIcon.Info);
                        return true;

                    }
                    else
                    {
                        throw new Exception("Couldn't login to Download Station");
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Adapter.ShowBalloonTip(ex.Message, ToolTipIcon.Error);
                return false;
            }
            finally
            {
                if (ds != null)
                {
                    try
                    {
                        ds.Logout();
                    }
                    catch
                    {
                        // Ignore error on logout
                    }                    
                }
            }
        }
示例#53
0
 public void Constructor_RelativeUri()
 {
     Uri        relative = new Uri("../dir/subdir/file", UriKind.RelativeOrAbsolute);
     UriBuilder ub       = new UriBuilder(relative);
 }
        /// <summary>
        /// Adds a file to Download Station
        /// </summary>
        /// <param name="path">Path of file</param>
        /// <returns>Success?</returns>
        public static bool AddFileToDownloadStation(string path)
        {
            DownloadStation ds = null;
            string name = string.Empty;
            string extention = string.Empty;
            FileStream file = null;

            try
            {
                UriBuilder uriBuilder = new UriBuilder(Properties.Settings.Default.Address)
                {
                    Scheme = Uri.UriSchemeHttp
                };

                ds = new DownloadStation(uriBuilder.Uri, Properties.Settings.Default.Username, Encoding.UTF8.GetString(Convert.FromBase64String(Properties.Settings.Default.Password)));

                if (File.Exists(path))
                {
                    name = Path.GetFileName(path);

                    
                        Adapter.ShowBalloonTip("Adding " + name , ToolTipIcon.Info, 30000);

                        // Register file for download
                        string fileDownload = RegisterFileDownload(path);

                        // Login to Download Station
                        if (ds.Login())
                        {
                            // Add file to Download Station
                            SynologyRestDAL.TResult<object> result = ds.CreateTask(fileDownload);

                            if (!result.Success)
                            {
                                if (result.Error.Code == 406)
                                {
                                    throw new Exception("Couldn't add link(s). You have to choose a download folder for your Download Station.");
                                }
                                else
                                {
                                    throw new Exception("While adding " + name + " error code " + result.Error.Code + " occurred");
                                }
                            }

                            Adapter.ShowBalloonTip("Added " + name, ToolTipIcon.Info);

                            return true;
                        }
                        else
                        {
                            throw new Exception("Couldn't login to Download Station");
                        }                    
                }
                else
                {
                    Adapter.ShowBalloonTip("Couldn't find file '" + path + "'", ToolTipIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Adapter.ShowBalloonTip(ex.Message, ToolTipIcon.Error);
                return false;
            }
            finally
            {
                if (ds != null)
                {
                    ds.Logout();
                }

                if (file != null)
                {
                    file.Close();
                }
            }
        }
        public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action <WKNavigationActionPolicy> decisionHandler)
        {
            string requestUrlString = navigationAction.Request.Url.ToString();

            // If the URL has the browser:// scheme then this is a request to open an external browser
            if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase))
            {
                DispatchQueue.MainQueue.DispatchAsync(() => AuthenticationAgentUIViewController.CancelAuthentication(null, null));

                // Build the HTTPS URL for launching with an external browser
                var httpsUrlBuilder = new UriBuilder(requestUrlString)
                {
                    Scheme = Uri.UriSchemeHttps
                };
                requestUrlString = httpsUrlBuilder.Uri.AbsoluteUri;

                DispatchQueue.MainQueue.DispatchAsync(
                    () => UIApplication.SharedApplication.OpenUrl(new NSUrl(requestUrlString)));
                AuthenticationAgentUIViewController.DismissViewController(true, null);
                decisionHandler(WKNavigationActionPolicy.Cancel);
                return;
            }

            if (requestUrlString.StartsWith(AuthenticationAgentUIViewController.callback, StringComparison.OrdinalIgnoreCase) ||
                requestUrlString.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase))
            {
                AuthenticationAgentUIViewController.DismissViewController(true, () =>
                                                                          AuthenticationAgentUIViewController.callbackMethod(new AuthorizationResult(AuthorizationStatus.Success, requestUrlString)));
                decisionHandler(WKNavigationActionPolicy.Cancel);
                return;
            }

            if (requestUrlString.StartsWith(BrokerConstants.DeviceAuthChallengeRedirect, StringComparison.OrdinalIgnoreCase))
            {
                Uri    uri   = new Uri(requestUrlString);
                string query = uri.Query;
                if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase))
                {
                    query = query.Substring(1);
                }

                Dictionary <string, string> keyPair = CoreHelpers.ParseKeyValueList(query, '&', true, false, null);
                string responseHeader = DeviceAuthHelper.CreateDeviceAuthChallengeResponseAsync(keyPair).Result;

                NSMutableUrlRequest newRequest = (NSMutableUrlRequest)navigationAction.Request.MutableCopy();
                newRequest.Url = new NSUrl(keyPair["SubmitUrl"]);
                newRequest[BrokerConstants.ChallengeResponseHeader] = responseHeader;
                webView.LoadRequest(newRequest);
                decisionHandler(WKNavigationActionPolicy.Cancel);
                return;
            }

            if (!navigationAction.Request.Url.AbsoluteString.Equals(AboutBlankUri, StringComparison.OrdinalIgnoreCase) &&
                !navigationAction.Request.Url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.ErrorHttp)
                {
                    Error            = CoreErrorCodes.NonHttpsRedirectNotSupported,
                    ErrorDescription = CoreErrorMessages.NonHttpsRedirectNotSupported
                };
                AuthenticationAgentUIViewController.DismissViewController(true, () => AuthenticationAgentUIViewController.callbackMethod(result));
                decisionHandler(WKNavigationActionPolicy.Cancel);
                return;
            }
            decisionHandler(WKNavigationActionPolicy.Allow);
            return;
        }
示例#56
0
        internal Tracer(TracerSettings settings, IAgentWriter agentWriter, ISampler sampler, IScopeManager scopeManager, IStatsd statsd)
        {
            // update the count of Tracer instances
            Interlocked.Increment(ref _liveTracerCount);

            Settings = settings ?? TracerSettings.FromDefaultSources();

            // if not configured, try to determine an appropriate service name
            DefaultServiceName = Settings.ServiceName ??
                                 GetApplicationName() ??
                                 UnknownServiceName;

            // only set DogStatsdClient if tracer metrics are enabled
            if (Settings.TracerMetricsEnabled)
            {
                // Run this first in case the port override is ready
                TracingProcessManager.SubscribeToDogStatsDPortOverride(
                    port =>
                {
                    Log.Debug("Attempting to override dogstatsd port with {0}", port);
                    Statsd = CreateDogStatsdClient(Settings, DefaultServiceName, port);
                });

                Statsd = statsd ?? CreateDogStatsdClient(Settings, DefaultServiceName, Settings.DogStatsdPort);
            }

            // Run this first in case the port override is ready
            TracingProcessManager.SubscribeToTraceAgentPortOverride(
                port =>
            {
                Log.Debug("Attempting to override trace agent port with {0}", port);
                var builder = new UriBuilder(Settings.AgentUri)
                {
                    Port = port
                };
                var baseEndpoint         = builder.Uri;
                IApi overridingApiClient = new Api(baseEndpoint, delegatingHandler: null, Statsd);
                if (_agentWriter == null)
                {
                    _agentWriter = _agentWriter ?? new AgentWriter(overridingApiClient, Statsd);
                }
                else
                {
                    _agentWriter.OverrideApi(overridingApiClient);
                }
            });

            // fall back to default implementations of each dependency if not provided
            _agentWriter = agentWriter ?? new AgentWriter(new Api(Settings.AgentUri, delegatingHandler: null, Statsd), Statsd);

            _scopeManager = scopeManager ?? new AsyncLocalScopeManager();
            Sampler       = sampler ?? new RuleBasedSampler(new RateLimiter(Settings.MaxTracesSubmittedPerSecond));

            if (!string.IsNullOrWhiteSpace(Settings.CustomSamplingRules))
            {
                // User has opted in, ensure rate limiter is used
                RuleBasedSampler.OptInTracingWithoutLimits();

                foreach (var rule in CustomSamplingRule.BuildFromConfigurationString(Settings.CustomSamplingRules))
                {
                    Sampler.RegisterRule(rule);
                }
            }

            if (Settings.GlobalSamplingRate != null)
            {
                var globalRate = (float)Settings.GlobalSamplingRate;

                if (globalRate < 0f || globalRate > 1f)
                {
                    Log.Warning("{0} configuration of {1} is out of range", ConfigurationKeys.GlobalSamplingRate, Settings.GlobalSamplingRate);
                }
                else
                {
                    Sampler.RegisterRule(new GlobalSamplingRule(globalRate));
                }
            }

            // Register callbacks to make sure we flush the traces before exiting
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;
            AppDomain.CurrentDomain.DomainUnload       += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Console.CancelKeyPress += Console_CancelKeyPress;

            // start the heartbeat loop
            _heartbeatTimer = new Timer(HeartbeatCallback, state: null, dueTime: TimeSpan.Zero, period: TimeSpan.FromMinutes(1));

            // If configured, add/remove the correlation identifiers into the
            // LibLog logging context when a scope is activated/closed
            if (Settings.LogsInjectionEnabled)
            {
                InitializeLibLogScopeEventSubscriber(_scopeManager);
            }
        }
示例#57
0
        /// <summary>
        ///    <para>Attempts to find the response Uri
        ///     Typical string looks like this, need to get trailing filename
        ///     "150 Opening BINARY mode data connection for FTP46.tmp."</para>
        /// </summary>
        private void TryUpdateResponseUri(string str, FtpWebRequest request)
        {
            Uri baseUri = request.RequestUri;
            //
            // Not sure what we are doing here but I guess the logic is IIS centric
            //
            int start = str.IndexOf("for ");

            if (start == -1)
            {
                return;
            }
            start += 4;
            int end = str.LastIndexOf('(');

            if (end == -1)
            {
                end = str.Length;
            }
            if (end <= start)
            {
                return;
            }

            string filename = str.Substring(start, end - start);

            filename = filename.TrimEnd(new char[] { ' ', '.', '\r', '\n' });
            // Do minimal escaping that we need to get a valid Uri
            // when combined with the baseUri
            string escapedFilename;

            escapedFilename = filename.Replace("%", "%25");
            escapedFilename = escapedFilename.Replace("#", "%23");

            // help us out if the user forgot to add a slash to the directory name
            string orginalPath = baseUri.AbsolutePath;

            if (orginalPath.Length > 0 && orginalPath[orginalPath.Length - 1] != '/')
            {
                UriBuilder uriBuilder = new UriBuilder(baseUri);
                uriBuilder.Path = orginalPath + "/";
                baseUri         = uriBuilder.Uri;
            }

            Uri newUri;

            if (!Uri.TryCreate(baseUri, escapedFilename, out newUri))
            {
                throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename));
            }
            else
            {
                if (!baseUri.IsBaseOf(newUri) ||
                    baseUri.Segments.Length != newUri.Segments.Length - 1)
                {
                    throw new FormatException(SR.Format(SR.net_ftp_invalid_response_filename, filename));
                }
                else
                {
                    _responseUri = newUri;
                }
            }
        }
示例#58
0
 public void Constructor_5_BadExtraValue()
 {
     b = new UriBuilder("http", "www.ximian.com", 80, "foo/bar/index.html", "extras");
     // should have thrown an ArgumentException because extraValue must start with '?' or '#' character.
 }
        protected override void EndInvoke(IAsyncResult asyncResult)
        {
            WebResponse webResponse = null;

            try
            {
                AutoDiscoverRequest.FaultInjectionTracer.TraceTest(2263231805U);
                webResponse = this.request.EndGetResponse(asyncResult);
                if (webResponse != null)
                {
                    this.headers = webResponse.Headers;
                    HttpWebResponse httpWebResponse = webResponse as HttpWebResponse;
                    if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.Found)
                    {
                        string text = this.headers["Location"];
                        if (string.IsNullOrEmpty(text))
                        {
                            this.HandleException(Strings.descAutoDiscoverBadRedirectLocation(this.emailAddress.ToString(), "null"), 50492U);
                        }
                        else
                        {
                            AutoDiscoverRequest.AutoDiscoverTracer.TraceDebug <object, string, Uri>((long)this.GetHashCode(), "{0}: Got a redirect from AutoDiscover to {1}, original location was {1}.", TraceContext.Get(), text, this.targetUri);
                            Uri uri;
                            try
                            {
                                uri = new Uri(text);
                            }
                            catch (UriFormatException exception)
                            {
                                this.HandleException(Strings.descAutoDiscoverBadRedirectLocation(this.emailAddress.ToString(), text), exception);
                                return;
                            }
                            UriBuilder uriBuilder = new UriBuilder(uri);
                            uriBuilder.Scheme = (Configuration.UseSSLForAutoDiscoverRequests ? "https" : "http");
                            this.Result       = new AutoDiscoverRequestResult(this.targetUri, null, uriBuilder.Uri, null, this.headers[WellKnownHeader.XFEServer], this.headers[WellKnownHeader.XBEServer]);
                        }
                    }
                    else
                    {
                        this.responseText = this.GetResponseText(webResponse);
                        if (this.responseText == null || this.responseText.Length == 0)
                        {
                            this.HandleException(Strings.descNullAutoDiscoverResponse, new XmlException());
                        }
                        else
                        {
                            string text2 = this.FindError();
                            if (text2 != null)
                            {
                                this.HandleException(Strings.descAutoDiscoverFailedWithException(this.emailAddress.ToString(), text2), 47420U);
                            }
                            else
                            {
                                string text3 = this.FindRedirectAddress();
                                if (text3 != null)
                                {
                                    string frontEndServerName  = null;
                                    string backEnderServerName = null;
                                    if (this.headers != null)
                                    {
                                        frontEndServerName  = this.headers[WellKnownHeader.XFEServer];
                                        backEnderServerName = this.headers[WellKnownHeader.XBEServer];
                                    }
                                    this.Result = new AutoDiscoverRequestResult(this.targetUri, text3, null, null, frontEndServerName, backEnderServerName);
                                }
                                else
                                {
                                    WebServiceUri webServiceUri = this.FindWebServiceUrlForProtocol("EXPR");
                                    if (webServiceUri != null)
                                    {
                                        this.Result = new AutoDiscoverRequestResult(this.targetUri, null, null, webServiceUri, null, null);
                                    }
                                    else
                                    {
                                        webServiceUri = this.FindWebServiceUrlForProtocol("EXCH");
                                        if (webServiceUri != null)
                                        {
                                            this.Result = new AutoDiscoverRequestResult(this.targetUri, null, null, webServiceUri, null, null);
                                        }
                                        else
                                        {
                                            this.HandleException(Strings.descProtocolNotFoundInAutoDiscoverResponse("EXCH", this.targetUri.ToString()), null);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException exception2)
            {
                this.HandleException(exception2);
            }
            catch (ArgumentNullException exception3)
            {
                this.HandleException(exception3);
            }
            catch (ArgumentException exception4)
            {
                this.HandleException(exception4);
            }
            catch (InvalidOperationException exception5)
            {
                this.HandleException(exception5);
            }
            catch (NotSupportedException exception6)
            {
                this.HandleException(exception6);
            }
            catch (XmlException exception7)
            {
                this.HandleException(exception7);
            }
            catch (XPathException exception8)
            {
                this.HandleException(exception8);
            }
            catch (UriFormatException exception9)
            {
                this.HandleException(exception9);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
                this.timer.Stop();
                base.RequestLogger.Add(RequestStatistics.Create(RequestStatisticsType.AutoDiscoverRequest, this.timer.ElapsedMilliseconds, this.targetUri.ToString()));
            }
        }
示例#60
0
        /// <summary>
        /// To make a call to the APROPLAN api
        /// </summary>
        /// <param name="uri">The url to call</param>
        /// <param name="method">The method to use to make the call</param>
        /// <param name="queryParams">The query params collection to use</param>
        /// <param name="data">The data to send through the request</param>
        /// <param name="stream">If you upload something, this is the stream containing the data to upload</param>
        /// <returns>The response of the request as a string</returns>
        private async Task <HttpResponse> Request(string uri, ApiMethod method, IDictionary <string, string> queryParams, string data, Stream stream, string contentType)
        {
            WriteLogRequest(uri, method, queryParams, data, stream);

            int nb = 0;

            if (uri != _resourceRenew)
            {
                if ((RequestLoginState == RequestLoginState.NotConnected || !IsTokenValid()) && !_resourcesWithoutConnection.Contains(new Tuple <ApiMethod, String>(method, uri)))
                {
                    throw new ApiException("Cannot call API without to be connected", "NOT_CONNECTED", null, uri, -1, method.ToString(), null);
                }
            }
            if (!_resourcesLogin.Contains(uri) && uri != _resourceRenew)
            {
                while ((RequestLoginState == RequestLoginState.Connecting || RequestLoginState == RequestLoginState.Renewing) && nb < 10)
                {
                    Thread.Sleep(300);
                    nb++;
                }
            }
            UriBuilder uriBuilder = new UriBuilder(uri);

            Dictionary <string, string> allQueryParams = BuildDefaultQueryParams();

            if (queryParams != null && queryParams.Count > 0)
            {
                foreach (var keyPair in queryParams)
                {
                    allQueryParams.Add(keyPair.Key, keyPair.Value);
                }
            }

            uriBuilder.Query = new FormUrlEncodedContent(allQueryParams).ReadAsStringAsync().Result;
            // Post To GET when url is too long
            if (uriBuilder.Uri.ToString().Length >= 1500 && method.ToString().ToUpperInvariant() == "GET")
            {
                var newUriBuilder = new UriBuilder(ApiRootUrl + "posttoget");

                newUriBuilder.Query = new FormUrlEncodedContent(BuildDefaultQueryParams()).ReadAsStringAsync().Result;
                var    action          = uriBuilder.Path.Split('/').Last();
                string paramsPostToGet = "";
                foreach (var param in queryParams)
                {
                    paramsPostToGet += (paramsPostToGet.Length > 0 ? "&" : "") + $"{param.Key}={param.Value}";
                }

                var dataPost = new
                {
                    EntityAction = action,
                    Params       = paramsPostToGet
                };

                data = JsonConvert.SerializeObject(dataPost, new JsonSerializerSettings
                {
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc
                });

                method     = ApiMethod.Post;
                uriBuilder = newUriBuilder;
            }

            WebRequest request = WebRequest.Create(uriBuilder.Uri);

            request.Method = method.ToString().ToUpperInvariant();


            //stream = request.GetRequestStream();
            if (!String.IsNullOrEmpty(data))
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(data);
                request.ContentType   = "application/json";
                request.ContentLength = byteArray.Length;
                using (stream = request.GetRequestStream())
                {
                    stream.Write(byteArray, 0, byteArray.Length);
                }
            }
            else if (stream != null)
            {
                var oldPosition = stream.Position;
                stream.Position       = 0;
                request.ContentType   = contentType;
                request.ContentLength = stream.Length;
                stream.CopyTo(request.GetRequestStream());
                stream.Position = oldPosition;
            }
            try
            {
                using (WebResponse response = await request.GetResponseAsync())
                {
                    using (stream = response.GetResponseStream())
                    {
                        StreamReader streamReader = new StreamReader(stream);
                        string       dataString   = streamReader.ReadToEnd();

                        if (_logger != null)
                        {
                            string debugMsg = $"API response of {method} to {uri}\r\n\r\n";
                            debugMsg += "\r\n data: " + (dataString == null ? "<null>" : dataString);
                            _logger.LogDebug(debugMsg);
                        }

                        return(new HttpResponse
                        {
                            Data = dataString,
                            Headers = response.Headers
                        });
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    string          url          = ex.Response.ResponseUri.ToString();
                    string          resMethod    = method.ToString();
                    string          errorCode    = null;
                    string          errorId      = null;
                    int             statusCode   = 0;
                    string          message      = "An error occured while the api call";
                    HttpWebResponse httpResponse = ex.Response as HttpWebResponse;
                    if (httpResponse != null)
                    {
                        resMethod  = httpResponse.Method;
                        statusCode = (int)httpResponse.StatusCode;
                    }
                    using (var streamRes = new StreamReader(ex.Response.GetResponseStream()))
                    {
                        string res = streamRes.ReadToEnd();
                        if (ex.Response.ContentType.Contains("application/json"))
                        {
                            JArray json = JsonConvert.DeserializeObject <JArray>(res, new JsonSerializerSettings
                            {
                                DateTimeZoneHandling = DateTimeZoneHandling.Local
                            });
                            JToken item = json.First;
                            IEnumerable <JProperty> properties = item.Children <JProperty>();
                            var element = properties.FirstOrDefault(x => x.Name == "Message");
                            if (element != null)
                            {
                                message = element.Value.ToString();
                            }

                            element = properties.FirstOrDefault(x => x.Name == "ErrorCode");
                            if (element != null)
                            {
                                errorCode = element.Value.ToString();
                            }
                            element = properties.FirstOrDefault(x => x.Name == "ErrorGuid");
                            if (element != null)
                            {
                                errorId = element.Value.ToString();
                            }
                        }
                    }
                    throw new ApiException(message, errorCode, errorId, url, statusCode, resMethod, ex);
                }
                throw;
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    throw;
                }
                string url       = uri;
                string resMethod = method.ToString();
                throw new ApiException("An error occured", null, null, url, 0, resMethod, ex);
            }
        }