コード例 #1
4
        public async Task ConnectAsync_AddCustomHeaders_Success(Uri server)
        {
            using (var cws = new ClientWebSocket())
            {
                cws.Options.SetRequestHeader("X-CustomHeader1", "Value1");
                cws.Options.SetRequestHeader("X-CustomHeader2", "Value2");
                using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
                {
                    Task taskConnect = cws.ConnectAsync(server, cts.Token);
                    Assert.True(
                        (cws.State == WebSocketState.None) ||
                        (cws.State == WebSocketState.Connecting) ||
                        (cws.State == WebSocketState.Open),
                        "State immediately after ConnectAsync incorrect: " + cws.State);
                    await taskConnect;
                }

                Assert.Equal(WebSocketState.Open, cws.State);

                byte[] buffer = new byte[65536];
                var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
                WebSocketReceiveResult recvResult;
                using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
                {
                    recvResult = await cws.ReceiveAsync(segment, cts.Token);
                }

                Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
                string headers = WebSocketData.GetTextFromBuffer(segment);
                Assert.True(headers.Contains("X-CustomHeader1:Value1"));
                Assert.True(headers.Contains("X-CustomHeader2:Value2"));

                await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
        }
コード例 #2
2
ファイル: CredentialCache.cs プロジェクト: yangjunhua/mono
    // properties

    // methods

        /// <devdoc>
        /// <para>Adds a <see cref='System.Net.NetworkCredential'/>
        /// instance to the credential cache.</para>
        /// </devdoc>
        // UEUE
        public void Add(Uri uriPrefix, string authType, NetworkCredential cred) {
            //
            // parameter validation
            //
            if (uriPrefix==null) {
                throw new ArgumentNullException("uriPrefix");
            }
            if (authType==null) {
                throw new ArgumentNullException("authType");
            }
            if ((cred is SystemNetworkCredential)
#if !FEATURE_PAL
                && !((string.Compare(authType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (DigestClient.WDigestAvailable && (string.Compare(authType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
                     || (string.Compare(authType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
                     || (string.Compare(authType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
                ) {
                throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authType), "authType");
            }

            ++m_version;

            CredentialKey key = new CredentialKey(uriPrefix, authType);

            GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");

            cache.Add(key, cred);
            if (cred is SystemNetworkCredential) {
                ++m_NumbDefaultCredInCache;
            }
        }
コード例 #3
1
ファイル: Scenario6.xaml.cs プロジェクト: mbin/Win81App
 private async void Launch_Click(object sender, RoutedEventArgs e)
 {
     if (FacebookClientID.Text == "")
     {
         rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
         return;
     }
  
     var uri = new Uri("https://graph.facebook.com/me");
     HttpClient httpClient = GetAutoPickerHttpClient(FacebookClientID.Text);
     
     DebugPrint("Getting data from facebook....");
     var request = new HttpRequestMessage(HttpMethod.Get, uri);
     try
     {
         var response = await httpClient.SendRequestAsync(request);
         if (response.IsSuccessStatusCode)
         {
             string userInfo = await response.Content.ReadAsStringAsync();
             DebugPrint(userInfo);
         }
         else
         {
             string str = "";
             if (response.Content != null) 
                 str = await response.Content.ReadAsStringAsync();
             DebugPrint("ERROR: " + response.StatusCode + " " + response.ReasonPhrase + "\r\n" + str);
         }
     }
     catch (Exception ex)
     {
         DebugPrint("EXCEPTION: " + ex.Message);
     }
 }
コード例 #4
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Uri uri = new Uri((string)e.Parameter);
	        bool bAuto = false;

            string[] _params = uri.Query.Replace("?", "").Split('&');
            //TODO case "warect"
            //
	    
            for (int i = 0; i < _params.Length; i++) {
                string[] fields = _params[i].Split('=');
                string _name = fields[0];
                string _val = fields[1];
                switch (_name) { 
                    case "waplay":
                        if (_val == "auto")
                            bAuto = true;
                        break;
                }
            }

            string path = "mov/";
            string fileName = uri.LocalPath.Replace("/", "");
            string name = fileName;

            mediaMain.AutoPlay = bAuto;
            string fullPath = String.Format("ms-appdata:///local/{0}", (path + name ));
            Uri videoUrl = new Uri(fullPath);
            mediaMain.Source = videoUrl;
            
        }
コード例 #5
0
 public BaseAppelRequstHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, string VersionHeader)
 {
     this.Request = Request;
     this.Response = Response;
     this.Prefix = Prefix;
     this.VersionHeader = VersionHeader;
 }
コード例 #6
0
ファイル: postecho.cs プロジェクト: Jakosa/MonoLibraries
	static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer)
	{
		Uri uri = new Uri (url);
		string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n";
		post += "Content-Type: application/x-www-form-urlencoded\r\n";
		post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n";
		post += "Host: " + uri.Host + "\r\n\r\n";
		post += "TEST=";
		byte[] bytes = Encoding.Default.GetBytes (post);

		IPHostEntry host = Dns.Resolve (uri.Host);
		IPAddress ip = host.AddressList [0];
		Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
		socket.Connect (new IPEndPoint (ip, uri.Port));
		NetworkStream ns = new NetworkStream (socket, false);
		SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol);
		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);

		ssl.Write (bytes, 0, bytes.Length);
		ssl.Write (buffer, 0, buffer.Length);
		ssl.Flush ();

		StreamReader reader = new StreamReader (ssl, Encoding.UTF8);
		string result = reader.ReadToEnd ();
		int start = result.IndexOf ("\r\n\r\n") + 4;
		start = result.IndexOf ("\r\n\r\n") + 4;
		return result.Substring (start);
	}
コード例 #7
0
    void ProcessDocument(Uri url)
    {
        Console.Error.WriteLine ("Processing {0}...", url);

        var doc = FetchXmlDocument (url);

        var baseTable = doc.SelectSingleNode ("//table[@class='jd-inheritance-table']");
        var baseTypeName = baseTable.SelectSingleNode ("tr[last() - 1]/td[last()]").InnerText;

        fs1.WriteLine ("<class name='{0}' url='{1}' base='{2}'>", GetName (url), url, baseTypeName);
        /*
        var table = doc.SelectSingleNode ("//table[@id='lattrs']");
        if (table != null) {
            var nodes = table.SelectNodes ("tr[contains(@class,'api')]");
            foreach (XmlNode node in nodes) {
                var attr = node.SelectSingleNode ("td[1]//text()");
                var method = node.SelectSingleNode ("td[2]//text()");
                var a = attr.InnerText;
                fs1.WriteLine ("<a>{0}</a>", a);//node.SelectSingleNode ("td[1]"));
                if (!atts.Contains (a))
                    atts.Add (a);
            }
        }
        */
        fs1.WriteLine ("</class>");
        fs1.Flush ();
    }
コード例 #8
0
 public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
 {
     var uri = new Uri(parent.BaseUri, path);
     BitmapImage result = new BitmapImage();
     result.UriSource = uri;
     return result;
 }
コード例 #9
0
        // Maps a URI to an Object containing the actual resource.
        public override Object GetEntity(Uri uri, string role, Type typeOfObjectToReturn)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (typeOfObjectToReturn != null && typeOfObjectToReturn != typeof(Stream) && typeOfObjectToReturn != typeof(Object))
            {
                throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
            }

            string filePath = uri.OriginalString;
            if (uri.IsAbsoluteUri)
            {
                if (!uri.IsFile)
                    throw new XmlException(SR.Format(SR.Xml_SystemPathResolverCannotOpenUri, uri.ToString()));

                filePath = uri.LocalPath;
            }

            try
            {
                return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (ArgumentException e)
            {
                throw new XmlException(SR.Format(SR.Xml_SystemPathResolverCannotOpenUri, uri.ToString()), e);
            }
        }
コード例 #10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        rptEntities.DataSource = companyFac.GetAllEntities();
        rptEntities.DataBind();

        int id = Convert.ToInt32(Request.QueryString["ID"]);
        if (id != 0)
        {
            ShowCompany.Attributes.Remove("hidden");
            comp = companyFac.GetEntityByID(id);
            PopulateFields();
        }
        else if (Request.QueryString["NewItem"] == "true")
        {
            ShowCompany.Attributes.Remove("hidden");
            comp = new Company();
        }
        else if (Convert.ToInt32(Request.QueryString["DID"]) > 0)
        {
            int deleteID = Convert.ToInt32(Request.QueryString["DID"]);

            companyFac.Delete(deleteID);

            var uri = new Uri(Request.Url.AbsoluteUri);
            string path = uri.GetLeftPart(UriPartial.Path);
            Response.Redirect(path);
        }
    }
コード例 #11
0
ファイル: HttpWebRequestTest.cs プロジェクト: nbilling/corefx
 public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
 {
     HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
     string acceptType = "*/*";
     request.Accept = acceptType;
     Assert.Equal(acceptType, request.Accept);
 }
コード例 #12
0
		public VolumeSource (Gnome.Vfs.Volume vol)
		{
			this.Volume = vol;
			this.Name = vol.DisplayName;

			try {
				mount_point = new Uri (vol.ActivationUri).LocalPath;
			} catch (System.Exception e) {
				System.Console.WriteLine (e);
			}

			uri = mount_point;
			
                        if (this.Icon == null)
				this.Icon = PixbufUtils.LoadThemeIcon (vol.Icon, 32);
			
			if (this.IsIPodPhoto)
				this.Icon = PixbufUtils.LoadThemeIcon ("gnome-dev-ipod", 32);

			if (this.Icon == null && this.IsCamera)
				this.Icon = PixbufUtils.LoadThemeIcon ("gnome-dev-media-cf", 32);

			try {
				if (this.Icon == null)
					this.Icon = new Gdk.Pixbuf (vol.Icon);
			} catch (System.Exception e) {
				System.Console.WriteLine (e.ToString ());
			}
		}
コード例 #13
0
    /// <summary>
    /// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization
    /// </summary>
    /// <param name="provider"></param>
    /// <returns></returns>
    protected override string GetAuthorizationUrl(String callbackUrl)
    {
        OAuthBase auth = new OAuthBase();
        String requestUrl = provider.Host + provider.RequestTokenUrl;
        Uri url = new Uri(requestUrl);
        String requestParams = "";
        String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST",
            auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
            new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl)));
        requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature);
        WebClient webClient = new WebClient();
        byte[] response;
        if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null)
        {
            response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams));
        }
        else
        {
            response = webClient.DownloadData(url + "?" + requestParams);
        }
        Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true");
        String requestToken = m.Groups[1].Value;
        String requestTokenSecret = m.Groups[2].Value;
        // we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin)
        // just stick it in the session for now
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken;
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret;

        return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken);
    }
コード例 #14
0
ファイル: XAuth.cs プロジェクト: phmatray/CCrossHelper
        private async Task<OAuth> SignInAsyncTask(string username, string password)
        {
            var o = new OAuth(ConsumerKey, ConsumerSecret);
            var uri = new Uri(XAuthUrl);
            string xauth = string.Format("x_auth_mode=client_auth&x_auth_password={0}&x_auth_username={1}",
                password.UrlEncode(), username.UrlEncode());
            uri = o.SignUri(uri, extraSignature: xauth, httpmethod: "POST");
            string result = await uri.HttpPost(xauth);

            if (result == null)
                return null;

            string token = "";
            string tokensecret = "";
            foreach (var val in result.Split('&').Select(item => item.Split('=')))
            {
                switch (val[0])
                {
                    case "oauth_token":
                        token = val[1];
                        break;
                    case "oauth_token_secret":
                        tokensecret = val[1];
                        break;
                }
            }
            o.Token = token;
            o.TokenSecret = tokensecret;
            return o;
        }
コード例 #15
0
        public MainPage()
        {
            this.InitializeComponent();

            //
            // Every Windows Store application has a unique URI.
            // Windows ensures that only this application will receive messages sent to this URI.
            // ADAL uses this URI as the application's redirect URI to receive OAuth responses.
            // 
            // To determine this application's redirect URI, which is necessary when registering the app
            //      in AAD, set a breakpoint on the next line, run the app, and copy the string value of the URI.
            //      This is the only purposes of this line of code, it has no functional purpose in the application.
            //
            redirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

            authContext = new AuthenticationContext(authority);

            //
            // Out of the box, this sample is *not* configured to work with Windows Integrated Authentication (WIA)
            // when used with a federated Azure Active Directory domain.  To work with WIA the application manifest
            // must enable additional capabilities.  These are not configured by default for this sample because 
            // applications requesting the Enterprise Authentication or Shared User Certificates capabilities require 
            // a higher level of verification to be accepted into the Windows Store, and not all developers may wish
            // to perform the higher level of verification.
            //
            // To enable Windows Integrated Authentication, in Package.appxmanifest, in the Capabilities tab, enable:
            // * Enterprise Authentication
            // * Private Networks (Client & Server)
            // * Shared User Certificates
            //
            // Plus uncomment the following line of code:
            // 
            // authContext.UseCorporateNetwork = true;

        }
コード例 #16
0
        public void ProxyExplicitlyProvided_DefaultCredentials_Ignored()
        {
            int port;
            Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            var rightCreds = new NetworkCredential("rightusername", "rightpassword");
            var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");

            using (var handler = new HttpClientHandler())
            using (var client = new HttpClient(handler))
            {
                handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
                handler.DefaultProxyCredentials = wrongCreds;

                Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
                Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                Task.WaitAll(proxyTask, responseTask, responseStringTask);

                TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}";
                Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
            }
        }
 public CompetitionResultAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate CompetitionResultsTemplate, UriTemplate ResultResourceTemplate, string AcceptHeader)
     : base(Request, Response, Prefix, AcceptHeader)
 {
     this.CompetitionResultsTemplate = CompetitionResultsTemplate;
     this.ResultResourceTemplate = ResultResourceTemplate;
     processRequest();
 }
コード例 #18
0
ファイル: MainWindow.cs プロジェクト: myersBR/My-FyiReporting
    private string GetParameters(Uri sourcefile)
    {
        string parameters = "";
        string sourceRdl = System.IO.File.ReadAllText(sourcefile.LocalPath);
        fyiReporting.RDL.RDLParser parser = new fyiReporting.RDL.RDLParser(sourceRdl);
        parser.Parse();
        if (parser.Report.UserReportParameters.Count > 0)
        {
					
            int count = 0;
            foreach (fyiReporting.RDL.UserReportParameter rp in parser.Report.UserReportParameters)
            {
                parameters += "&" + rp.Name + "=";
            }
			
            fyiReporting.RdlGtkViewer.ParameterPrompt prompt = new fyiReporting.RdlGtkViewer.ParameterPrompt();
            prompt.Parameters = parameters;
            if (prompt.Run() == (int)Gtk.ResponseType.Ok)
            {
                parameters = prompt.Parameters;
            }
            prompt.Destroy();
			
        }	
		
        return parameters;
    }
コード例 #19
0
        public void BuildRoute_ValidatesConstraintType_InvalidType()
        {
            // Arrange
            var actions = GetActions();
            var builder = new DirectRouteBuilder(actions, targetIsAction: true);

            var constraint = new Uri("http://localhost/");
            var constraints = new TRouteValueDictionary();
            constraints.Add("custom", constraint);

            builder.Constraints = constraints;
            builder.Template = "c/{id}";

#if ASPNETWEBAPI
            string expectedMessage =
                "The constraint entry 'custom' on the route with route template 'c/{id}' " +
                "must have a string value or be of a type which implements 'System.Web.Http.Routing.IHttpRouteConstraint'.";
#else
            string expectedMessage =
                "The constraint entry 'custom' on the route with route template 'c/{id}' " +
                "must have a string value or be of a type which implements 'System.Web.Routing.IRouteConstraint'.";
#endif

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() => builder.Build(), expectedMessage);
        }
コード例 #20
0
            /// <summary>
            /// Helper that produces the contents corresponding to a Uri.
            /// Uses the C# await pattern to coordinate async operations.
            /// </summary>
            /// <param name="uri"></param>
            /// <returns></returns>
            private async Task<IInputStream> GetContentAsync(Uri uri)
            {
                string path = uri.AbsolutePath;
                string contents;

                switch (path)
                {
                    case "/default.html":
                        contents = await MainPage.LoadStringFromPackageFileAsync("stream_example.html");
                        contents = contents.Replace("%", Windows.ApplicationModel.Package.Current.Id.Name);
                        break;

                    case "/stream.css":
                        contents = "p { color: blue; }";
                        break;

                    default:
                        throw new Exception($"Could not resolve URI \"{uri}\"");
                }

                // Convert the string to a stream.
                IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(contents, BinaryStringEncoding.Utf8);
                var stream = new InMemoryRandomAccessStream();
                await stream.WriteAsync(buffer);
                return stream.GetInputStreamAt(0);
            }
コード例 #21
0
	private void SearchByApml(Uri url)
	{
		List<IPublishable> list = new List<IPublishable>();
		try
		{
			Dictionary<Uri, XmlDocument> docs = Utils.FindSemanticDocuments(url, "apml");
			if (docs.Count > 0)
			{
				foreach (Uri key in docs.Keys)
				{
					list = Search.ApmlMatches(docs[key], 30);
					Page.Title = "APML matches for '" + Server.HtmlEncode(key.ToString()) + "'";
					break;
				}
			}
			else
			{
				Page.Title = "APML matches for '" + Server.HtmlEncode(Request.QueryString["q"]) + "'";
			}
			h1Headline.InnerText = Page.Title;
		}
		catch
		{

		}

		BindSearchResult(list);
	}
コード例 #22
0
    public static HttpWebRequest GenerateHttpWebRequest(Uri uri)
    {
        //all this mess below is my attempt to resolve some of the issues in taking on various conflicts in httpreqeust.
            //code is left in
            //if infact requests vary may need to switch(key) on differnet sites?

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.2 Safari/534.2";

            CookieContainer cc = new CookieContainer();
            httpRequest.CookieContainer = cc;//must assing a cookie container for the request to pull the cookies

            httpRequest.AllowAutoRedirect = true;   //example, Hanes.com

            httpRequest.Credentials = CredentialCache.DefaultCredentials;

            //httpRequest.Headers.Add("HTTP_USER_AGENT", @"Mozilla/5.0(PC) (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4");

            //   httpRequest.Headers.Add("Agent", "Mozilla/5.0(PC) (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4");
            //   httpRequest.Headers.Add("Accept-Charset", "ISO-8859-1");
            /*

            httpRequest.Headers.Add("Accept-Language", "en-us,en;q=0.5");
            httpRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            httpRequest.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

          //  httpRequest.Headers.Add("Set-Cookie", response.Headers("Set-Cookie"));
            httpRequest.Headers.Add("Agent", "Mozilla//5.0 (X11; U; Linux i686; en-US; ry; 1.8.0.7) Geck//20060925 Firefox//1.5.0.7");
            */

            return httpRequest;
    }
コード例 #23
0
    public void DocumentationIndexIsUpToDate()
    {
        var documentationIndexFile = ReadDocumentationFile("../mkdocs.yml");
        var docsDirectoryPath = new Uri(docsDirectory.FullName, UriKind.Absolute);

        Console.WriteLine(docsDirectoryPath);

        foreach (var markdownFile in docsDirectory.EnumerateFiles("*.md", SearchOption.AllDirectories))
        {
            var fullPath = new Uri(markdownFile.FullName, UriKind.Absolute);
            var relativePath = docsDirectoryPath
                .MakeRelativeUri(fullPath)
                .ToString()
                .Replace("docs/", string.Empty);

            // The readme file in the docs directory is not supposed to be deployed to ReadTheDocs;
            // it's only there for the convenience of contributors wanting to improve the documentation itself.
            if (relativePath == "readme.md")
            {
                continue;
            }

            documentationIndexFile.ShouldContain(relativePath, () => string.Format("The file '{0}' is not listed in 'mkdocs.yml'.", relativePath));
        }
    }
コード例 #24
0
        public static Evidence CreateEvidenceForUrl(string securityUrl) {
#if !DISABLE_CAS_USE
            Evidence evidence = new Evidence();
            if (securityUrl != null && securityUrl.Length > 0) {
                evidence.AddHostEvidence(new Url(securityUrl));
                evidence.AddHostEvidence(Zone.CreateFromUrl(securityUrl));
                Uri uri = new Uri(securityUrl, UriKind.RelativeOrAbsolute);
                if (uri.IsAbsoluteUri && !uri.IsFile) {
                    evidence.AddHostEvidence(Site.CreateFromUrl(securityUrl));
                }

                // Allow same directory access for UNCs (SQLBUDT 394535)
                if (uri.IsAbsoluteUri && uri.IsUnc) {
                    string uncDir = System.IO.Path.GetDirectoryName(uri.LocalPath);
                    if (uncDir != null && uncDir.Length != 0) {
                        evidence.AddHostEvidence(new UncDirectory(uncDir));
                    }
                }
            }

            return evidence;
#else
            return null;
#endif
        }
コード例 #25
0
 public void UriIsWellFormed_NewAbsoluteUnregisteredAsRelative_Throws()
 {
     Assert.ThrowsAny<FormatException>(() =>
   {
       Uri test = new Uri("any://foo", UriKind.Relative);
   });
 }
コード例 #26
0
ファイル: MoeOAuth.cs プロジェクト: mazheng367/Moe.fm
        private async Task<string> GetRequestToken()
        {
            try
            {
                const string requestTokenUrl = "http://api.moefou.org/oauth/request_token";
                const string httpMethod = "GET";
                Uri url = new Uri(requestTokenUrl);
                string timeStamp = this.OAuth.GenerateTimeStamp();
                string nonce = this.OAuth.GenerateNonce();
                string nUrl = null;
                string pa = null;
                string signature = this.OAuth.GenerateSignature(url, AppConst.MoeAppKey, AppConst.ConsumerSecret, string.Empty, string.Empty, httpMethod, timeStamp, nonce, string.Empty, out nUrl, out pa);
                List<QueryParameter> parameters = new List<QueryParameter>();


                string requestUrl = string.Format("{0}?{1}&{2}={3}", nUrl, pa, OAuthBase.OAuthSignatureKey, signature);
                WebRequest request = WebRequest.Create(requestUrl);
                WebResponse response = await request.GetResponseAsync();
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    List<QueryParameter> reqPa = this.OAuth.GetQueryParameters(await sr.ReadToEndAsync());
                    var oauth_token = reqPa.Find(qp => qp.Name.Equals("oauth_token")).Value;
                    var oauth_token_secret = reqPa.Find(qp => qp.Name.Equals("oauth_token_secret")).Value;
                    //将为授权的token放入到
                    Windows.Storage.ApplicationData.Current.LocalSettings.Values["oauth_token"] = oauth_token;
                    Windows.Storage.ApplicationData.Current.LocalSettings.Values["oauth_token_secret"] = oauth_token_secret;
                }
                return string.Empty;
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #27
0
ファイル: UriUtils.cs プロジェクト: rambo-returns/MonoRail
        internal static string UriToString(Uri uri)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(uri != null, "uri != null");

            return uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString;
        }
コード例 #28
0
        /// <summary>
        /// Get Presence information per user.
        /// </summary>
        private async void AsyncPresence()
        {
            var client = new HttpClient();

            var uri = new Uri(string.Format(Configurations.PresenceUrl, Configurations.ApiKey, _currentMember.id));
            var response = await client.GetAsync(uri);
            var statusCode = response.StatusCode;
            switch (statusCode)
            {
                // TODO: Error handling for invalid htpp responses.
            }
            response.EnsureSuccessStatusCode();
            var theResponse = await response.Content.ReadAsStringAsync();
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(theResponse)))
            {
                var serializer = new DataContractJsonSerializer(typeof(PresenceRoot));
                var presenceObject = serializer.ReadObject(ms) as PresenceRoot;
                // This will allow the application to toggle the presence indicator color.    
                if (presenceObject != null && presenceObject.ok && presenceObject.IsActive())
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        StatusIndicator.Fill = new SolidColorBrush(Color.FromArgb(255, 127, 153, 71));
                    });
                }
                // TODO: Add more code for bad replies or invalid requests.
            }
        }
コード例 #29
0
 // Internal constructor
 // <param name="uri">URI of the markup page to navigate to.</param>
 // <param name="bytesRead">The number of bytes that have already been downloaded.</param>
 // <param name="maxBytes">The maximum number of bytes to be downloaded.</param>
 // <param name="Navigator">navigator that raised this event</param>
 internal NavigationProgressEventArgs(Uri uri, long bytesRead, long maxBytes, object Navigator)
 {
     _uri = uri;
     _bytesRead = bytesRead;
     _maxBytes = maxBytes;
     _navigator = Navigator;
 }
コード例 #30
0
 		public PolicyBasedWebRequest (Uri uri)
 		{
			this.uri = uri;
			allow_read_buffering = true;
			method = "GET";
			content_length = -1;
		}
コード例 #31
0
 public ReferenceLink(string shortDescription, string url)
 {
     ShortDescription = shortDescription;
     Uri = new Uri(url);
 }
コード例 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FamilySearchFamilyTree"/> class.
 /// </summary>
 /// <param name="uri">The URI where the target resides.</param>
 /// <param name="stateFactory">The state factory to use for state instantiation.</param>
 private FamilySearchFamilyTree(Uri uri, FamilyTreeStateFactory stateFactory)
     : this(uri, stateFactory.LoadDefaultClientInt(uri), stateFactory)
 {
 }
コード例 #33
0
 internal static string EndpointReference(Uri uri, string contractName)
 {
     return(EndpointReference((null != uri) ? uri.ToString() : string.Empty, contractName, true));
 }
コード例 #34
0
        public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Configuration.Http.RemoteServer remoteServer, Uri url, bool checkRevocation)
        {
            HttpClientHandler handler = CreateHttpClientHandler();
            using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler))
            {
                bool callbackCalled = false;
                handler.CheckCertificateRevocationList = checkRevocation;
                handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
                    callbackCalled = true;
                    Assert.NotNull(request);

                    X509ChainStatusFlags flags = chain.ChainStatus.Aggregate(X509ChainStatusFlags.NoError, (cur, status) => cur | status.Status);
                    bool ignoreErrors = // https://github.com/dotnet/runtime/issues/22644#issuecomment-315555237
                        RuntimeInformation.IsOSPlatform(OSPlatform.OSX) &&
                        checkRevocation &&
                        errors == SslPolicyErrors.RemoteCertificateChainErrors &&
                        flags == X509ChainStatusFlags.RevocationStatusUnknown;
                    Assert.True(ignoreErrors || errors == SslPolicyErrors.None, $"Expected {SslPolicyErrors.None}, got {errors} with chain status {flags}");

                    Assert.True(chain.ChainElements.Count > 0);
                    Assert.NotEmpty(cert.Subject);

                    // UWP always uses CheckCertificateRevocationList=true regardless of setting the property and
                    // the getter always returns true. So, for this next Assert, it is better to get the property
                    // value back from the handler instead of using the parameter value of the test.
                    Assert.Equal(
                        handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
                        chain.ChainPolicy.RevocationMode);
                    return true;
                };

                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                }

                Assert.True(callbackCalled);
            }
        }
コード例 #35
0
ファイル: sts.cs プロジェクト: stanasse/olive
        public static void Main(string [] args)
        {
            int    port = 0;
            string certfile = null;
            string certpass = null;
            bool   no_sc = false, no_nego = false;

            foreach (string arg in args)
            {
                if (arg == "--help")
                {
                    Usage();
                    return;
                }
                if (arg.StartsWith("--port:"))
                {
                    int.TryParse(arg.Substring(7), out port);
                    continue;
                }
                if (arg == "--no-sc")
                {
                    no_sc = true;
                    continue;
                }
                if (arg == "--no-nego")
                {
                    no_nego = true;
                    continue;
                }
                if (arg.StartsWith("--certfile:"))
                {
                    certfile = arg.Substring(11);
                    continue;
                }
                if (arg.StartsWith("--certpass:"******"unrecognized option: " + arg);
                return;
            }
            if (certfile == null || certpass == null)
            {
                Console.WriteLine("specify certificate information to identify this service.");
                return;
            }

            if (port <= 0)
            {
                port = 8080;
            }
            Uri listeningUri = new Uri("http://localhost:" + port);

            ServiceHost host = new ServiceHost(
                typeof(WSTrustSecurityTokenService), listeningUri);

            host.Description.Behaviors.Find <ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);

            WSHttpBinding binding = new WSHttpBinding();

            binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
            if (no_sc)
            {
                binding.Security.Message.EstablishSecurityContext = false;
            }
            if (no_nego)
            {
                binding.Security.Message.NegotiateServiceCredential = false;
            }
            ServiceCredentials credentials = new ServiceCredentials();

            credentials.ServiceCertificate.Certificate = new X509Certificate2(certfile, certpass);
            //credentials.IssuedTokenAuthentication.AllowUntrustedRsaIssuers = true;
            host.Description.Behaviors.Add(credentials);

            host.AddServiceEndpoint(
                typeof(IWSTrustSecurityTokenService),
                binding,
                listeningUri);

            host.Open();
            Console.WriteLine("Type [ENTER] to close ...");
            Console.ReadLine();
            host.Close();
        }
コード例 #36
0
        /// <summary>
        /// Builds a model using the specified <see cref="DocumentModelAdministrationClient"/> and the specified set of training files. A
        /// <see cref="DisposableBuildModel"/> instance is returned. Upon disposal,
        /// the associated model will be deleted.
        /// </summary>
        /// <param name="adminClient">The client to use for building and for deleting the model upon disposal.</param>
        /// <param name="trainingFilesUri">An externally accessible Azure storage blob container Uri.</param>
        /// <param name="buildMode">The technique to use to build the model.</param>
        /// <param name="modelId">Model Id.</param>
        /// <returns>A <see cref="DisposableBuildModel"/> instance from which the trained model ID can be obtained.</returns>
        public static async Task<DisposableBuildModel> BuildModelAsync(DocumentModelAdministrationClient adminClient, Uri trainingFilesUri, DocumentBuildMode buildMode, string modelId)
        {
            BuildModelOperation operation = await adminClient.StartBuildModelAsync(trainingFilesUri, buildMode, modelId);
            await operation.WaitForCompletionAsync();

            Assert.IsTrue(operation.HasValue);

            return new DisposableBuildModel(adminClient, operation.Value.ModelId);
        }
コード例 #37
0
 public override void WriteValue(Uri value)
 {
     _textWriter.WriteValue(value);
     _innerWriter.WriteValue(value);
     base.WriteValue(value);
 }
コード例 #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FamilySearchFamilyTree"/> class.
 /// </summary>
 /// <param name="uri">The URI where the target resides.</param>
 /// <param name="client">The REST API client to use for API calls.</param>
 /// <param name="stateFactory">The state factory to use for state instantiation.</param>
 private FamilySearchFamilyTree(Uri uri, IFilterableRestClient client, FamilyTreeStateFactory stateFactory)
     : this(new RedirectableRestRequest().Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE).Build(uri, Method.GET), client, stateFactory)
 {
 }
コード例 #39
0
        private string CreateOauthSignature(string resourceUrl, Method method, string oauthNonce, string oauthTimestamp, SortedDictionary requestParameters)
        {
            //firstly we need to add the standard oauth parameters to the sorted list
            requestParameters.Add("oauth_consumer_key", ConsumerKey);
            requestParameters.Add("oauth_nonce", oauthNonce);
            requestParameters.Add("oauth_signature_method", OauthSignatureMethod);
            requestParameters.Add("oauth_timestamp", oauthTimestamp);
            requestParameters.Add("oauth_token", AccessToken);
            requestParameters.Add("oauth_version", OauthVersion);
            var sigBaseString       = requestParameters.ToWebString();
            var signatureBaseString = string.Concat(method.ToString(), "&", Uri.EscapeDataString(resourceUrl), "&", Uri.EscapeDataString(sigBaseString.ToString()));
            //Using this base string, we then encrypt the data using a composite of the
            //secret keys and the HMAC-SHA1 algorithm.

            var    compositeKey = string.Concat(Uri.EscapeDataString(ConsumerKeySecret), "&", Uri.EscapeDataString(AccessTokenSecret));
            string oauthSignature;

            using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
            {
                oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));
            }
            return(oauthSignature);
        }
コード例 #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FamilySearchFamilyTree"/> class.
 /// </summary>
 /// <param name="uri">The URI where the target collection resides.</param>
 public FamilySearchFamilyTree(Uri uri)
     : this(uri, new FamilyTreeStateFactory())
 {
 }
コード例 #41
0
 public void RegisterLoadBalancerEndpoint(Uri loadBalancerEndpoint)
 {
     container.Configure(c => c.For<LoadBalancerMessageModule>().Singleton().Use<LoadBalancerMessageModule>()
                                  .Ctor<Uri>().Is(loadBalancerEndpoint));
 }
コード例 #42
0
        private string CreateHeader(string resourceUrl, Method method, SortedDictionary requestParameters)
        {
            var oauthNonce     = CreateOauthNonce();
            var oauthTimestamp = CreateOAuthTimestamp();
            var oauthSignature = CreateOauthSignature(resourceUrl, method, oauthNonce, oauthTimestamp, requestParameters);
            //The oAuth signature is then used to generate the Authentication header.
            const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + "oauth_version=\"{6}\""; var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauthNonce), Uri.EscapeDataString(OauthSignatureMethod), Uri.EscapeDataString(oauthTimestamp), Uri.EscapeDataString(ConsumerKey), Uri.EscapeDataString(AccessToken), Uri.EscapeDataString(oauthSignature), Uri.EscapeDataString(OauthVersion));

            return(authHeader);
        }
コード例 #43
0
 public static Task<string> Get(this IWebClient client, Uri address)
 {
     return Get(client, null, address);
 }
コード例 #44
0
 public Activity(Uri uri) : base(uri) { }
コード例 #45
0
 public static Task<string> Post(this IWebClient client, Uri address, string data)
 {
     return Post(client, null, address, data);
 }
コード例 #46
0
        public static string createTicket(string requester, string tech, string desc, string subj)
        {
            string input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            input += "<operation>  ";
            input += "  <Details>";
            input += "    <parameter>";
            input += "      <name>REQUESTER</name>";
            input += "      <value>" + requester + "</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>SUBJECT</name>";
            input += "      <value>" + subj + "</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>REQUESTTEMPLATE</name>";
            input += "      <value>Default Request</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>PRIORITY</name>";
            input += "      <value>Low</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>IMPACT</name>";
            input += "      <value>None</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>URGENCY</name>";
            input += "      <value>Low</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>DESCRIPTION</name>";
            input += "      <value>" + desc + "</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            //input += "      <name>TECHNICIAN</name>";
            input += "      <name>GROUP</name>";
            input += "      <value>Production Support</value>";
            //input += "      <value>" + tech + "</value>";
            input += "    </parameter>";
            input += "    <parameter>";
            input += "      <name>SITE</name>";
            input += "      <value>Manchester</value>";
            input += "    </parameter>";
            input += "  </Details>";
            input += "</operation>";

            // ee0eb78335d1e4ea02add34a18be2607
            // 0b63f1cf2ce5a0f63307bc53836cd910
            // ebd6098dbe251cc26eccf68617c8ed49
            // string json = GetData(@"https://sdpondemand.manageengine.com/api/request", "?scope=sdpodapi&authtoken=0b63f1cf2ce5a0f63307bc53836cd910&OPERATION_NAME=ADD_REQUEST&INPUT_DATA=" + System.Web.HttpUtility.UrlEncode(input));

            string json = GetData(@"https://sdpondemand.manageengine.com/api/request", "?scope=sdpodapi&authtoken=0b63f1cf2ce5a0f63307bc53836cd910&OPERATION_NAME=ADD_REQUEST&INPUT_DATA=" + Uri.EscapeUriString(input));
            return json;

        }
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task<IDictionary<string, string>> AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            // Try to cancel any existing authentication process.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            _auth = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: new Uri(OAuthRedirectUrl))
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            _auth.Completed += (o, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete.
                    InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); });

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    _auth.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            _auth.Error += (o, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    _taskCompletionSource?.TrySetCanceled();
                }

                // Cancel authentication.
                _auth.OnCancelled();
                _auth = null;
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_auth.GetUI(), true, null); });

            // Return completion source task so the caller can await completion.
            return _taskCompletionSource.Task;
        }
コード例 #48
0
 Task <ReceivedStatus> IReceiverCallback.Received(Uri uri, Envelope[] messages)
 {
     throw new NotImplementedException();
 }
コード例 #49
0
        void t1_Tick(object sender, EventArgs e)
        {
            try
            {
                WAstatus = WinampLib.GetPlaybackStatus();       // Winamp states: 3=pause,1=play,0=stop
                switch (WAstatus)
                {
                    case 1:                                     // Winamp playing
                        strWATitlePast = strWATitle;
                        strWATitle = WinampLib.GetCurrentSongTitle();
                        lbl_CurrentTitle.Text = strWATitle;
                        if (strWATitle != strWATitlePast)       // new song started
                        {
                            axWindowsMediaPlayer1.URL = "none.mp3";                     // dummy input (else cannot overwrite speech.mp3 with new file)
                            if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsPlaying)
                            {
                                axWindowsMediaPlayer1.Ctlcontrols.stop();
                            }
                            axWindowsMediaPlayer1.close();
                            // URL encoding
                            strWATitleTalk = strWATitle.Replace("&", "%26");
                            strWATitleTalk = strWATitleTalk.Replace("ä", "ae");
                            strWATitleTalk = strWATitleTalk.Replace("ö", "oe");
                            strWATitleTalk = strWATitleTalk.Replace("ü", "ue");
                            strWATitleTalk = strWATitleTalk.Replace("Ä", "Ae");
                            strWATitleTalk = strWATitleTalk.Replace("Ö", "Oe");
                            strWATitleTalk = strWATitleTalk.Replace("Ü", "Ue");
                            // ...

                            strTTSURL = "http://translate.google.com/translate_tts?tl=" + strLanguage + "&q=" + strWATitleTalk;
                            //MessageBox.Show(strWATitleTalk);                          // debug

                            if ((strWATitle.Length < 100) && (cb_voice.Checked))        // max. length 100 chars
                            {
                                
                                // download voice file
                                using (wc = new WebClient())
                                {
                                    wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DLCompleted);
                                    //wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

                                    Uri URL = new Uri(strTTSURL);

                                    try
                                    {
                                        // download
                                        wc.DownloadFileAsync(URL, "speech.mp3");
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                }
                            }
                        }
                        break;
                    case 3:                                                             // Winamp paused
                        lbl_CurrentTitle.Text = "P A U S E";
                        break;
                    default:
                        strWATitle = "";
                        strWATitlePast = "";
                        strWATitleTalk = "";
                        lbl_CurrentTitle.Text = "";
                        break;
                }
            }
            catch { }
        }
コード例 #50
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("please Enter the TFS Server IP : ");
                String TfsServerIp = Console.ReadLine();
                String TfsServerPort = "8080";
                String TfsServerVirtualPath = "tfs";
                String TfsServerUriString = string.Format("http://{0}:{1}/{2}", TfsServerIp, TfsServerPort, TfsServerVirtualPath);
                Uri TfsServerUri = new Uri(TfsServerUriString);

                TfsConfigurationServer TfsServerconfiguration = TfsConfigurationServerFactory.GetConfigurationServer(TfsServerUri);

                ReadOnlyCollection<CatalogNode> ProjectCollectionNodes = TfsServerconfiguration.CatalogNode.QueryChildren(
                 new[] { CatalogResourceTypes.ProjectCollection },
                 false, CatalogQueryOptions.None);


                Console.WriteLine("please enter the ProjectCollection name : ");
                string ProjectCollectionName = Console.ReadLine();

                foreach (CatalogNode ProjectCollectionNode in ProjectCollectionNodes)
                {
                    if (ProjectCollectionNode.Resource.DisplayName == ProjectCollectionName)
                    {
                        Guid collectionId = new Guid(ProjectCollectionNode.Resource.Properties["InstanceId"]);
                        TfsTeamProjectCollection TeamProjectCollection = TfsServerconfiguration.GetTeamProjectCollection(collectionId);
                        TeamProjectCollection.Connect(ConnectOptions.None);
                        VersionControlServer Vcs = TeamProjectCollection.GetService<VersionControlServer>();

                        ReadOnlyCollection<CatalogNode> TeamProjectNodes = ProjectCollectionNode.QueryChildren(
                       new[] { CatalogResourceTypes.TeamProject },
                       false, CatalogQueryOptions.None);

                        Console.WriteLine("please enter the Team Project name : ");
                        String TeamProjectName = Console.ReadLine();

                        Console.WriteLine("Please enter the Branch name : ");
                        String BranchName = Console.ReadLine();

                        foreach (CatalogNode TeamProjectNode in TeamProjectNodes)
                        {

                            if (TeamProjectNode.Resource.DisplayName == TeamProjectName)
                            {



                                var tp = Vcs.GetTeamProject(TeamProjectNode.Resource.DisplayName);
                                var ServerPath = String.Format("{0}/Branches/{1}", tp.ServerItem, BranchName);


                                VersionSpec versionFrom = null;
                                VersionSpec versionTo = VersionSpec.Latest;


                                var ChangeSetList = Vcs.QueryHistory(

                                                         ServerPath,
                                                         VersionSpec.Latest,
                                                         0,
                                                         RecursionType.Full,
                                                         null,
                                                         versionFrom,
                                                         versionTo,
                                                         Int32.MaxValue,
                                                         true,
                                                         true
                                                                ).Cast<Changeset>().ToList();

                                Changeset Lastchangeset = null;
                                Lastchangeset = ChangeSetList.First();

                                Console.WriteLine(".....last Changest Report.....");
                                Console.WriteLine();
                                Console.WriteLine(string.Format("ID : {0} , Date: {1} , Comment : {2} , by : {3} ", Lastchangeset.ChangesetId, Lastchangeset.CreationDate, Lastchangeset.Comment, Lastchangeset.OwnerDisplayName));
                                Console.WriteLine();
                                Console.WriteLine(".....End The Report.....");

                            }

                        }

                    }
                                   }
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.WriteLine(" Warnining ");
                Console.WriteLine("-----------please check your TFS Server IP-----------");
                Console.ReadLine();
            }
        }
コード例 #51
0
 public static Task<string> Get(this IWebClient client, WebHeaderCollection headers, Uri address)
 {
     if (client == null) throw new ArgumentNullException("client");
     return client.Get(headers, address, (_, r) => r);
 }
コード例 #52
0
        /// <summary>
        /// Adds a service bus host using the MassTransit style URI host name
        /// </summary>
        /// <param name="configurator">The bus factory configurator</param>
        /// <param name="hostAddress">The host address, in MassTransit format (sb://namespace.servicebus.windows.net/scope)</param>
        /// <param name="configure">A callback to further configure the service bus</param>
        /// <returns>The service bus host</returns>
        public static IServiceBusHost Host(this IServiceBusBusFactoryConfigurator configurator, Uri hostAddress,
                                           Action <IServiceBusHostConfigurator> configure)
        {
            var hostConfigurator = new ServiceBusHostConfigurator(hostAddress);

            configure(hostConfigurator);

            return(configurator.Host(hostConfigurator.Settings));
        }
コード例 #53
0
        private void CreateAndShowMainWindow ()
        {

            // Create the application's main window
            mainWindow = new Window ();
            mainWindow.Title = "BMP Imaging Sample";
            ScrollViewer mySV = new ScrollViewer();

            int width = 128;
            int height = width;
            int stride = width / 8;
            byte[] pixels = new byte[height * stride];

            // Try creating a new image with a custom palette.
            List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
            colors.Add(System.Windows.Media.Colors.Red);
            colors.Add(System.Windows.Media.Colors.Blue);
            colors.Add(System.Windows.Media.Colors.Green);
            BitmapPalette myPalette = new BitmapPalette(colors);

            // Creates a new empty image with the pre-defined palette
            BitmapSource image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed1,
                myPalette,
                pixels,
                stride);

            FileStream stream = new FileStream("new.bmp", FileMode.Create);
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            TextBlock myTextBlock = new TextBlock();
            myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);



            // Open a Stream and decode a BMP image
            Stream imageStreamSource = new FileStream("tulipfarm.bmp", FileMode.Open, FileAccess.Read, FileShare.Read);
            BmpBitmapDecoder decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];
            
            // Draw the Image
            Image myImage = new Image();
            myImage.Source = bitmapSource;
            myImage.Stretch = Stretch.None;
            myImage.Margin = new Thickness(20);


            // Open a Uri and decode a BMP image
            Uri myUri = new Uri("tulipfarm.bmp", UriKind.RelativeOrAbsolute);
            BmpBitmapDecoder decoder2 = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource2 = decoder2.Frames[0];

            // Draw the Image
            Image myImage2 = new Image();
            myImage2.Source = bitmapSource2;
            myImage2.Stretch = Stretch.None;
            myImage2.Margin = new Thickness(20);

            // Define a StackPanel to host the decoded BMP images
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Orientation = Orientation.Vertical;
            myStackPanel.VerticalAlignment = VerticalAlignment.Stretch;
            myStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch;
            
            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage); 
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySV.Content = myStackPanel;
            mainWindow.Content = mySV;
            mainWindow.Show();
        }
コード例 #54
0
        /// <summary>
        /// Get method with unencoded query parameter with value
        /// 'value1&amp;q2=value2&amp;q3=value3'
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task<AzureOperationResponse> GetSwaggerQueryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            string q1 = "value1&q2=value2&q3=value3";
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("q1", q1);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerQueryValid", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/query/valid").ToString();
            List<string> _queryParameters = new List<string>();
            if (q1 != null)
            {
                _queryParameters.Add(string.Format("q1={0}", q1));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }
コード例 #55
0
        /// <summary>
        /// AudioRequest from a formatted string
        /// </summary>
        /// <param name="formattedString">[local|streaming]://reciterId?amount=AudioDownloadAmount&amp;currentAyah=1:2&amp;fromAyah=1:2&amp;to=2:1&amp;repeat=xxx;currentRepeat=2</param>
        public AudioRequest(string formattedString)
        {
            if (string.IsNullOrEmpty(formattedString))
                throw new ArgumentNullException("formattedString");

            try
            {
                Uri patternAsUri = new Uri(formattedString);
                if (patternAsUri.Scheme.Equals("local", StringComparison.OrdinalIgnoreCase))
                    IsStreaming = false;
                else if (patternAsUri.Scheme.Equals("streaming", StringComparison.OrdinalIgnoreCase))
                    IsStreaming = true;
                else
                    throw new ArgumentException("scheme");

                this.Reciter = AudioUtils.GetReciterById(int.Parse(patternAsUri.Host));

                var splitQueryString = patternAsUri.Query.Split(new char[] { '?', '&' });

                int currentRepeatIteration = 0;

                foreach (var part in splitQueryString)
                {
                    var splitPart = part.Split('=');
                    if (splitPart[0].Equals("amount", StringComparison.OrdinalIgnoreCase))
                    {
                        this.AudioDownloadAmount =
                            (AudioDownloadAmount) Enum.Parse(typeof (AudioDownloadAmount), splitPart[1]);
                    }
                    else if (splitPart[0].Equals("currentAyah", StringComparison.OrdinalIgnoreCase))
                    {
                        this.CurrentAyah = QuranAyah.FromString(splitPart[1]);
                    }
                    else if (splitPart[0].Equals("fromAyah", StringComparison.OrdinalIgnoreCase))
                    {
                        this.FromAyah = QuranAyah.FromString(splitPart[1]);
                    }
                    else if (splitPart[0].Equals("toAyah", StringComparison.OrdinalIgnoreCase))
                    {
                        this.ToAyah = QuranAyah.FromString(splitPart[1]);
                    }
                    else if (splitPart[0].Equals("repeat", StringComparison.OrdinalIgnoreCase))
                    {
                        this.RepeatInfo = RepeatInfo.FromString(splitPart[1]);
                    }
                    else if (splitPart[0].Equals("currentRepeat", StringComparison.OrdinalIgnoreCase))
                    {
                        int.TryParse(splitPart[1], out currentRepeatIteration);
                    }
                }

                if (this.CurrentAyah == null)
                    this.CurrentAyah = this.FromAyah;

                this.repeatManager = new RepeatManager(this.RepeatInfo, this.FromAyah, currentRepeatIteration);
            }
            catch
            {
                throw new ArgumentException("formattedString");
            }
        }
コード例 #56
0
ファイル: JTokenWriter.cs プロジェクト: mindis/Transformalize
 /// <summary>
 /// Writes a <see cref="Uri"/> value.
 /// </summary>
 /// <param name="value">The <see cref="Uri"/> value to write.</param>
 public override void WriteValue(Uri value)
 {
     base.WriteValue(value);
     AddValue(value, JsonToken.String);
 }
コード例 #57
0
 internal AsyncRequestString SetUrl(Uri url)
 {
     this.url = url;
     return(this);
 }
コード例 #58
0
        internal IEnumerator Start()
        {
            WWW www;

            if (this.method == HttpMethod.GET)
            {
                string urlParams = this.url.AbsoluteUri.Contains("?") ? "&" : "?";
                if (this.formData != null)
                {
                    foreach (KeyValuePair <string, string> pair in this.formData)
                    {
                        urlParams += string.Format("{0}={1}&", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value));
                    }
                }

                Dictionary <string, string> headers = new Dictionary <string, string>();

                headers["User-Agent"] = Constants.GraphApiUserAgent;

                www = new WWW(this.url + urlParams, null, headers);
            }
            else
            {
                // POST or DELETE
                if (this.query == null)
                {
                    this.query = new WWWForm();
                }

                if (this.method == HttpMethod.DELETE)
                {
                    this.query.AddField("method", "delete");
                }

                if (this.formData != null)
                {
                    foreach (KeyValuePair <string, string> pair in this.formData)
                    {
                        this.query.AddField(pair.Key, pair.Value);
                    }
                }

                this.query.headers["User-Agent"] = Constants.GraphApiUserAgent;
                www = new WWW(this.url.AbsoluteUri, this.query);
            }

            yield return(www);

            if (this.callback != null)
            {
                this.callback(new GraphResult(www));
            }

            // after the callback is called, www should be able to be disposed
            www.Dispose();
            MonoBehaviour.Destroy(this);
        }
コード例 #59
0
 public static Task<string> Post(this IWebClient client, WebHeaderCollection headers, Uri address, string data)
 {
     if (client == null) throw new ArgumentNullException("client");
     return client.Post(headers, address, data, (responseHeaders, r) => responseHeaders["Location"]);
 }
コード例 #60
0
 internal Transfer(IRestfulClient restfulClient, TransferResource resource, Uri baseUri, Uri resourceUri, AudioVideoCall parent)
     : base(restfulClient, resource, baseUri, resourceUri, parent)
 {
     if (parent == null)
     {
         throw new ArgumentNullException(nameof(parent), "AudioVideo is required");
     }
     m_transferCompleteTcs = new TaskCompletionSource <string>();
 }