Example #1
0
		public WebXlob(string uri, NameValueCollection customHeaders, ICredentials credentials)
		{
			if (uri == null) throw new ArgumentNullException("uri");
			this.uri = new Uri(uri);
			this.headers = customHeaders;
			this.credentials = credentials;
		}
        public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials)
        {
            if (serviceUrl == null)
            {
                throw new ArgumentNullException("serviceUrl");
            }

            // Set up our own HttpClientHandler and configure it
            HttpClientHandler clientHandler = new HttpClientHandler();

            if (credentials != null)
            {
                // Set up credentials cache which will handle basic authentication
                CredentialCache credentialCache = new CredentialCache();

                // Get base address without terminating slash
                string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);

                // Add credentials to cache and associate with handler
                NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
                credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
                clientHandler.Credentials = credentialCache;
                clientHandler.PreAuthenticate = true;
            }

            // Our handler is ready
            return clientHandler;
        }
Example #3
0
 public void SetUp()
 {
     _successor = MockRepository.GenerateStub<IHandler>();
     _handler = new OptionsHandler(_successor);
     _endpointDetails = MockRepository.GenerateStub<IEndpointDetails>();
     _credentials = MockRepository.GenerateStub<ICredentials>();
 }
Example #4
0
 public BuildFetcher(String serverAddress, String projectName, ICredentials credentials)
 {
     this.projectName = projectName;
     tfsServer = new TeamFoundationServer(serverAddress, credentials);
     tfsServer.Authenticate();
     buildServer = (IBuildServer) tfsServer.GetService(typeof (IBuildServer));
 }
		public RavenCountersClient(string serverUrl, string counterStorageName, ICredentials credentials = null, string apiKey = null)
        {
            try
            {
                ServerUrl = serverUrl;
                if (ServerUrl.EndsWith("/"))
                    ServerUrl = ServerUrl.Substring(0, ServerUrl.Length - 1);

				CounterStorageName = counterStorageName;
                Credentials = credentials ?? CredentialCache.DefaultNetworkCredentials;
                ApiKey = apiKey;

				convention = new CounterConvention();
                //replicationInformer = new RavenFileSystemReplicationInformer(convention, JsonRequestFactory);
                //readStripingBase = replicationInformer.GetReadStripingBase();
	            //todo: implement remote counter changes
                //notifications = new RemoteFileSystemChanges(serverUrl, apiKey, credentials, jsonRequestFactory, convention, replicationInformer, () => { });
                               
                InitializeSecurity();
            }
            catch (Exception)
            {
                Dispose();
                throw;
            }
        }
 public IPromise<string> Login(ICredentials credentials, bool async)
 {
   _lastCredentials = credentials;
   var mapping = _mappings.First(m => m.Databases.Contains(credentials.Database));
   _current = mapping.Connection;
   return _current.Login(credentials, async);
 }
        public static void SetupEnvironment(string url,
            ICredentials credentials,
            string path)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentException("url");

            if (string.IsNullOrEmpty(path))
                throw new ArgumentException("path");

            ReportingService2010 service = ReportingService2010TestEnvironment.GetReportingService(url, credentials);

            if (ReportingService2010TestEnvironment.ItemExists(service, path, "Folder"))
                service.DeleteItem(path);

            // Create the parent (base) folder where the integration tests will be written to (e.g. /DEST_SSRSMigrate_Tests)
            ReportingService2010TestEnvironment.CreateFolderFromPath(service, path);

            // Create folder structure
            ReportingService2010TestEnvironment.CreateFolders(service, path);

            // Create the the data sources
            ReportingService2010TestEnvironment.CreateDataSources(service, path);

            // Create the the reports
            //ReportingService2010TestEnvironment.CreateReports(service, path);
        }
 /// <summary>
 /// Modifies the request to ensure that the authentication requirements are met.
 /// </summary>
 /// <param name="client">Client executing this request</param>
 /// <param name="request">Request to authenticate</param>
 /// <param name="credentials">The credentials used for the authentication</param>
 /// <returns>The task the authentication is performed on</returns>
 public override async Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials)
 {
     // When the authorization failed or when the Authorization header is missing, we're just adding it (again) with the
     // new AccessToken.
     var authHeader = $"{_tokenType} {await Client.GetCurrentToken()}";
     request.SetAuthorizationHeader(AuthHeader.Www, authHeader);
 }
 public void Login(ICredentials credentials)
 {
   _lastCredentials = credentials;
   var mapping = _mappings.First(m => m.Databases.Contains(credentials.Database));
   _current = mapping.Connection;
   _current.Login(credentials);
 }
Example #10
0
        /// <summary>
        /// Make a web request to the given URL using the given credentials, and download the response into a file.
        /// </summary>
        /// <param name="uri">download url</param>
        /// <param name="cred">credentials to access url</param>
        /// <param name="path">file path</param>
        public static void Download(Uri uri, ICredentials cred, string path)
        {
            var request = (HttpWebRequest) WebRequest.Create(uri);
            request.Timeout = 60*1000;
            request.Method = "GET";
            request.KeepAlive = true;
            request.Credentials = cred;

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse) request.GetResponse();
                using (Stream rcvd = response.GetResponseStream())
                {
                    using (FileStream store = File.Create(path))
                    {
                        int n = 64*1024;
                        var buf = new byte[n];
                        while ((n = rcvd.Read(buf, 0, n)) > 0)
                        {
                            store.Write(buf, 0, n);
                        }
                    }
                }
            }
            finally
            {
                if (response != null) response.Close();
            }
        }
Example #11
0
		public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials) 
		{
			if (authObject == null)
				return null;

			return authObject.Authenticate (challenge, webRequest, credentials);
		}
        /// <summary>
        /// Retrieves the latest changeset ID associated with a path
        /// </summary>
        /// <param name="localPath">A path on the local filesystem</param>
        /// <param name="credentials">Credentials used to authenticate against the serer</param>
        /// <returns></returns>
        public int GetLatestChangesetId(string localPath, ICredentials credentials)
        {
            int latestChangesetId = 0;
            string server;

            Workstation workstation = new Workstation(versionControlClientAssembly);
            WorkspaceInfo workspaceInfo = workstation.GetLocalWorkspaceInfo(localPath);
            server = workspaceInfo.ServerUri.ToString();
            VersionControlServer sourceControl = new VersionControlServer(clientAssembly, versionControlClientAssembly, server, credentials);

            Workspace workspace = sourceControl.GetWorkspace(localPath);
            WorkspaceVersionSpec workspaceVersionSpec = new WorkspaceVersionSpec(versionControlClientAssembly, workspace);

            VersionSpec versionSpec = new VersionSpec(versionControlClientAssembly);
            RecursionType recursionType = new RecursionType(versionControlClientAssembly);

            IEnumerable history = sourceControl.QueryHistory(localPath, versionSpec.Latest, recursionType.Full, workspaceVersionSpec);

            IEnumerator historyEnumerator = history.GetEnumerator();
            Changeset latestChangeset = new Changeset(versionControlClientAssembly);
            if (historyEnumerator.MoveNext())
            {
                latestChangeset = new Changeset(versionControlClientAssembly, historyEnumerator.Current);
            }

            if (latestChangeset.Instance != null)
            {
                latestChangesetId = latestChangeset.ChangesetId;
            }
            return latestChangesetId;
        }
        public ClientConnectionManager(HazelcastClient client)
        {
            _client = client;

            var config = client.GetClientConfig();

            _networkConfig = config.GetNetworkConfig();

            config.GetNetworkConfig().IsRedoOperation();
            _credentials = config.GetCredentials();

            //init socketInterceptor
            var sic = config.GetNetworkConfig().GetSocketInterceptorConfig();
            if (sic != null && sic.IsEnabled())
            {
                //TODO Socket interceptor
                throw new NotImplementedException("Socket Interceptor not yet implemented.");
            }
            _socketInterceptor = null;

            var timeout = EnvironmentUtil.ReadEnvironmentVar("hazelcast.client.invocation.timeout.seconds");
            if (timeout > 0)
            {
                ThreadUtil.TaskOperationTimeOutMilliseconds = timeout.Value*1000;
            }

            _heartbeatTimeout = EnvironmentUtil.ReadEnvironmentVar("hazelcast.client.heartbeat.timeout") ??
                                _heartbeatTimeout;
            _heartbeatInterval = EnvironmentUtil.ReadEnvironmentVar("hazelcast.client.heartbeat.interval") ??
                                 _heartbeatInterval;
        }
Example #14
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="convention">The convention.</param>
		/// <param name="credentials">The credentials.</param>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory)
		{
			this.url = url;
			this.jsonRequestFactory = jsonRequestFactory;
			this.convention = convention;
			this.credentials = credentials;
		}
Example #15
0
 public ArcGISLegendResponse GetLegendInfo(string serviceUrl, ICredentials credentials = null)
 {
     _webRequest = CreateRequest(serviceUrl, credentials);
     var response = _webRequest.GetSyncResponse(_timeOut);
     _legendResponse = GetLegendResponseFromWebresponse(response);
     return _legendResponse;
 }
        public void Login(ICredentials credentials, Action<IStatus> onCompleteCallback)
        {
            if (credentials.Service.OAuth == null)
            {
                credentials.Service
                    .Login(
                        credentials.UserName,
                        credentials.Password,
                        status =>
                        {
                            if (status.Success)
                            {
                                _isSignedOn = true;
                                Accounts.Add(credentials);
                            }

                            if (onCompleteCallback == null)
                                return;

                            onCompleteCallback(status);
                        });    
            }
            else
            {
                var status = new Status {Success = credentials.Service.OAuth.IsValid};
                
                onCompleteCallback(status);
            }
        }
Example #17
0
		static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials)
		{
			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null || credentials == null)
				return null;

			NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			if (userName == null || userName == "")
				return null;

			string password = cred.Password;
			string domain = cred.Domain;
			byte [] bytes;

			// If domain is set, MS sends "domain\user:password". 
			if (domain == null || domain == "" || domain.Trim () == "")
				bytes = GetBytes (userName + ":" + password);
			else
				bytes = GetBytes (domain + "\\" + userName + ":" + password);

			string auth = "Basic " + Convert.ToBase64String (bytes);
			return new Authorization (auth);
		}
        private Stream GetNonFileStream( Uri uri, ICredentials credentials ) {
            WebRequest req = WebRequest.Create( uri );
            if ( credentials != null ) {
                req.Credentials = credentials;
            }
            WebResponse resp = req.GetResponse();
            HttpWebRequest webReq = req as HttpWebRequest;
            if ( webReq != null ) {
                lock ( this ) {
                    if ( connections == null ) {
                        connections = new Hashtable();
                    }
                    OpenedHost openedHost = (OpenedHost)connections[webReq.Address.Host];
                    if ( openedHost == null ) {
                        openedHost = new OpenedHost();
                    }

                    if ( openedHost.nonCachedConnectionsCount < webReq.ServicePoint.ConnectionLimit - 1 ) {
                        // we are not close to connection limit -> don't cache the stream
                        if ( openedHost.nonCachedConnectionsCount == 0 ) {
                            connections.Add( webReq.Address.Host, openedHost );
                        }
                        openedHost.nonCachedConnectionsCount++;
                        return new XmlRegisteredNonCachedStream( resp.GetResponseStream(), this, webReq.Address.Host );
                    }
                    else {
                        // cache the stream and save the connection for the next request
                        return new XmlCachedStream( resp.ResponseUri, resp.GetResponseStream() );
                    }
                }
            }
            else {
                return resp.GetResponseStream();
            }
        }
Example #19
0
        /// <summary>
        /// To be called by a deriving class when a request is being executed. This method defines the
        /// basic workflow of an HTTP REST, which can be customized by a deriving class via virtual
        /// method overrides
        /// </summary>
        /// <param name="url">HTTP URL of the request</param>
        /// <param name="credentials">Credentials to use for the HTTP request. This parameter is optional
        /// and null can be passed in if there's no credentials</param>
        protected void SendRequest( string          url,
                                    ICredentials    credentials )
        {
            try
            {
                ServicePointManager.Expect100Continue = false;

                _httpRequest = (HttpWebRequest)WebRequest.Create( url );
                _httpRequest.Credentials = credentials;
                _httpRequest.Method = GetHttpMethod();

                FillInHttpRequest( _httpRequest );

                AddBodyToRequest( GetRequestBody() );

                var response = (HttpWebResponse)_httpRequest.GetResponse();

                HandleResponse( response, response.GetResponseStream() );

                response.Close();
            }
            catch( WebException ex )
            {
                HandleHttpFailure( ex );
            }
        }
Example #20
0
        public static TfsConnection GetTfsConfigurationServer(string uri, ICredentials credentials)
        {
            // constructor
            var tfsMock = _getTfsMock(uri, credentials);

            return tfsMock.Object;
        }
Example #21
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanismLogin"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new LOGIN SASL context.
		/// </remarks>
		/// <param name="uri">The URI of the service.</param>
		/// <param name="encoding">The encoding to use for the user's credentials.</param>
		/// <param name="credentials">The user's credentials.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="uri"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="encoding"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="credentials"/> is <c>null</c>.</para>
		/// </exception>
		public SaslMechanismLogin (Uri uri, Encoding encoding, ICredentials credentials) : base (uri, credentials)
		{
			if (encoding == null)
				throw new ArgumentNullException (nameof (encoding));

			this.encoding = encoding;
		}
Example #22
0
        public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials, bool useCookies = false)
        {
            if (serviceUrl == null)
            {
                throw new ArgumentNullException("serviceUrl");
            }

            // Set up our own HttpClientHandler and configure it
            HttpClientHandler clientHandler = new HttpClientHandler();

            if (credentials != null)
            {
                // Set up credentials cache which will handle basic authentication
                CredentialCache credentialCache = new CredentialCache();

                // Get base address without terminating slash
                string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);

                // Add credentials to cache and associate with handler
                NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
                credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
                clientHandler.Credentials = credentialCache;
                clientHandler.PreAuthenticate = true;
            }

            // HttpClient's default UseCookies is true (meaning always roundtripping cookie back)
            // However, our api will default to false to cover multiple instance scenarios
            clientHandler.UseCookies = useCookies;

            // Our handler is ready
            return clientHandler;
        }
Example #23
0
 public WebXlob(Uri uri, NameValueCollection customHeaders, ICredentials credentials)
 {
     if (uri == null) throw new ArgumentNullException("uri");
     _uri = uri;
     _headers = customHeaders;
     _credentials = credentials;
 }
        /// <summary>
        /// Sends a get request to the server
        /// </summary>
        public string NewGetRequest(string method, IDictionary<string, string> keyValues, ICredentials credentials)
        {
            StringBuilder url = new StringBuilder();
            url.Append(_baseUrl);
            url.Append(method);
            url.Append("?");

            bool first = true;
            foreach (string key in keyValues.Keys)
            {
                if (!first)
                    url.Append("&");
                url.Append(key);
                url.Append("=");
                url.Append(keyValues[key]);
                first = false;
            }

            HttpWebRequest request = WebRequest.Create(url.ToString()) as HttpWebRequest;

            if (credentials != null)
                request.Credentials = credentials;

            // Get response
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output
                return reader.ReadToEnd();
            }
        }
Example #25
0
        public void FixtureSetUp()
        {
            tfsUrl = Environment.GetEnvironmentVariable("TFS_URL");
            if (String.IsNullOrEmpty(tfsUrl))
                {
                    Console.WriteLine("Warning: Environment variable TFS_URL not set.");
                    Console.WriteLine("					Some tests cannot be executed without TFS_URL.");
                    return;
                }

            string username = Environment.GetEnvironmentVariable("TFS_USERNAME");
            if (String.IsNullOrEmpty(username))
                {
                    Console.WriteLine("Warning: No TFS user credentials specified.");
                    return;
                }

            credentials = new NetworkCredential(username,
                                                                                    Environment.GetEnvironmentVariable("TFS_PASSWORD"),
                                                                                    Environment.GetEnvironmentVariable("TFS_DOMAIN"));

            // need TFS_ envvars for this test
            if (String.IsNullOrEmpty(tfsUrl)) return;
            TeamFoundationServer tfs = new TeamFoundationServer(tfsUrl, credentials);
            versionControlServer = (VersionControlServer) tfs.GetService(typeof(VersionControlServer));

            workspace = versionControlServer.CreateWorkspace("WorkspaceTest",
                                                                            Environment.GetEnvironmentVariable("TFS_USERNAME"));
        }
Example #26
0
 internal void PreAuthIfNeeded(HttpWebRequest httpWebRequest, ICredentials authInfo) {
     //
     // attempt to do preauth, if needed
     //
     GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() TriedPreAuth:" + TriedPreAuth.ToString() + " authInfo:" + ValidationHelper.HashString(authInfo));
     if (!TriedPreAuth) {
         TriedPreAuth = true;
         if (authInfo!=null) {
             PrepareState(httpWebRequest);
             Authorization preauth = null;
             try {
                 preauth = AuthenticationManager.PreAuthenticate(httpWebRequest, authInfo);
                 GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() preauth:" + ValidationHelper.HashString(preauth));
                 if (preauth!=null && preauth.Message!=null) {
                     GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() setting TriedPreAuth to Complete:" + preauth.Complete.ToString());
                     UniqueGroupId = preauth.ConnectionGroupId;
                     httpWebRequest.Headers.Set(AuthorizationHeader, preauth.Message);
                 }
             }
             catch (Exception exception) {
                 GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() PreAuthenticate() returned exception:" + exception.Message);
             }
         }
     }
 }
Example #27
0
		public static HttpWebRequest ToRequest(this string url, IDictionary<string, string> operationsHeaders, ICredentials credentials, string verb)
		{
			var request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create( url.ToUri() );
			request.WithOperationHeaders(operationsHeaders);
			request.Method = verb;
			return request;
		}
        public Stream GetStream(Uri uri, ICredentials credentials, int? timeout, int? byteLimit)
        {
            WebRequest request = WebRequest.Create(uri);
#if !PORTABLE
            if (timeout != null)
                request.Timeout = timeout.Value;
#endif

            if (credentials != null)
                request.Credentials = credentials;

            WebResponse response;

#if PORTABLE
            Task<WebResponse> result = Task.Factory.FromAsync(
                request.BeginGetResponse,
                new Func<IAsyncResult, WebResponse>(request.EndGetResponse), null);
            result.ConfigureAwait(false);

            response = result.Result;
#else
            response = request.GetResponse();
#endif

            Stream responseStream = response.GetResponseStream();
            if (timeout != null)
                responseStream.ReadTimeout = timeout.Value;

            if (byteLimit != null)
                return new LimitedStream(responseStream, byteLimit.Value);

            return responseStream;
        }
Example #29
0
        // ===========================================================================================================
        /// <summary>
        /// Launches the current sequence by executing all it's templates 
        /// </summary>
        /// <param name="credentials">The credentials required for creating the client context</param>
        /// <param name="templateProvider">The <b>XMLTemplatePRovider</b> that is mapped to the client's working directory</param>
        // ===========================================================================================================
        public void Launch(ICredentials credentials, XMLTemplateProvider templateProvider)
        {
            if(!this.Ignore)
            {
                logger.Info("Launching sequence '{0}' ({1})", this.Name, this.Description);

                using (ClientContext ctx = new ClientContext(this.WebUrl))
                {
                    // --------------------------------------------------
                    // Sets the context with the provided credentials
                    // --------------------------------------------------
                    ctx.Credentials = credentials;
                    ctx.RequestTimeout = Timeout.Infinite;

                    // --------------------------------------------------
                    // Loads the full web for futur references (providers)
                    // --------------------------------------------------
                    Web web = ctx.Web;
                    ctx.Load(web);
                    ctx.ExecuteQueryRetry();

                    // --------------------------------------------------
                    // Launches the templates
                    // --------------------------------------------------
                    foreach (Template template in this.Templates)
                    {
                        template.Apply(web, templateProvider);
                    }
                }
            }
            else
            {
                logger.Info("Ignoring sequence '{0}' ({1})", this.Name, this.Description);
            }
        }
Example #30
0
		public static IEnumerable<XElement> GetSearchResult(string SearchQuery, int PageSize, int PageCount, string SearchServiceUrl, string Scope, ICredentials Credentials)
		{
			var query = @"SELECT WorkId,Rank,Title,Author,Size,Path,Write,HitHighlightedSummary FROM Scope() WHERE freetext('" + SearchQuery.Replace('\'', ' ') + @"')";
			if (!string.IsNullOrEmpty(Scope))
			{
				query = query + string.Format(@"AND ""Scope""='{0}'", Scope);
			}

			XNamespace ns = "urn:Microsoft.Search.Query";
			XElement queryPacket = new XElement(ns + "QueryPacket",
				new XElement(ns + "Query",
					new XElement(ns + "Context",
						new XElement(ns + "QueryText",
							new XAttribute("language", CultureInfo.CurrentCulture.ToString()),
							new XAttribute("type", "MSSQLFT"),
								query
							)
						), new XElement(ns + "TrimDuplicates", false),
						new XElement(ns + "Range",
							new XElement(ns + "StartAt", (PageCount - 1) * PageSize + 1),
							new XElement(ns + "Count", PageSize)
						)
					)
				);

			QueryService queryService = new QueryService();
			queryService.Url = SearchServiceUrl;
			queryService.Credentials = Credentials;
			string queryResultsString = queryService.Query(queryPacket.ToString());

			return new List<XElement>() {
				XElement.Parse(CleanInvalidXmlChars(queryResultsString))
			};
		}
Example #31
0
 public Connection(Uri url, NetworkCredential networkCredential)
 {
     Url        = url;
     Credential = networkCredential;
 }
 public DummyModuleIdentityLifecycleManager(string hostName, string gatewayHostname, string deviceId, string moduleId, ICredentials credentials)
 {
     this.hostName        = hostName;
     this.gatewayHostname = gatewayHostname;
     this.deviceId        = deviceId;
     this.moduleId        = moduleId;
     this.credentials     = credentials;
 }
Example #33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebCredentials"/> class using
        /// specified credentials.
        /// </summary>
        /// <param name="credentials">Credentials to use.</param>
        public WebCredentials(ICredentials credentials)
        {
            EwsUtilities.ValidateParam(credentials, "credentials");

            this.credentials = credentials;
        }
 protected HttpWebResponse PostEvent <T>(T data, ICredentials credentials = null)
 {
     return(MakeArrayEventsPost(
                TestStream, new[] { new { EventId = Guid.NewGuid(), EventType = "event-type", Data = data } }, credentials));
 }
Example #35
0
 public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
     : this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials)
 {
 }
Example #36
0
        private async Task CreateAndValidateRequest(HttpClientHandler handler, Uri url, HttpStatusCode expectedStatusCode, ICredentials credentials)
        {
            handler.Credentials = credentials;

            using (HttpClient client = CreateHttpClient(handler))
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    Assert.Equal(expectedStatusCode, response.StatusCode);
                }
        }
Example #37
0
 public NoBypassWebProxy(Uri uri, ICredentials credentials = null)
 {
     _uri        = uri ?? throw new ArgumentNullException(nameof(uri));
     Credentials = credentials ?? new NetworkCredential("", "");
 }
Example #38
0
 private static IAsyncDatabaseCommands SetupCommandsAsync(IAsyncDatabaseCommands databaseCommands, string database, ICredentials credentialsForSession, OpenSessionOptions options)
 {
     if (database != null)
     {
         databaseCommands = databaseCommands.ForDatabase(database);
     }
     if (credentialsForSession != null)
     {
         databaseCommands = databaseCommands.With(credentialsForSession);
     }
     if (options.ForceReadFromMaster)
     {
         databaseCommands.ForceReadFromMaster();
     }
     return(databaseCommands);
 }
Example #39
0
 public Stream GetStream(Uri uri, ICredentials credentials, int?timeout, int?byteLimit)
 {
     throw new Exception("Could not find");
 }
Example #40
0
 public Connection(Uri url, string username, string password)
 {
     Url        = url;
     Credential = new NetworkCredential(username, password);
 }
Example #41
0
        /// <summary>
        /// Метод отправки коллекции писем
        /// </summary>
        /// <param name="messages">коллекция писем для отправки  - объектов типа MailMessage</param>
        /// <param name="sMailBoxUrl">url почтого ящика с которого отправляется письмо, например http://dm.croc.ru/exchange/DAlexandrov</param>
        public static void Send(ICollection messages, string sMailBoxUrl, int nTimeout, ICredentials credentials)
        {
            if (0 == messages.Count)
            {
                return;
            }

            string        draftsUrl     = sMailBoxUrl + "/drafts/";
            StringBuilder mailToDeliver = new StringBuilder();

            mailToDeliver.Append("<?xml version=\"1.0\"?><D:move xmlns:D=\"DAV:\"><D:target>");
            WebDAVRequest req;

            foreach (MailMessage m in messages)
            {
                ///
                string mailUrl = draftsUrl + Guid.NewGuid().ToString("N") + ".eml";
                req = WebDAVRequest.Create(WebDAVMethods.PROPPATCH, mailUrl, m.ToXmlByteArray(), credentials);
                req.SetTimeout(nTimeout);
                req.Send();
                mailToDeliver.AppendFormat("<D:href>{0}</D:href>", mailUrl);
                ///
            }


            mailToDeliver.Append("</D:target></D:move>");

            ///
            byte[] data = Encoding.UTF8.GetBytes(mailToDeliver.ToString());
            req = WebDAVRequest.Create(WebDAVMethods.BMOVE, draftsUrl, credentials);
            req.SetTimeout(nTimeout);
            req.AddHeader("Destination", sMailBoxUrl + "/##DavMailSubmissionURI##/");
            req.AddHeader("Saveinsent", "f");
            req.WriteContent(data);
            req.Send();
        }
Example #42
0
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, ICredentials existingCredentials, bool retrying)
        {
            bool result = false;

            DispatchService.GuiSyncDispatch(() => {
                using (var ns = new NSAutoreleasePool()) {
                    var message = string.Format("{0} needs {1} credentials to access {2}.", BrandingService.ApplicationName,
                                                credentialType == CredentialType.ProxyCredentials ? "proxy" : "request", uri.Host);

                    NSAlert alert = NSAlert.WithMessage("Credentials Required", "OK", "Cancel", null, message);
                    alert.Icon    = NSApplication.SharedApplication.ApplicationIconImage;

                    NSView view = new NSView(new RectangleF(0, 0, 313, 91));

                    var creds = Utility.GetCredentialsForUriFromICredentials(uri, existingCredentials);

                    var usernameLabel = new NSTextField(new RectangleF(17, 55, 71, 17))
                    {
                        Identifier      = "usernameLabel",
                        StringValue     = "Username:"******"Password:",
                        Alignment       = NSTextAlignment.Right,
                        Editable        = false,
                        Bordered        = false,
                        DrawsBackground = false,
                        Bezeled         = false,
                        Selectable      = false,
                    };
                    view.AddSubview(passwordLabel);

                    var passwordInput         = new NSSecureTextField(new RectangleF(93, 20, 200, 22));
                    passwordInput.StringValue = creds != null ? creds.Password : string.Empty;
                    view.AddSubview(passwordInput);

                    alert.AccessoryView = view;
                    result = alert.RunModal() == 1;

                    username = usernameInput.StringValue;
                    password = passwordInput.StringValue;
                }
            });

            return(result ? new NetworkCredential(username, password) : null);
        }
 /// <summary>
 /// Adds an <c>Authenticator</c> to the <c>RestSharp.RestClient</c>.
 /// </summary>
 /// <remarks>
 /// Authenticators are used to interact with the DNSimple API. They can
 /// be either HTTPBasic (email and password) or OAuth2 tokens.
 /// </remarks>
 /// <param name="credentials">The credentials containing the authenticator to be used</param>
 /// <see cref="ICredentials"/>
 /// <see cref="RestSharp.Authenticators.IAuthenticator"/>
 public virtual void AddAuthenticator(ICredentials credentials) =>
 RestClient.Authenticator = credentials.Authenticator;
Example #44
0
            /// <summary>
            /// Методы формирования http-запроса
            /// </summary>
            public static WebDAVRequest Create(string sMethod, string sUrl, byte[] data, ICredentials credentials)
            {
                WebDAVRequest req = Create(sMethod, sUrl, credentials);

                req.WriteContent(data);
                return(req);
            }
 static void Save(ICredentials credentials, string pin);
 public Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
 {
     throw new NotImplementedException();
 }
Example #47
0
 public DeployManager(Uri urlToWeb, ICredentials credentials, bool isSharePointOnline)
 {
     _urlToWeb           = urlToWeb;
     _credentials        = credentials;
     _isSharePointOnline = isSharePointOnline;
 }
 static void Delete(ICredentials credentials);
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response          = null;
            ICredentials        promptCredentials = null;

            var configuration = request.GetOrCreateConfiguration();

            // Authorizing may take multiple attempts
            while (true)
            {
                // Clean up any previous responses
                if (response != null)
                {
                    response.Dispose();
                }

                // store the auth state before sending the request
                var beforeLockVersion = _credentials.Version;

                response = await base.SendAsync(request, cancellationToken);

                if (_credentialService == null)
                {
                    return(response);
                }

                if (response.StatusCode == HttpStatusCode.Unauthorized ||
                    (configuration.PromptOn403 && response.StatusCode == HttpStatusCode.Forbidden))
                {
                    IList <Stopwatch> stopwatches = null;

                    if (request.Properties.TryGetValue(HttpRetryHandler.StopwatchPropertyName, out var value))
                    {
                        stopwatches = value as IList <Stopwatch>;
                        if (stopwatches != null)
                        {
                            foreach (var stopwatch in stopwatches)
                            {
                                stopwatch.Stop();
                            }
                        }
                    }

                    promptCredentials = await AcquireCredentialsAsync(
                        response.StatusCode,
                        beforeLockVersion,
                        configuration.Logger,
                        cancellationToken);

                    if (stopwatches != null)
                    {
                        foreach (var stopwatch in stopwatches)
                        {
                            stopwatch.Start();
                        }
                    }

                    if (promptCredentials == null)
                    {
                        return(response);
                    }

                    continue;
                }

                if (promptCredentials != null)
                {
                    CredentialsSuccessfullyUsed(_packageSource.SourceUri, promptCredentials);
                }

                return(response);
            }
        }
Example #50
0
        /// <summary>
        /// Get response from the given uri with given credentials
        /// </summary>
        /// <param name="uri">uri</param>
        /// <param name="credentials">credentials</param>
        /// <param name="callbackFunc">callback function</param>
        public static void GetResponseAsync(String uri, Action <String> callbackFunc, ICredentials credentials = null)
        {
            if (uri == null || uri.Length == 0)
            {
                throw new Exception("Must supply valid URI!");
            }

            WebClient client = new WebClient(); WebRequest.Create(uri);

            if (credentials != null)
            {
                client.Credentials = credentials;
            }
            client.DownloadStringCompleted += (s, e) =>
            {
                callbackFunc(e.Result);
            };
            client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));
        }
Example #51
0
 public HttpClient CreateHttpClient(string endpoint, ICredentials credentials)
 {
     return(CreateHttpClient(endpoint, ClientFactory.CreateHttpClientHandler(endpoint, credentials)));
 }
 /// <summary>
 /// Sets the ProxyCredentials property.
 /// </summary>
 /// <param name="proxyCredentials">ProxyCredentials property</param>
 /// <returns>this instance</returns>
 public AmazonSimpleNotificationServiceConfig WithProxyCredentials(ICredentials proxyCredentials)
 {
     this.proxyCredentials = proxyCredentials;
     return(this);
 }
Example #53
0
        private void DownloadPackage(string packageId, NuGetVersion version, Uri feedUri, ICredentials feedCredentials, string cacheDirectory, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff, out LocalNuGetPackage downloaded, out string downloadedTo)
        {
            Log.Info("Downloading NuGet package {0} {1} from feed: '{2}'", packageId, version, feedUri);
            Log.VerboseFormat("Downloaded package will be stored in: '{0}'", cacheDirectory);
            fileSystem.EnsureDirectoryExists(cacheDirectory);
            fileSystem.EnsureDiskHasEnoughFreeSpace(cacheDirectory);

            var fullPathToDownloadTo = GetFilePathToDownloadPackageTo(cacheDirectory, packageId, version.ToString());

            var downloader = new NuGetPackageDownloader();

            downloader.DownloadPackage(packageId, version, feedUri, feedCredentials, fullPathToDownloadTo, maxDownloadAttempts, downloadAttemptBackoff);

            downloaded   = new LocalNuGetPackage(fullPathToDownloadTo);
            downloadedTo = fullPathToDownloadTo;
            CheckWhetherThePackageHasDependencies(downloaded.Metadata);
        }
 private void CredentialsSuccessfullyUsed(Uri uri, ICredentials credentials)
 {
     HttpHandlerResourceV3.CredentialsSuccessfullyUsed?.Invoke(uri, credentials);
 }
Example #55
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataClientSettings"/> class.
 /// </summary>
 /// <param name="baseUri">The URL address.</param>
 /// <param name="credentials">The client credentials.</param>
 public ODataClientSettings(string baseUri, ICredentials credentials = null)
 {
     this.BaseUri     = new Uri(baseUri);
     this.Credentials = credentials;
 }
Example #56
0
        public void DownloadPackage(string packageId, NuGetVersion version, string feedId, Uri feedUri, ICredentials feedCredentials, bool forcePackageDownload, int maxDownloadAttempts, TimeSpan downloadAttemptBackoff, out string downloadedTo, out string hash, out long size)
        {
            var cacheDirectory = GetPackageRoot(feedId);

            LocalNuGetPackage downloaded = null;

            downloadedTo = null;
            if (!forcePackageDownload)
            {
                AttemptToGetPackageFromCache(packageId, version, cacheDirectory, out downloaded, out downloadedTo);
            }

            if (downloaded == null)
            {
                DownloadPackage(packageId, version, feedUri, feedCredentials, cacheDirectory, maxDownloadAttempts, downloadAttemptBackoff, out downloaded, out downloadedTo);
            }
            else
            {
                Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloadedTo);
            }

            size = fileSystem.GetFileSize(downloadedTo);
            string packageHash = null;

            downloaded.GetStream(stream => packageHash = HashCalculator.Hash(stream));
            hash = packageHash;
        }
Example #57
0
 /// <summary>
 /// Returns a new <see cref="IDatabaseCommands"/> using the specified credentials
 /// </summary>
 /// <param name="credentialsForSession">The credentials for session.</param>
 /// <returns></returns>
 public IDatabaseCommands With(ICredentials credentialsForSession)
 {
     return(new ServerClient((AsyncServerClient)asyncServerClient.With(credentialsForSession)));            //TODO This cast is bad
 }
Example #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataClientSettings"/> class.
 /// </summary>
 /// <param name="baseUri">The URL address.</param>
 /// <param name="credentials">The client credentials.</param>
 public ODataClientSettings(Uri baseUri, ICredentials credentials = null)
 {
     this.BaseUri     = baseUri;
     this.Credentials = credentials;
 }
Example #59
0
 /// <summary>
 /// Create an instance of the specified SASL mechanism using the uri and credentials.
 /// </summary>
 /// <remarks>
 /// If unsure that a particular SASL mechanism is supported, you should first call
 /// <see cref="IsSupported"/>.
 /// </remarks>
 /// <returns>An instance of the requested SASL mechanism if supported; otherwise <c>null</c>.</returns>
 /// <param name="mechanism">The name of the SASL mechanism.</param>
 /// <param name="uri">The URI of the service to authenticate against.</param>
 /// <param name="credentials">The user's credentials.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="mechanism"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="uri"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="credentials"/> is <c>null</c>.</para>
 /// </exception>
 public static SaslMechanism Create(string mechanism, Uri uri, ICredentials credentials)
 {
     return(Create(mechanism, uri, Encoding.UTF8, credentials));
 }
Example #60
0
 /// <summary>
 ///     Authenticate by impersonation, using an existing <c>ICredentials</c> instance
 /// </summary>
 /// <param name="credentials"></param>
 public NtlmAuthenticator(ICredentials credentials) => this.credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));