コード例 #1
0
        private void AuthenticateUser(Uri uri, string authenticationType)
        {
            DiscoveryNetworkCredential credential = (DiscoveryNetworkCredential)_credentialCache.GetCredential(uri, authenticationType);

            if (credential != null)
            {
                StartDiscovery(uri, credential);
            }
            else
            {
                using (UserCredentialsDialog credentialsForm = new UserCredentialsDialog(uri.ToString(), authenticationType))
                {
                    if (DialogResult.OK == credentialsForm.ShowDialog())
                    {
                        StartDiscovery(uri, credentialsForm.Credential);
                    }
                }
            }
        }
コード例 #2
0
        public static CredentialCache getConnectionCredentials(string Url)
        {
            CredentialCache myCredentials = new CredentialCache();

            if (myCredentials.GetCredential(new Uri(Url), "Basic") == null)
            {
                myCredentials.Add(new Uri(Url), "Basic", netCred);
            }
            return(myCredentials);
        }
コード例 #3
0
        /// <summary>
        /// generic request class with digest authentication
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetRequest(string url)
        {
            int  counter = 0;
            bool status  = false;
            var  result  = "";

            while (counter < 3 && status == false)
            {
                try
                {
                    var url_tmp = url;

                    //add credentials to request
                    var credCache = new CredentialCache();
                    var cred      = new NetworkCredential("admin", "abb");
                    credCache.Add(new Uri(url), AuthenticationSchemes.Digest.ToString(), new NetworkCredential("admin", "abb"));
                    NativeMessageHandler nativeHandler = new NativeMessageHandler();
                    nativeHandler.Credentials = credCache.GetCredential(new Uri(url), AuthenticationSchemes.Digest.ToString());
                    var handler = new HttpClientHandler();
                    handler.PreAuthenticate = true;
                    handler.Credentials     = credCache.GetCredential(new Uri(url), "Digest");
                    var client = new HttpClient(nativeHandler);
                    //set timeout for Request
                    client.Timeout = new TimeSpan(0, 0, 10);
                    var answer = client.GetAsync(new Uri(url));
                    if (answer.Result.StatusCode == HttpStatusCode.OK)
                    {
                        status = true;
                    }
                    Debug.WriteLine("------------------------->" + answer.Result);
                    Debug.WriteLine("***********************************************************************************");
                    result = answer.Result.Content.ReadAsStringAsync().Result;
                    Debug.WriteLine("json: " + result);

                    counter++;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }
            }
            return(result);
        }
コード例 #4
0
        public static void GetCredential_SimilarUriAuthenticationType_GetLongestUriPrefix()
        {
            CredentialCache cc = new CredentialCache();

            cc.Add(new Uri("http://microsoft:80/greaterpath"), authenticationType1, credential2);
            cc.Add(new Uri("http://microsoft:80/"), authenticationType1, credential1);

            NetworkCredential nc = cc.GetCredential(new Uri("http://microsoft:80"), authenticationType1);

            Assert.Equal(nc, credential2);
        }
コード例 #5
0
        public static void GetCredential_HostPort(string host, int hostPortCount)
        {
            CredentialCache cc = CreateCredentialCache(uriCount: 0, hostPortCount: 0);

            foreach (var iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                {
                    cc.GetCredential(host, Port, AuthenticationType);
                }
            }
        }
コード例 #6
0
        public static void Add_HostPortAuthenticationTypeCredential_Success()
        {
            CredentialCache cc = HostPortAuthenticationTypeCredentialCache();

            Assert.Equal(credential1, cc.GetCredential(host1, port1, authenticationType1));
            Assert.Equal(credential2, cc.GetCredential(host1, port1, authenticationType2));
            Assert.Equal(credential3, cc.GetCredential(host1, port2, authenticationType1));
            Assert.Equal(credential4, cc.GetCredential(host1, port2, authenticationType2));

            Assert.Equal(credential5, cc.GetCredential(host2, port1, authenticationType1));
            Assert.Equal(credential6, cc.GetCredential(host2, port1, authenticationType2));
            Assert.Equal(credential7, cc.GetCredential(host2, port2, authenticationType1));
            Assert.Equal(credential8, cc.GetCredential(host2, port2, authenticationType2));
        }
コード例 #7
0
        public static void GetCredential_Uri(string uriString, int uriCount)
        {
            var             uri = new Uri(uriString);
            CredentialCache cc  = CreateCredentialCache(uriCount, hostPortCount: 0);

            foreach (var iteration in Benchmark.Iterations)
            {
                using (iteration.StartMeasurement())
                {
                    cc.GetCredential(uri, AuthenticationType);
                }
            }
        }
コード例 #8
0
ファイル: CredentialCacheTest.cs プロジェクト: jnm2/corefx
        public static void Add_HostPortAuthenticationTypeCredential_Invalid()
        {
            CredentialCache cc = CreateHostPortCredentialCache();

            Assert.Null(cc.GetCredential("invalid-host", port1, authenticationType1));                                                       //No such host
            Assert.Null(cc.GetCredential(host1, 900, authenticationType1));                                                                  //No such port
            Assert.Null(cc.GetCredential(host1, port1, "invalid-authentication-type"));                                                      //No such authenticationType

            AssertExtensions.Throws <ArgumentNullException>("host", () => cc.Add(null, 500, "authenticationType", new NetworkCredential())); //Null host
            AssertExtensions.Throws <ArgumentNullException>("authenticationType", () => cc.Add("host", 500, null, new NetworkCredential())); //Null authenticationType

            var exception = Record.Exception(() => cc.Add("", 500, "authenticationType", new NetworkCredential()));

            // On full framework we get exception.ParamName as null while it is "host" on netcore
            Assert.NotNull(exception);
            Assert.True(exception is ArgumentException);
            ArgumentException ae = exception as ArgumentException;

            Assert.True(ae.ParamName == "host" || ae.ParamName == null);

            AssertExtensions.Throws <ArgumentOutOfRangeException>("port", () => cc.Add("host", -1, "authenticationType", new NetworkCredential())); //Port < 0
        }
コード例 #9
0
ファイル: Crash2.xaml.cs プロジェクト: KhaledSMQ/SipServer
        private void CreateWebClient()
        {
            if (webClient == null)
            {
                CredentialCache credentialCache = new CredentialCache();
                credentialCache.Add(uploadUri, @"Basic", new NetworkCredential(@"uprep", @"qeiusroi123woi3zf"));

                webClient = new WebClient();
                webClient.UploadFileCompleted   += WebClient_UploadFileCompleted;
                webClient.UploadProgressChanged += WebClient_UploadProgressChanged;
                webClient.Credentials            = credentialCache.GetCredential(uploadUri, @"Basic");
                webClient.QueryString.Add("app", "MSG");
                webClient.QueryString.Add("ver", AssemblyInfo.AssemblyVersion);
            }
        }
コード例 #10
0
        public string Connect()
        {
            var username = ConfigurationManager.AppSettings["FS01UN"];
            var encryptedPassword = ConfigurationManager.AppSettings["FS01PS"];
            var password = encryptionProcessor.Decrypt(encryptedPassword, 1);
            var credentials = new NetworkCredential(username, password);
            var netCache = new CredentialCache { { "\\FS01", 80, "Basic", credentials } };
            var credential = netCache.GetCredential("\\FS01", 80, "Basic");
            if (credential == null)
                return string.Empty;

            var ping = new Ping();
            var reply = ping.Send("FS01", 1000);
            return reply?.Status == IPStatus.Success ? $"{reply.Address:x}" : string.Empty;
        }
コード例 #11
0
        public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
        {
            NetworkCredential creds = credentialCache.GetCredential(uri, "NTLM");

            if (creds != null)
            {
                return(creds);
            }

            string login = PromptForLogin(uri.ToString());

            creds = new TFCredential(login);

            credentialCache.Add(uri, "NTLM", creds);
            return(creds);
        }
コード例 #12
0
 public Auth(string rootSite,
             bool isSharepointOnline,
             string domain,
             string username,
             string password,
             string authScheme)
 {
     if (!isSharepointOnline)
     {
         NetworkCredential networkCredential;
         if (password == null && username != null)
         {
             Console.WriteLine("Please enter password for {0}", username);
             networkCredential = new NetworkCredential(username, GetPassword(), domain);
         }
         else if (username != null)
         {
             networkCredential = new NetworkCredential(username, password, domain);
         }
         else
         {
             networkCredential = CredentialCache.DefaultNetworkCredentials;
         }
         credentialsCache = new CredentialCache();
         credentialsCache.Add(new Uri(rootSite), authScheme, networkCredential);
         CredentialCache credentialCache = new CredentialCache {
             { Util.getBaseUrlHost(rootSite), Util.getBaseUrlPort(rootSite), authScheme, networkCredential }
         };
         httpHandler = new HttpClientHandler()
         {
             CookieContainer = new CookieContainer(),
             Credentials     = credentialCache.GetCredential(Util.getBaseUrlHost(rootSite), Util.getBaseUrlPort(rootSite), authScheme)
         };
     }
     else
     {
         SecureString securePassword = new SecureString();
         foreach (char c in password)
         {
             securePassword.AppendChar(c);
         }
         sharepointOnlineCredentials = new SharePointOnlineCredentials(username, securePassword);
         httpHandler = new HttpClientHandler();
         Uri rootSiteUri = new Uri(Util.getBaseUrl(rootSite));
         httpHandler.CookieContainer.SetCookies(rootSiteUri, sharepointOnlineCredentials.GetAuthenticationCookie(rootSiteUri));
     }
 }
コード例 #13
0
        protected override WebRequest GetWebRequest(Uri address)
        {
            if (null == _credentialCache.GetCredential(new Uri(address.GetLeftPart(UriPartial.Authority)), "Basic"))
            {
                _credentialCache.Add(new Uri(address.GetLeftPart(UriPartial.Authority)), "Basic", this._networkCredential);
            }

            var r   = base.GetWebRequest(address);
            var req = r as HttpWebRequest;

            if (null != req)
            {
                req.CookieContainer = _container;
            }

            return(r);
        }
コード例 #14
0
        private void SendReport()
        {
            try
            {
                var fileName = Path.GetTempFileName();
                File.WriteAllText(fileName, report, Encoding.Unicode);

                CredentialCache credentialCache = new CredentialCache();
                credentialCache.Add(uploadUri, @"Basic", new NetworkCredential(@"uprep", @"qeiusroi123woi3zf"));

                var webClient = new WebClient();
                webClient.Credentials = credentialCache.GetCredential(uploadUri, @"Basic");
                webClient.QueryString.Add("app", "SRV");
                webClient.QueryString.Add("ver", version.ToString());
                webClient.UploadFile(uploadUri, fileName);
            }
            catch
            {
            }
        }
コード例 #15
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <param name="domain">域</param>
        /// <param name="loginUrl">登录地址</param>
        /// <param name="IsLogin">不使用缓存,重新登录</param>
        public void LogLan(string userName, string passWord, string domain, string loginUrl = "", bool IsLogin = false)
        {
            if (string.IsNullOrEmpty(loginUrl))
            {
                loginUrl = LoginUrl;
            }
            else
            {
                LoginUrl = loginUrl;
            }

            HttpWebRequest  WRequest;
            HttpWebResponse WResponse;

            if (IsLogin)
            {
                myCredCache = null;
            }
            if (myCredCache == null)
            {
                myCredCache = new CredentialCache();
            }
            if (myCredCache.GetCredential(new Uri(LoginUrl), "NTLM") == null)
            {
                myCredCache.Add(new Uri(LoginUrl), "NTLM", new NetworkCredential(userName, passWord, domain));
                // Pre-authenticate the request.
                WRequest = (HttpWebRequest)HttpWebRequest.Create(LoginUrl);
                // Set the username and the password.
                WRequest.Credentials = myCredCache;
                // This property must be set to true for Kerberos authentication.

                // Keep the connection alive.

                WRequest.UserAgent = "Upload Test";
                WRequest.Method    = "HEAD";
                WRequest.Timeout   = 10000;
                WResponse          = (HttpWebResponse)WRequest.GetResponse();
                WResponse.Close();
            }
        }
コード例 #16
0
// <Snippet1>
    public static void GetPage(string url, string userName, string password, string domainName)
    {
        try
        {
            CredentialCache myCredentialCache = new CredentialCache();
            // Dummy names used as credentials.
            myCredentialCache.Add(new Uri("http://microsoft.com/"), "Basic", new NetworkCredential("user1", "passwd1", "domain1"));
            myCredentialCache.Add(new Uri("http://msdn.com/"), "Basic", new NetworkCredential("user2", "passwd2", "domain2"));
            myCredentialCache.Add(new Uri(url), "Basic", new NetworkCredential(userName, password, domainName));
            // Create a webrequest with the specified url.
            WebRequest myWebRequest = WebRequest.Create(url);
            // Call 'GetCredential' to obtain the credentials specific to our Uri.
            NetworkCredential myCredential = myCredentialCache.GetCredential(new Uri(url), "Basic");
            Display(myCredential);
            // Associating only our credentials.
            myWebRequest.Credentials = myCredential;
            // Sends the request and waits for response.
            WebResponse myWebResponse = myWebRequest.GetResponse();

            // Process response here.

            Console.WriteLine("\nResponse Received.");
            myWebResponse.Close();
        }
        catch (WebException e)
        {
            if (e.Response != null)
            {
                Console.WriteLine("\r\nFailed to obtain a response. The following error occurred : {0}", ((HttpWebResponse)(e.Response)).StatusDescription);
            }
            else
            {
                Console.WriteLine("\r\nFailed to obtain a response. The following error occurred : {0}", e.Status);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following exception was raised : {0}", e.Message);
        }
    }
コード例 #17
0
        /// <summary>
        /// </summary>
        /// <param name="host"></param>
        /// <param name="oauthToken"></param>
        public void AddOAuthCredentials(Uri host, string oauthToken)
        {
            Logging.Info("Adding OAuth Credentials");
            Logging.Debug("Host: {0}", new object[] { host });

            try
            {
                var existingCredentials = CredentialCache.GetCredential(host, "Bearer");
                if (existingCredentials != null)
                {
                    CredentialCache.Remove(host, "Bearer");
                }
            }
            catch (Exception exception)
            {
                Logging.Error(exception, "Failed to add OAuth credentials");
            }
            finally
            {
                CredentialCache.Add(host, "Bearer", new OAuth2Credential(oauthToken));
            }
        }
コード例 #18
0
 protected override void Send()
 {
     try
     {
         SmtpClient        client = new SmtpClient(mailserver, port);
         NetworkCredential myNC   = new NetworkCredential(Base.GetMailAccount(), Base.GetMailAccountPassword());
         CredentialCache   myCC   = new CredentialCache();
         myCC.Add(mailserver, port, "NTLM", myNC);
         if (Base.GetMailAccount() != "" && Base.GetMailAccountPassword() != "")
         {
             client.Credentials = myCC.GetCredential(mailserver, port, "NTLM");
         }
         else
         {
             client.Credentials = CredentialCache.DefaultNetworkCredentials;
         }
         client.Send(mail);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #19
0
        public bool ConnectToFs01(CurlDetails details)
        {
            var isUpdated          = false;
            var username           = ConfigurationManager.AppSettings["FS01UN"];
            var password           = ConfigurationManager.AppSettings["FS01PS"];
            var decrypted          = encryptionProcessor.Decrypt(password, 1);
            var networkCredentials = new NetworkCredential(username, decrypted, details.Domain);
            var netCache           = new CredentialCache {
                { "\\FS01", 80, "Basic", networkCredentials }
            };
            var credential = netCache.GetCredential("\\FS01", 80, "Basic");

            if (credential != null)
            {
                var ping  = new Ping();
                var reply = ping.Send("192.168.10.150", 100);
                if (reply?.Status == IPStatus.Success)
                {
                    isUpdated = true;
                }
            }

            return(isUpdated);
        }
コード例 #20
0
    // ICredentialsProvider method
    public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
    {
        NetworkCredential creds = credentialCache.GetCredential(uri, "NTLM");

        if (creds != null)
        {
            return(creds);
        }

        string url   = uri.ToString();
        string login = GetLogin(url);

        if (String.IsNullOrEmpty(login))
        {
            return(null);
        }
        creds = new TFCredential(login);

        if (!(String.IsNullOrEmpty(creds.UserName)) &&
            String.IsNullOrEmpty(creds.Password) && !Options.NoPrompt)
        {
            Console.Write("Password: "******"Credentials.Save");

        if (saveSetting && !String.IsNullOrEmpty(Options.Login))
        {
            Keyring.SetCredentials(url, creds.Domain, creds.UserName, creds.Password);
        }

        credentialCache.Add(uri, "NTLM", creds);
        return(creds);
    }
コード例 #21
0
        /// <summary>
        /// Similar to GetResponse(string uriArg), but uses a user/pw to log in.
        /// </summary>
        /// <param name="uriArg">e.g. "http://192.168.2.1"</param>
        /// <param name="userArg">e.g. "root"</param>
        /// <param name="pwArg">e.g. "admin"</param>
        /// <returns>string containing the http response.</returns>
        /// <example>
        /// // Example to get a response with DHCP table from my LinkSys router.
        /// string s = GetResponse( "http://192.168.2.1/DHCPTable.htm", "root", "admin" );
        /// </example>
        public static string GetResponse(string uriArg, string userArg, string pwArg)
        {
            var uri   = new Uri(uriArg);
            var req   = (HttpWebRequest)WebRequest.Create(uri);
            var creds = new CredentialCache();

            // See http://msdn.microsoft.com/en-us/library/system.directoryservices.protocols.authtype.aspx for list of types.
            const string authType = "basic";

            creds.Add(uri, authType, new NetworkCredential(userArg, pwArg));
            req.PreAuthenticate = true;
            req.Credentials     = creds.GetCredential(uri, authType);

            var responseStream = req.GetResponse().GetResponseStream();

            if (responseStream == null)
            {
                return(string.Empty);
            }

            var reader = new StreamReader(responseStream);

            return(reader.ReadToEnd());
        }
コード例 #22
0
        public static void AddRemove_HostPortAuthenticationTypeDefaultCredentials_Success()
        {
            NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;

            CredentialCache cc = new CredentialCache();
            cc.Add(host1, port1, authenticationType1, nc);

            Assert.Equal(nc, cc.GetCredential(host1, port1, authenticationType1));

            cc.Remove(host1, port1, authenticationType1);
            Assert.Null(cc.GetCredential(host1, port1, authenticationType1));
        }
コード例 #23
0
        /// <summary>
        /// Submit HTTP Request
        /// </summary>
        /// <remarks>
        /// Submit an HTTP request.
        /// </remarks>
        /// <param name="method">HTTP Method. for example "POST", "GET"</param>
        /// <param name="URL">URL to send HTTP Request to</param>
        /// <param name="postdata">Data to be posted</param>
        /// <param name="usr">Username</param>
        /// <param name="pwd">Password</param>
        /// <returns>Response in plain text.</returns>
        public string SubmitHttpRequest(string method, string URL, string postdata, string usr, string pwd)
        {
            String responseText = "";

            HttpWebRequest request;
            Uri            uri = new Uri(URL);

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

            if (method.Equals("SOAP"))
            {
                request.Method = "POST";
                request.Headers.Add("SOAPAction: Some-URI");
                request.ContentType = "text/xml; charset=UTF-8";
            }
            else if (method.Equals("DOWNLOAD"))
            {
                request.Method = "GET";
            }
            else
            {
                request.ContentType = "text/xml; charset=UTF-8";
                request.Method      = method;
            }

            // Credential and cookies
            request.CookieContainer = _cookieContainer;
            string authType = "Negotiate";

            if (_credentialCache.GetCredential(uri, authType) == null)
            {
                // System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.;
                // ICredentials c = System.Net.CredentialCache.DefaultCredentials;
                NetworkCredential nc = System.Net.CredentialCache.DefaultNetworkCredentials;
                _credentialCache.Add(uri, authType, nc);
            }
            request.Credentials = _credentialCache;


            // post data
            if (request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                UTF8Encoding encoding = new UTF8Encoding();
                Byte[]       byteTemp = encoding.GetBytes(postdata);
                request.ContentLength = byteTemp.Length;

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

            // get response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (_cookieContainer.GetCookies(uri) == null)
            {
                _cookieContainer.Add(uri, response.Cookies);
            }

            Stream responseStream = response.GetResponseStream();

            if (method.Equals("DOWNLOAD"))
            {
                FileStream file = null;

                string fileName = response.GetResponseHeader("Content-Disposition");

                string[] s = null;
                if (fileName.ToLower().EndsWith(".tif"))
                {
                    s    = URL.Split(new String[] { "coverage=" }, 100, StringSplitOptions.RemoveEmptyEntries);
                    s[1] = s[1].Trim() + ".tif";
                }
                else
                {
                    s    = fileName.Split('=');
                    s[1] = s[1].Replace('\\', ' ');
                    s[1] = s[1].Replace('"', ' ');
                    s[1] = s[1].Trim();
                }

                try
                {
                    downloadFileName = System.IO.Path.Combine(Utils.GetSpecialFolderPath(SpecialFolder.ConfigurationFiles), s[1]);
                    System.IO.File.Delete(downloadFileName);
                    file = System.IO.File.Create(downloadFileName);
                    // Buffer to read 10K bytes in chunk:
                    byte[] buffer = new Byte[10000];
                    int    length = 10000;
                    int    offset = 0;
                    while (length > 0)
                    {
                        length  = responseStream.Read(buffer, 0, length);
                        offset += length;
                        file.Write(buffer, 0, length);
                    }
                }
                catch (Exception e)
                {
                }
                finally
                {
                    if (file != null)
                    {
                        file.Close();
                    }
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                }

                return(downloadFileName);
            }

            StreamReader reader = new StreamReader(responseStream);

            responseText = reader.ReadToEnd();

            reader.Close();
            responseStream.Close();

            return(responseText);
        }
コード例 #24
0
 /// <inheritdoc />
 public INetworkCredential GetCredential(string host, int port, string authenticationType)
 {
     return(_cache.GetCredential(host, port, authenticationType).ToInterface());
 }
コード例 #25
0
        public static CreateChannelResult <T> BuildChannel <T>(Uri uri, string authType, CredentialCache cc)
        {
            if (cc == null)
            {
                throw new ArgumentException();
            }
            var uriBuilder = new UriBuilder(uri)
            {
                Scheme = authType == AuthType.Basic ? "https" : "http",
                Port   = authType == AuthType.Basic ? 443 : uri.Port,
                Path   = ServicePaths[typeof(T)]
            };
            var serviceUri = uriBuilder.Uri;
            var factory    = ChannelFactoryBuilder.BuildChannelFactory <T>(serviceUri, authType, cc.GetCredential(uri, authType));

            ServicePointManager.ServerCertificateValidationCallback = ChannelSettings.RemoteCertificateValidationCallback;
            try
            {
                var channel = factory.CreateChannel();
                return(new CreateChannelResult <T>
                {
                    Channel = channel,
                    Success = true
                });
            }
            catch (Exception e)
            {
                return(new CreateChannelResult <T>
                {
                    Exception = e
                });
            }
        }
コード例 #26
0
ファイル: WebManager.cs プロジェクト: imp908/NSQLmanager
 public NetworkCredential credentials(Uri uri_, string type_)
 {
     return(credentialsCache.GetCredential(uri_, type_));
 }
コード例 #27
0
        // Пример отправки сообщения с вложением по эл.почте
        // Не асинхронный вариант
        public void MessageWithAttachment()
        {
            string errMsg = CheckMailParameters();

            if (errMsg != null)
            { // Была ошика чтения параметров
                txtSmtpLog.Text += errMsg;
                txtSmtpLog.Text += "ОШИБКА: Отправка не произведена\r\n";
                return;
            }

            string smtPServer = txtSmtpServer.Text.Trim();
            int    smtpPort   = int.Parse(txtSmtpPort.Text);

            string mailFrom = txtMailFrom.Text.Trim();
            string mailPass = txtUserPassword.Text;

            string mailTo     = txtMailTo.Text.Trim();
            string msgSubject = txtMsgSubject.Text;
            string msgBody    = txtMessage.Text;

            // файл для отправки
            string msgFileAttach = txtFileAttach.Text.Trim();

            // На всякий случай инициализирую пустыми строками поля Subject и MessageBody
            if (msgSubject == null)
            {
                msgSubject = "";
            }
            if (msgBody == null)
            {
                msgBody = "";
            }

            // Создаем экземпляр сообщения MailMessage
            MailMessage message = new MailMessage(
                mailFrom,                   // Mail address FROM
                mailTo,                     // Mail address TO
                msgSubject,                 // Mail message SUBJECT - заголовок письма
                msgBody);                   // Mail message BODY - текст сообщения

            //message.Body; - текст сообщения
            // кодировка тела письма
            message.BodyEncoding = System.Text.Encoding.UTF8;

            //message.Subject; -заголовок письма
            // кодировка заголовока эл.письма
            message.SubjectEncoding = System.Text.Encoding.UTF8;

            // Создания объекта вложения
            Attachment attachData = null;

            if (msgFileAttach.Length > 0)
            {
                attachData = new Attachment(msgFileAttach, MediaTypeNames.Application.Octet);

                // Информация о файле вложения
                ContentDisposition disposition = attachData.ContentDisposition;
                // Время создания/модификации/доступа файла
                disposition.CreationDate     = System.IO.File.GetCreationTime(msgFileAttach);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(msgFileAttach);
                disposition.ReadDate         = System.IO.File.GetLastAccessTime(msgFileAttach);

                // Добавления фложения в письмо
                message.Attachments.Add(attachData);
            }

            txtSmtpLog.Text += "SMTP Server: " + smtPServer + "\r\n";
            txtSmtpLog.Text += "User name/mail FROM: " + mailFrom + "\r\n";
            txtSmtpLog.Text += "User password: ********\r\n";

            CredentialCache   cc = new CredentialCache();
            NetworkCredential nc = new NetworkCredential(mailFrom, mailPass);

            cc.Add(smtPServer, smtpPort, "Basic", nc);

            // Создание объекта почтового клиента SmtpClient
            SmtpClient mailClient = new SmtpClient(smtPServer, smtpPort);

            // Add credentials if the SMTP server requires them.
            mailClient.Credentials = cc.GetCredential(smtPServer, smtpPort, "Basic");
            //mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;   // По умолчанию

            // Устанавливам SSL для соединения и обмена с SMTP-сервером
            //  по флагу "Use SSL/TLS"
            mailClient.EnableSsl = chkUseTls.Checked;

            try
            {
                if (chkUseSendAsync.Checked)
                { // Пример асинхронной отправки сообщения по электронной почты
                    mailSent = false;
                    string userState = "Asynchronous sending";
                    mailClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                    mailClient.SendAsync(message, userState);
                    return;
                }
                else
                { // Пример синхронной отправки сообщения по электронной почты
                    mailClient.Send(message);
                    txtSmtpLog.Text += "Сообщение отправлено\r\n";
                }
            }
            catch (Exception ex)
            {
                txtSmtpLog.Text += "ОШИБКА отправки сообщения: " + ex.ToString() + "\r\n";
            }

            // Компоненты ContentDisposition прикрепленного файла
            if (attachData != null)
            {
                ContentDisposition cd = attachData.ContentDisposition;
                txtSmtpLog.Text += "Content disposition:\r\n";
                txtSmtpLog.Text += cd.ToString() + "\r\n";
                txtSmtpLog.Text += " File: " + cd.FileName + "\r\n";
                txtSmtpLog.Text += " Size: " + cd.Size.ToString() + " bytes \r\n";
                txtSmtpLog.Text += " Creation:     " + cd.CreationDate.ToString() + "\r\n";
                txtSmtpLog.Text += " Modification: " + cd.ModificationDate.ToString() + "\r\n";
                txtSmtpLog.Text += " Last Read:    " + cd.ReadDate.ToString() + "\r\n";
                txtSmtpLog.Text += " Inline: " + cd.Inline.ToString() + "\r\n";
                txtSmtpLog.Text += " Parameters: " + cd.Parameters.Count.ToString() + "\r\n";
                foreach (DictionaryEntry d in cd.Parameters)
                {
                    txtSmtpLog.Text += " --" + d.Key.ToString() + " = " + d.Value.ToString() + "\r\n";
                }
                // Удаление объекта Attachment
                attachData.Dispose();
            }
        }
コード例 #28
0
        public static void GetCredential_UriAuthenticationType_Invalid()
        {
            CredentialCache cc = new CredentialCache();

            Assert.Throws<ArgumentNullException>(() => cc.GetCredential(null, "authenticationType")); //Null uriPrefix
            Assert.Throws<ArgumentNullException>(() => cc.GetCredential(new Uri("http://microsoft:80"), null)); //Null authenticationType
        }
コード例 #29
0
        public static void GetCredential_HostPortAuthenticationType_Invalid()
        {
            CredentialCache cc = new CredentialCache();

            Assert.Throws<ArgumentNullException>(() => cc.GetCredential(null, 500, "authenticationType")); //Null host
            Assert.Throws<ArgumentNullException>(() => cc.GetCredential("host", 500, null)); //Null authenticationType

            Assert.Throws<ArgumentException>(() => cc.GetCredential("", 500, "authenticationType")); //Empty host

            Assert.Throws<ArgumentOutOfRangeException>(() => cc.GetCredential("host", -1, "authenticationType")); //Port < 0
        }
コード例 #30
0
        /// <summary>
        /// Submit HTTP Request
        /// </summary>
        /// <remarks>
        /// Submit an HTTP request.
        /// </remarks>
        /// <param name="method">HTTP Method. for example "POST", "GET"</param>
        /// <param name="URL">URL to send HTTP Request to</param>
        /// <param name="postdata">Data to be posted</param>
        /// <param name="usr">Username</param>
        /// <param name="pwd">Password</param>
        /// <returns>Response in plain text.</returns>
        public string SubmitHttpRequest(string method, string URL, string postdata, string usr, string pwd)
        {
            String         responseText = "";
            HttpWebRequest request;
            Uri            uri = new Uri(URL);

            request = (HttpWebRequest)WebRequest.Create(uri);
            request.AllowAutoRedirect = true;
            if (method.Equals("SOAP"))
            {
                request.Method = "POST";
                request.Headers.Add("SOAPAction: Some-URI");
                request.ContentType = "text/xml; charset=UTF-8";
            }
            else if (method.Equals("DOWNLOAD"))
            {
                request.Method = "GET";
            }
            else
            {
                request.ContentType = "text/xml; charset=UTF-8";
                request.Method      = method;
            }

            // Credential and cookies
            request.CookieContainer = _cookieContainer;

            NetworkCredential nc       = null;
            String            authType = "Negotiate";

            if (_credentialCache.GetCredential(uri, authType) == null && _credentialCache.GetCredential(uri, "Basic") == null)
            {
                if (!String.IsNullOrEmpty(usr) && !String.IsNullOrEmpty(pwd))
                {
                    nc = new NetworkCredential(usr, pwd);
                    _credentialCache.Add(uri, "Basic", nc);
                    _credentialCache.Add(uri, authType, nc);
                }
                else
                {
                    nc = System.Net.CredentialCache.DefaultNetworkCredentials;
                    _credentialCache.Add(uri, authType, nc);
                }
            }
            request.Credentials = _credentialCache;
            // post data
            if (request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                UTF8Encoding encoding = new UTF8Encoding();
                Byte[]       byteTemp = encoding.GetBytes(postdata);
                request.ContentLength = byteTemp.Length;

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

            HttpWebResponse response = null;

            try{
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (UnauthorizedAccessException ua)
            {
                if (retryAttempt)
                {
                    PromptCredentials pc = new PromptCredentials();
                    pc.ShowDialog();
                    retryAttempt = false;
                    try
                    {
                        _credentialCache.Remove(uri, "Basic");
                    }
                    catch (Exception) { };
                    _credentialCache.Remove(uri, authType);
                    if (!String.IsNullOrEmpty(pc.Username) && !String.IsNullOrEmpty(pc.Password))
                    {
                        return(SubmitHttpRequest(method, URL, postdata, pc.Username, pc.Password));
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    retryAttempt = true;
                    throw ua;
                }
            }
            catch (WebException we)
            {
                if (retryAttempt)
                {
                    PromptCredentials pc = new PromptCredentials();
                    pc.ShowDialog();
                    retryAttempt = false;
                    try
                    {
                        _credentialCache.Remove(uri, "Basic");
                    }catch (Exception) {};
                    _credentialCache.Remove(uri, authType);
                    if (!String.IsNullOrEmpty(pc.Username) && !String.IsNullOrEmpty(pc.Password))
                    {
                        return(SubmitHttpRequest(method, URL, postdata, pc.Username, pc.Password));
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    retryAttempt = true;
                    throw we;
                }
            }
            if (_cookieContainer.GetCookies(uri) == null)
            {
                _cookieContainer.Add(uri, response.Cookies);
            }

            Stream responseStream = response.GetResponseStream();

            if (method.Equals("DOWNLOAD"))
            {
                FileStream file = null;

                string fileName = response.GetResponseHeader("Content-Disposition");

                string[] s = null;
                if (fileName.ToLower().EndsWith(".tif"))
                {
                    s    = URL.Split(new String[] { "coverage=" }, 100, StringSplitOptions.RemoveEmptyEntries);
                    s[1] = s[1].Trim() + ".tif";
                }
                else
                {
                    s    = fileName.Split('=');
                    s[1] = s[1].Replace('\\', ' ');
                    s[1] = s[1].Replace('"', ' ');
                    s[1] = s[1].Trim();
                }

                try
                {
                    downloadFileName = System.IO.Path.Combine(Utils.GetSpecialFolderPath(SpecialFolder.ConfigurationFiles), s[1]);
                    System.IO.File.Delete(downloadFileName);
                    file = System.IO.File.Create(downloadFileName);
                    // Buffer to read 10K bytes in chunk:
                    byte[] buffer = new Byte[10000];
                    int    length = 10000;
                    int    offset = 0;
                    while (length > 0)
                    {
                        length  = responseStream.Read(buffer, 0, length);
                        offset += length;
                        file.Write(buffer, 0, length);
                    }
                }
                catch (Exception e)
                {}
                finally
                {
                    if (file != null)
                    {
                        file.Close();
                    }
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                    retryAttempt = true;
                }

                return(downloadFileName);
            }

            StreamReader reader = new StreamReader(responseStream);

            responseText = reader.ReadToEnd();

            reader.Close();
            responseStream.Close();

            return(responseText);
        }
コード例 #31
0
        public void All()
        {
            CredentialCache c = new CredentialCache();

            NetworkCredential cred1 = new NetworkCredential("user1", "pwd1");
            NetworkCredential cred2 = new NetworkCredential("user2", "pwd2");
            NetworkCredential cred3 = new NetworkCredential("user3", "pwd3");
            NetworkCredential cred4 = new NetworkCredential("user4", "pwd4");
            NetworkCredential cred5 = new NetworkCredential("user5", "pwd5");

            c.Add(new Uri("http://www.ximian.com"), "Basic", cred1);
            c.Add(new Uri("http://www.ximian.com"), "Kerberos", cred2);

            c.Add(new Uri("http://www.contoso.com/portal/news/index.aspx"), "Basic", cred1);
            c.Add(new Uri("http://www.contoso.com/portal/news/index.aspx?item=1"), "Basic", cred2);
            c.Add(new Uri("http://www.contoso.com/portal/news/index.aspx?item=12"), "Basic", cred3);
            c.Add(new Uri("http://www.contoso.com/portal/"), "Basic", cred4);
            c.Add(new Uri("http://www.contoso.com"), "Basic", cred5);

            NetworkCredential result = null;

            try {
                c.Add(new Uri("http://www.ximian.com"), "Basic", cred1);
                Assert.Fail("#1: should have failed");
            } catch (ArgumentException) { }

            c.Add(new Uri("http://www.contoso.com/"), "**Unknown**", cred1);
            result = c.GetCredential(new Uri("http://www.contoso.com/"), "**Unknown**");
            Assert.AreEqual(result, cred1, "#3");
            c.Remove(new Uri("http://www.contoso.com/"), "**Unknown**");
            result = c.GetCredential(new Uri("http://www.contoso.com/"), "**Unknown**");
            Assert.IsTrue(result == null, "#4");

            c.Add(new Uri("http://www.contoso.com/"), "**Unknown**", cred1);
            result = c.GetCredential(new Uri("http://www.contoso.com"), "**Unknown**");
            Assert.AreEqual(result, cred1, "#5");
            c.Remove(new Uri("http://www.contoso.com"), "**Unknown**");
            result = c.GetCredential(new Uri("http://www.contoso.com"), "**Unknown**");
            Assert.IsTrue(result == null, "#6");

            c.Add(new Uri("http://www.contoso.com/portal/"), "**Unknown**", cred1);
            result = c.GetCredential(new Uri("http://www.contoso.com/portal/foo/bar.html"), "**Unknown**");
            Assert.AreEqual(result, cred1, "#7");
            c.Remove(new Uri("http://www.contoso.com"), "**Unknown**");
            result = c.GetCredential(new Uri("http://www.contoso.com"), "**Unknown**");
            Assert.IsTrue(result == null, "#8");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal/news/index.aspx"), "Basic");
            Assert.AreEqual(result, cred3, "#9");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal/news/index"), "Basic");
            Assert.AreEqual(result, cred3, "#10");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal/news/"), "Basic");
            Assert.AreEqual(result, cred3, "#11");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal/news"), "Basic");
            Assert.AreEqual(result, cred4, "#12");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal/ne"), "Basic");
            Assert.AreEqual(result, cred4, "#13");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal/"), "Basic");
            Assert.AreEqual(result, cred4, "#14");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/portal"), "Basic");
            Assert.AreEqual(result, cred5, "#15");

            result = c.GetCredential(new Uri("http://www.contoso.com:80/"), "Basic");
            Assert.AreEqual(result, cred5, "#16");

            result = c.GetCredential(new Uri("http://www.contoso.com"), "Basic");
            Assert.AreEqual(result, cred5, "#17");

            /*
             * IEnumerator e = c.GetEnumerator ();
             * while (e.MoveNext ()) {
             *      Console.WriteLine (e.Current.GetType () + " : " + e.Current.ToString ());
             * }
             */
#if NET_2_0
            result = c.GetCredential("www.ximian.com", 80, "Basic");
            Assert.IsTrue(result == null, "#18");

            c.Add("www.ximian.com", 80, "Basic", cred1);

            try {
                c.Add("www.ximian.com", 80, "Basic", cred1);
                Assert.Fail("#19: should have failed");
            } catch (ArgumentException) { }

            result = c.GetCredential("www.ximian.com", 80, "Basic");
            Assert.AreEqual(result, cred1, "#20");

            c.Remove(new Uri("http://www.contoso.com"), "Basic");
            c.Add("www.contoso.com", 80, "Basic", cred5);
            result = c.GetCredential(new Uri("http://www.contoso.com"), "Basic");
            Assert.IsTrue(result == null, "#21");
#endif
        }
コード例 #32
0
        public static void GetCredential_SimilarUriAuthenticationType_GetLongestUriPrefix()
        {
            CredentialCache cc = new CredentialCache();
            cc.Add(new Uri("http://microsoft:80/greaterpath"), authenticationType1, credential2);
            cc.Add(new Uri("http://microsoft:80/"), authenticationType1, credential1);

            NetworkCredential nc = cc.GetCredential(new Uri("http://microsoft:80"), authenticationType1);
            Assert.Equal(nc, credential2);
        }
コード例 #33
0
 public NetworkCredential GetCredential(Uri uri, string authType)
 {
     return(_cache.GetCredential(uri, authType) ?? CredentialCache.DefaultNetworkCredentials);
 }