Add() public method

public Add ( Uri uriPrefix, string authType, NetworkCredential cred ) : void
uriPrefix Uri
authType string
cred NetworkCredential
return void
示例#1
1
        /// <summary>
        /// method to download the contents of a file from a remote URI
        /// </summary>
        /// <param name="ftpUri"></param>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public static string GetFileFromSite(Uri ftpUri, string user, string pass)
        {
            string fileString = string.Empty;

            // The serverUri parameter should start with the ftp:// scheme.
            if (ftpUri.Scheme != Uri.UriSchemeFtp)
            {
                return string.Empty;
            }
            // Get the object used to communicate with the server.
            WebClient request = new WebClient();

            // This example assumes the FTP site uses anonymous logon.
            NetworkCredential nc = new NetworkCredential(user, pass);
            CredentialCache cc = new CredentialCache();
            cc.Add(ftpUri, "Basic", nc);
            request.Credentials = cc;

            try
            {

                byte[] newFileData = request.DownloadData(ftpUri.ToString());
                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
            }
            catch (WebException e)
            {
                m_logger.WriteToLogFile("FtpUtils::GetFileFromSite();ECaught: " + e.Message);
            }
            return fileString;
        }
        /// <summary>
        /// Checks to see if someone has access to a specific calendar
        /// </summary>
        /// <param name="UserName">User name</param>
        /// <param name="Password">Password</param>
        /// <param name="Directory">Directory to check</param>
        /// <param name="Server">Server location</param>
        /// <returns>true if they can, false otherwise</returns>
        public static bool HasPermissionToCalendar(string UserName, string Password, string Directory, string Server)
        {
            System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(Server + "exchange/" + Directory + "/Calendar/");

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(Server + "exchange/" + Directory + "/Calendar/"),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(Server + "exchange/" + Directory + "/Calendar/"),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }

            Request.Credentials = MyCredentialCache;

            Request.Method            = "GET";
            Request.ContentType       = "text/xml; encoding='utf-8'";
            Request.UserAgent         = "Mozilla/4.0(compatible;MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)";
            Request.KeepAlive         = true;
            Request.AllowAutoRedirect = false;

            System.Net.WebResponse Response = (HttpWebResponse)Request.GetResponse();
            Response.Close();
            return(true);
        }
		public void multiple_credentials_via_user_supplied_credential_cache()
		{
			var cred = new OAuth2Client.OAuth2Credential(
				"apiv1",
				new OAuth2Client.Storage.JsonFileStorage(
					@"C:\Projects\github\oauth2_files\local_versiononeweb_client_secrets.json",
					@"C:\Projects\github\oauth2_files\local_versiononeweb_creds.json"),
				null
				);

			var cache = new CredentialCache();

			var simpleCred = new NetworkCredential(V1Username, V1Password);

			cache.Add(V1Uri, "Basic", simpleCred);
			cache.Add(V1Uri, "Bearer", cred);

			var windowsIntegratedCredential = CredentialCache.DefaultNetworkCredentials;
			// TODO explore: CredentialCache.DefaultCredentials
			// Suppose for some weird reason you just wanted to support NTLM:
			cache.Add(V1Uri, "NTLM", windowsIntegratedCredential);
			
			var connector = new VersionOneAPIConnector(V1Path, cache);

			connector.HttpGet("rest-1.v1/Data/Member/20");
		}
        public void TestLookupCredentialWithCredentialCache()
        {
            var credentials = new CredentialCache();
              var credPopuser1 = new NetworkCredential("popuser1", "password");
              var credPopuser2 = new NetworkCredential("popuser2", "password");
              var credImapuser1 = new NetworkCredential("imapuser1", "password");
              var credImapuser2 = new NetworkCredential("imapuser2", "password");

              credentials.Add("localhost", 110, string.Empty, credPopuser1);
              credentials.Add("localhost", 110, "cram-md5", credPopuser2);
              credentials.Add("localhost", 143, string.Empty, credImapuser1);
              credentials.Add("localhost", 143, "digest-md5", credImapuser2);

              Assert.AreEqual(credPopuser1, credentials.LookupCredential("localhost", 110, "popuser1", null));
              Assert.AreEqual(credPopuser2, credentials.LookupCredential("localhost", 110, "popuser2", "CRAM-MD5"));
              Assert.AreEqual(credImapuser1, credentials.LookupCredential("localhost", 143, "imapuser1", null));
              Assert.AreEqual(credImapuser2, credentials.LookupCredential("localhost", 143, "imapuser2", "DIGEST-MD5"));

              Assert.AreEqual(credPopuser1, credentials.LookupCredential("localhost", 110, null, null));
              Assert.AreEqual(credPopuser2, credentials.LookupCredential("localhost", 110, null, "CRAM-MD5"));
              Assert.IsNull(credentials.LookupCredential("localhost", 110, null, "DIGEST-MD5"));

              Assert.AreEqual(credImapuser1, credentials.LookupCredential("localhost", 143, null, null));
              Assert.AreEqual(credImapuser2, credentials.LookupCredential("localhost", 143, null, "DIGEST-MD5"));
              Assert.IsNull(credentials.LookupCredential("localhost", 143, null, "CRAM-MD5"));
        }
示例#5
0
文件: main.cs 项目: barroyo/medkinect
        public object conexion_rest(string type_request,string controller,object jsonObject,int id)
        {
            string json = JsonConvert.SerializeObject(jsonObject);
            string host = "http://localhost:3000/";
            HttpWebRequest request;

            request = (HttpWebRequest)WebRequest.Create(host + controller + ".json");
            if (type_request == "post")
            {
                request.Method = WebRequestMethods.Http.Post;
                byte[] data = Encoding.UTF8.GetBytes(json);

                request.ContentType = "application/json";
                request.Accept = "application/json";
                request.ContentLength = data.Length;
                StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
                postStream.Write(json);
                postStream.Close();
            }
            if (type_request == "get")
            {
                if (id != -1)
                {
                    request = (HttpWebRequest)WebRequest.Create(host + controller + "/"+id);
                }
                request.Method = WebRequestMethods.Http.Get;

            }
            if (type_request == "Put")
            {
                request = (HttpWebRequest)WebRequest.Create(host + controller + "/"+id);
                request.Method = WebRequestMethods.Http.Put;
                request.ContentType = "application/json";
                request.Accept = "application/json";
                byte[] data = Encoding.UTF8.GetBytes(json);
                request.ContentLength = data.Length;
                StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
                postStream.Write(json);
                postStream.Close();

            }
            NetworkCredential credentials = new NetworkCredential("username", "123");
            CredentialCache cache = new CredentialCache();
            cache.Add(new Uri(host),"Basic", credentials);
            cache.Add(new Uri(host),"Negotiate",credentials);
            request.Credentials = cache;

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

            StreamReader sr = new StreamReader(response.GetResponseStream(),  Encoding.UTF8);
            string html = sr.ReadToEnd();

               object json_respond = JsonConvert.DeserializeObject(html);

               return json;
            //return html;
        }
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(NegotiateCredential));
            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));

            // Get the user name from the credential data.
            string userName;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.UserName, out userName))
            {
                userName = null;
            }

            ArgUtil.NotNullOrEmpty(userName, nameof(userName));
            trace.Info("User name retrieved.");

            // Get the password from the credential data.
            string password;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Password, out password))
            {
                password = null;
            }

            ArgUtil.NotNullOrEmpty(password, nameof(password));
            trace.Info("Password retrieved.");

            // Get the URL from the credential data.
            string url;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out url))
            {
                url = null;
            }

            ArgUtil.NotNullOrEmpty(url, nameof(url));
            trace.Info($"URL retrieved: {url}");

            // Create the Negotiate and NTLM credential object.
            var credential = new NetworkCredential(userName, password);
            var credentialCache = new CredentialCache();
            switch (Constants.Agent.Platform)
            {
                case Constants.OSPlatform.Linux:
                case Constants.OSPlatform.OSX:
                    credentialCache.Add(new Uri(url), "NTLM", credential);
                    break;
                case Constants.OSPlatform.Windows:
                    credentialCache.Add(new Uri(url), "Negotiate", credential);
                    break;
            }
            
            VssCredentials creds = new VssClientCredentials(new WindowsCredential(credentialCache));
            trace.Verbose("cred created");
            return creds;
        }
        public void multiple_credentials_via_user_supplied_credential_cache()
        {
            var simpleCred = new NetworkCredential(_username, _password);

            var windowsIntegratedCredential = CredentialCache.DefaultNetworkCredentials;

            var cache = new CredentialCache();
            var uri = new Uri(_prefix);
            cache.Add(uri, "Basic", simpleCred);
            // Suppose for some weird reason you just wanted to support NTLM:
            cache.Add(uri, "NTLM", windowsIntegratedCredential);

            var connector = new VersionOneAPIConnector(_prefix, cache);
            using (connector.GetData(Path)) ;
        }
        internal static ICredentials AsCredentialCache(this ICredentials credentials, Uri uri)
        {
            // No credentials then bail
            if (credentials == null)
            {
                return null;
            }

            // Do nothing with default credentials
            if (credentials == CredentialCache.DefaultCredentials ||
                credentials == CredentialCache.DefaultNetworkCredentials)
            {
                return credentials;
            }

            // If this isn't a NetworkCredential then leave it alove
            var networkCredentials = credentials as NetworkCredential;
            if (networkCredentials == null)
            {
                return credentials;
            }

            // Set this up for each authentication scheme we support
            // The reason we're using a credential cache is so that the HttpWebRequest will forward our
            // credentials if there happened to be any redirects in the chain of requests.
            var cache = new CredentialCache();
            foreach (string scheme in _authenticationSchemes)
            {
                cache.Add(uri, scheme, networkCredentials);
            }
            return cache;
        }
        private static void SetupProxy()
        {
            // if a proxyURL is specified in the configuration file,
            // create a WebProxy object for later use.
            string proxyURL = AppSettings.GetSetting(null, PROXY_URL);
            if (proxyURL != null)
            {
                mProxy = new WebProxy(proxyURL);

                // if a proxyUser is specified in the configuration file,
                // set up the proxy object's Credentials.
                string proxyUser
                    = AppSettings.GetSetting(null, PROXY_USER);
                if (proxyUser != null)
                {
                    string proxyPassword
                        = AppSettings.GetSetting(null, PROXY_PASSWORD);

                    NetworkCredential credential
                        = new NetworkCredential(proxyUser, proxyPassword);

                    CredentialCache cache = new CredentialCache();
                    cache.Add(new Uri(proxyURL), BASIC_AUTH, credential);
                    mProxy.Credentials = cache;
                }
            }
        }
示例#10
0
        protected static bool PostJson(Uri uri, string json, out ResponseMessage responseMessage)
        {
            var request = (HttpWebRequest)WebRequest.Create(uri);
            CredentialCache cc = new CredentialCache();
            cc.Add(uri, "NTLM", CredentialCache.DefaultNetworkCredentials);
            request.Credentials = cc;
            //request.Headers.Add("Authorization", AuthorizationHeaderValue);
            request.ContentType = "text/json";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    string responseContent = streamReader.ReadToEnd();
                    responseMessage = JsonConvert.DeserializeObject<ResponseMessage>(responseContent);
                }

            return response.StatusCode == HttpStatusCode.Created;
        }
示例#11
0
        public bool Connect(string userName, string passWord) {
            try {
                CredentialCache credCache = new CredentialCache();
                credCache.Add(host, "Basic", new NetworkCredential(userName, passWord));

                // Ligação à API-A
                service = new FedoraAPIAService();
                service.Url = host.ToString() + "/services/access";
                service.Timeout = 240000;
                service.PreAuthenticate = true;
                service.Credentials = credCache;

                // Ligação à API-M
                manager = new FedoraAPIMService();
                manager.Url = host.ToString() + "/services/management";
                manager.Timeout = 120000;
                manager.PreAuthenticate = true;
                manager.Credentials = credCache;

                serverNamespace = service.describeRepository().repositoryPIDNamespace;
                return true; 
            }  catch (Exception ex) {
                Trace.WriteLine(ex.ToString());
                return false; 
            }
        }
示例#12
0
        protected static string GetJson(Uri uri)
        {
            string result = String.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            CredentialCache cc = new CredentialCache();
            cc.Add(uri, "NTLM", CredentialCache.DefaultNetworkCredentials);
            request.Credentials = cc;
            request.ContentType = "application/json";
            //request.Headers.Add("Authorization", AuthorizationHeaderValue);

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                }
                throw;
            }

            return result;
        }
 private void btnGo_Click(object sender, EventArgs e)
 {
     string URL = string.Format("http://{1}/sdata/slx/dynamic/-/{0}?format=json",
     "Accounts", "localhost:3333");
     CredentialCache myCache = new CredentialCache();
     myCache.Add(new Uri(URL), "Basic",
         new NetworkCredential("Admin", "ll@@kers123"));
     WebRequest wreq = System.Net.WebRequest.Create(URL);
     wreq.Credentials = myCache;
     WebResponse wresp = wreq.GetResponse();
     StreamReader sr = new StreamReader(wresp.GetResponseStream());
     string jsonresp = sr.ReadToEnd();
     
     AccountsMyWayJSON.Account j = JsonConvert.DeserializeObject<AccountsMyWayJSON.Account>(jsonresp);
     int total = 0;
     foreach (Dictionary<string,object> item in j.resources)
     {
         if ((item["Employees"]!=null))
         {
             total += int.Parse(item["Employees"].ToString());
         }
     }
     j.totalEmployeesinResults = total;
     List<Dictionary<string,object>> r = new List<Dictionary<string,object>>(0);
     j.resources = r;
     rtbDisplay.Text =  JsonConvert.SerializeObject(j);
 }
示例#14
0
        public static IWebProxy CreateWebProxyWithCredentials(String sUrl, string ProxyUserName, string ProxyUserPassword, string sAuthType, string ProxyUserDomain)
        {
            if (String.IsNullOrEmpty(ProxyUserName) || String.IsNullOrEmpty(ProxyUserPassword))
            {
                return(null);
            }
            // get default proxy and assign it to the WebService. Alternatively, you can replace this with manual WebProxy creation.
            IWebProxy iDefaultWebProxy = WebRequest.DefaultWebProxy;
            Uri       uriProxy         = iDefaultWebProxy.GetProxy(new Uri(sUrl));
            string    sProxyUrl        = uriProxy.AbsoluteUri;

            if (sProxyUrl == sUrl)
            {//no proxy specified
                return(null);
            }
            IWebProxy proxyObject = new WebProxy(sProxyUrl, true);

            // assign the credentials to the Proxy
            //todo do we need to add credentials to  WebService too??
            if ((!String.IsNullOrEmpty(sAuthType)) && (sAuthType.ToLower() != "basic"))
            {
                //from http://www.mcse.ms/archive105-2004-10-1165271.html
                // create credentials cache - it will hold both, the WebProxy credentials (??and the WebService credentials too??)
                System.Net.CredentialCache cache = new System.Net.CredentialCache();
                // add default credentials for Proxy (notice the authType = 'Kerberos' !) Other types are 'Basic', 'Digest', 'Negotiate', 'NTLM'
                cache.Add(new Uri(sProxyUrl), sAuthType, new System.Net.NetworkCredential(ProxyUserName, ProxyUserPassword, ProxyUserDomain));
                proxyObject.Credentials = cache;
            }
            else//special case for Basic (from http://www.xmlwebservices.cc/index_FAQ.htm )
            {
                proxyObject.Credentials = new System.Net.NetworkCredential(ProxyUserName, ProxyUserPassword);
            }
            return(proxyObject);
        }
        // This function sends the OPTIONS request and returns an
        // ASOptionsResponse class that represents the response.
        public ASOptionsResponse GetOptions()
        {
            if (credential == null || server == null)
                throw new InvalidDataException("ASOptionsRequest not initialized.");

            string uriString = string.Format("{0}//{1}/Microsoft-Server-ActiveSync", UseSSL ? "https:" : "http:", Server);
            Uri serverUri = new Uri(uriString);
            CredentialCache creds = new CredentialCache();
            // Using Basic authentication
            creds.Add(serverUri, "Basic", Credentials);

            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uriString);
            httpReq.Credentials = creds;
            httpReq.Method = "OPTIONS";

            try
            {
                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();

                ASOptionsResponse response = new ASOptionsResponse(httpResp);

                httpResp.Close();

                return response;
            }
            catch (Exception ex)
            {
                ASError.ReportException(ex);
                return null;
            }
        }
示例#16
0
        public ActionResult Index()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://clowa.com");

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            CredentialCache myCache = new CredentialCache();
            myCache.Add(new Uri("http://clowa.com/service/login.ashx"), "Basic", new NetworkCredential("wyxy2005","13561387"));
            //myCache.Add(new Uri("http://www.contoso.com/"), "Digest", new NetworkCredential(UserName, SecurelyStoredPassword, Domain));

            request.Credentials = myCache;

            //request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.WriteLine("Content length is {0}", response.ContentLength);
            Console.WriteLine("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format.
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            Console.WriteLine("Response stream received.");
            Console.WriteLine(readStream.ReadToEnd());
            response.Close();
            readStream.Close();

            return View();
        }
示例#17
0
        public static string GoogleAuthManagerExample( string uri, string username, string password )
        {
            AuthenticationManager.Register( new GoogleLoginClient() );
            // Now 'GoogleLogin' is a recognized authentication scheme

            GoogleCredentials creds = new GoogleCredentials( username, password, "HOSTED_OR_GOOGLE" );

            // Cached credentials can only be used when requested by specific URLs and authorization schemes
            CredentialCache credCache = new CredentialCache();
            credCache.Add( new Uri( uri ), "GoogleLogin", creds );

            WebRequest request = WebRequest.Create( uri );

            // Must be a cache, basic credentials are cleared on redirect
            request.Credentials = credCache;
            request.PreAuthenticate = true; // More efficient, but optional


            // Process response  
            var response = request.GetResponse() as HttpWebResponse;
            var stream = new StreamReader( response.GetResponseStream(), Encoding.Default );
            var responseString = stream.ReadToEnd();
            stream.Close();

            // Erase cached auth token unless you'll use it again soon.
            creds.PrevAuth = null;

            return responseString;
        }
示例#18
0
 /// <summary>
 /// 重启路由
 /// </summary>
 private string reset(string url, string userName, string password, string method, string data)
 {
     CookieContainer container = new CookieContainer();
     string requestUriString = url;
     if (method == "GET") requestUriString += "?" + data;
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
     request.Method = method;
     if (method == "POST") {
         byte[] POSTData = new UTF8Encoding().GetBytes(data);
         request.ContentLength = POSTData.Length;
         request.GetRequestStream().Write(POSTData, 0, POSTData.Length);
     }
     request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;CIBA)";
     request.CookieContainer = container;
     request.KeepAlive = true;
     request.Accept = "*/*";
     request.Timeout = 3000;
     request.PreAuthenticate = true;
     CredentialCache cache = new CredentialCache();
     cache.Add(new Uri(requestUriString), "Basic", new NetworkCredential(routeInfo.UserName, routeInfo.RPassword));
     request.Credentials = cache;
     try {
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         response.Cookies = container.GetCookies(request.RequestUri);
         new StreamReader(response.GetResponseStream(), Encoding.Default).Close();
         response.Close();
         return string.Empty;
     } catch (Exception ex) {
         return ex.Message;
     }
 }
    /// <summary>
    /// retrieve the content of given url. throws httpexception if raised
    /// </summary>
    /// <param name="relativeUrl"></param>
    /// <returns></returns>
    protected string GetContents(string relativeUrl)
    {
      try
      {
        Uri uri = new Uri(string.Format("{0}{1}", BaseUrl, relativeUrl));
        WebRequest myWebRequest = HttpWebRequest.Create(uri);

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;

        NetworkCredential myNetworkCredential = new NetworkCredential(UserName, Password);
        CredentialCache myCredentialCache = new CredentialCache();
        myCredentialCache.Add(uri, "Basic", myNetworkCredential);

        myHttpWebRequest.PreAuthenticate = true;
        myHttpWebRequest.Credentials = myCredentialCache;

        using (WebResponse myWebResponse = myWebRequest.GetResponse())
        {
          using (Stream responseStream = myWebResponse.GetResponseStream())
          {
            StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
            return myStreamReader.ReadToEnd();
          }
        }
      }
      catch (Exception e)
      {
        throw new HttpException(string.Format("Error while retrieving url '{0}': {1}", relativeUrl, e.Message), e);
      }
    }
示例#20
0
        static void Main(string[] args)
        {
            string strBaseUrl = "http://192.168.1.1";
            string strUrl = strBaseUrl + "/userRpm/SysRebootRpm.htm?Reboot={0}";//%D6%D8%C6%F4%C2%B7%D3%C9%C6%F7";
            string strCommand = "重启路由器";

            strCommand = HttpUtility.UrlEncode(strCommand, Encoding.GetEncoding("GB2312"));
            strUrl = string.Format(strUrl, strCommand);

            NetworkCredential myCred = new NetworkCredential(
	        "1802", "1qaz2wsx",null);

            CredentialCache myCache = new CredentialCache();

            myCache.Add(new Uri(strBaseUrl), "Basic", myCred);
            //myCache.Add(new Uri("app.contoso.com"), "Basic", myCred);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Credentials = myCache;

            try
            {
                WebResponse response = request.GetResponse();
            }
            catch (Exception)
            {
                
                throw;
            }
            //string strIPCtlFormat = "QoSCtrl={0}&h_lineType={1}&h_down_bandWidth={2}";


            //string strFormFormat = "QoSCtrl={0}&h_lineType={1}&h_down_bandWidth=4000&hips_1=1&hipe_1=2&hm_1=0&hbW_1=999&hn_1=hahaha&hen_1=1&hips_2=&hipe_2=&hm_2=0&hbW_2=&hn_2=&hen_2=&hips_3=&hipe_3=&hm_3=0&hbW_3=&hn_3=&hen_3=&hips_4=&hipe_4=&hm_4=0&hbW_4=&hn_4=&hen_4=&hips_5=&hipe_5=&hm_5=0&hbW_5=&hn_5=&hen_5=&hips_6=&hipe_6=&hm_6=0&hbW_6=&hn_6=&hen_6=&hips_7=&hipe_7=&hm_7=0&hbW_7=&hn_7=&hen_7=&hips_8=&hipe_8=&hm_8=0&hbW_8=&hn_8=&hen_8=&sv=%B1%A3%20%B4%E6"
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string URL = string.Format("http://{1}/sdata/slx/dynamic/-/{0}?format=json",
         "Accounts", "localhost:3333");
            CredentialCache myCache = new CredentialCache();
            myCache.Add(new Uri(URL), "Basic",
                new NetworkCredential("Admin", "ll@@kers123"));
            WebRequest wreq = System.Net.WebRequest.Create(URL);
            wreq.Credentials = myCache;
            WebResponse wresp = wreq.GetResponse();
            StreamReader sr = new StreamReader(wresp.GetResponseStream());
            string jsonresp = sr.ReadToEnd();

            AccountsMyWayJSON.Account j = JsonConvert.DeserializeObject<AccountsMyWayJSON.Account>(jsonresp);
            int total = 0;
            //this is really the difference with this example. 
            //I need a place to hold the new resources temporarily...
            List<Dictionary<string,object>> newresources = new List<Dictionary<string,object>>();

            foreach (Dictionary<string, object> item in j.resources)
            {
                if ((item["AccountName"] != null) && item["AccountName"].ToString().StartsWith("A"))
                {
                    Dictionary<string, object> newkeyvalue = new Dictionary<string, object>(0);
                    newkeyvalue.Add("AccountName", item["AccountName"]);

                    newresources.Add(newkeyvalue);
                }
            }
            //then I replace the .resources in the original object. Simple. 
            j.resources = newresources;
            rtbDisplay.Text = JsonConvert.SerializeObject(j);
        }
示例#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;
        }
示例#23
0
        public void AddEntitlementLineItemToLicenseServer(EntitlementLineItemResponse lineItem,
                                                          string serverName)
        {
            var fnoWs = new v1ManageDeviceService();

            fnoWs.Url = EndPointUrl + "ManageDeviceService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;
            var lineItemRq = new linkAddonLineItemDataType[1];

            lineItemRq[0] = new linkAddonLineItemDataType();
            lineItemRq[0].deviceIdentifier = GetLicenseServer(serverName);

            var linkLineItems = new linkLineItemDataType[1];

            linkLineItems[0] = new linkLineItemDataType();
            linkLineItems[0].lineItemIdentifier = new linkLineItemIdentifier
            {
                activationId = lineItem.ActivationCode,

                count = lineItem.TotalQty.ToString()
            };


            lineItemRq[0].lineItem = linkLineItems;
            var resp = fnoWs.linkAddonLineItems(lineItemRq);
        }
示例#24
0
 // Authentication using a Credential Cache to store the authentication
 CredentialCache GetCredential(string uri, string username, string password)
 {
     // ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
     var credentialCache = new CredentialCache();
     credentialCache.Add(new System.Uri(uri), "Basic", new NetworkCredential(username, password));
     return credentialCache;
 }
		private HttpMessageHandler TryGetCredentialAndProxy(PackageSource packageSource) 
        {
            Uri uri = new Uri(packageSource.Source);
            var proxy = ProxyCache.Instance.GetProxy(uri);
            var credential = CredentialStore.Instance.GetCredentials(uri);

            if (proxy != null && proxy.Credentials == null) {
                proxy.Credentials = CredentialCache.DefaultCredentials;
            }

            if (credential == null && !String.IsNullOrEmpty(packageSource.UserName) && !String.IsNullOrEmpty(packageSource.Password)) 
            {
                var cache = new CredentialCache();
                foreach (var scheme in _authenticationSchemes)
                {
                    cache.Add(uri, scheme, new NetworkCredential(packageSource.UserName, packageSource.Password));
                }
                credential = cache;
            }

            if (proxy == null && credential == null) return null;
            else
            {
                if(proxy != null) ProxyCache.Instance.Add(proxy);
                if (credential != null) CredentialStore.Instance.Add(uri, credential);
                return new WebRequestHandler()
                {
                    Proxy = proxy,
                    Credentials = credential
                };
            }


        }
        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;
        }
示例#27
0
        /// <summary>
        /// <para>Issue an HTTP GET request to the given <paramref name="requestUrl"/>.</para>
        /// <para>The <paramref name="requestUrl"/> can contain query parameters 
        /// (name=value pairs).</para>
        /// </summary>
        /// <param name="requestUrl">The URL to issue the GET request to (with optional query 
        /// parameters)</param>
        /// <returns>The server response.</returns>
        /// <exception cref="HttpUtilsException">If an error issuing the GET request or parsing 
        /// the server response occurs.</exception>
        public string Get(String requestUrl)
        {
            try
            {
                Uri requestUri = new Uri(requestUrl);

                HttpWebRequest apiRequest = WebRequest.Create(requestUri) as HttpWebRequest;

                apiRequest.Method = "GET";
                apiRequest.KeepAlive = false;

                if (username != null && password != null)
                {
                    CredentialCache authCredentials = new CredentialCache();
                    authCredentials.Add(requestUri, "Basic", new NetworkCredential(username, password));
                    apiRequest.Credentials = authCredentials;
                }

                // Get response
                string apiResponse = "";
                using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    apiResponse = reader.ReadToEnd();
                }
                return apiResponse;
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                    log.Error("Get failed", e);
                throw new HttpUtilsException("Get failed", e);
            }
        }
示例#28
0
        //public void NavigateFull(string fullURL)
        //{
        //    ucWB1.WebBrowser.Navigate(fullURL, null, null, authHdr);
        //    tbAddress.Text = fullURL;
        //}

        public void NavigateMyServer(string relURL)
        {
            string address = myServer + relURL;

            Uri u = new Uri(address);

            if (AtMng.AppMan.UseProxy)
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

                System.Net.NetworkCredential nc = new System.Net.NetworkCredential(AtMng.AppMan.myUser, AtMng.AppMan.myFWPassword);
                Uri up = new Uri(AtMng.AppMan.ServerInfo.remoteUrl);
                cc.Add(up, "Digest", nc);
                cc.Add(up, "Basic", nc);


                System.Net.HttpWebRequest wcinit = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(up);


                wcinit.CookieContainer = jar;
                wcinit.Credentials     = cc;
                wcinit.PreAuthenticate = true;
                wcinit.UnsafeAuthenticatedConnectionSharing = true; //for kerberos
                try
                {
                    System.Net.HttpWebResponse hwinit = (System.Net.HttpWebResponse)wcinit.GetResponse();

                    hwinit.Close();
                    System.Diagnostics.Trace.WriteLine("Ready to start Lawmate...");
                }
                catch (Exception x)
                {
                    System.Diagnostics.Trace.WriteLine(x.Message);

                    //  return;
                }
                for (int i = 0; i < jar.GetCookies(u).Count; i++)
                {
                    Cookie c = jar.GetCookies(u)[i];
                    InternetSetCookie(address, c.Name, c.Value);
                }
            }


            ucWB1.WebBrowser.Navigate(u, null, null, authHdr);
            tbAddress.Text = address;
        }
示例#29
0
        static void Main( string[] args )
        {
            try
                {
                List<string> nonSwitchArgs = new List<string>();
                Dictionary<string, object> switchValues = new Dictionary<string, object>();

                parseArgs( args, nonSwitchArgs, switchValues );

                SecureString securePassword = passwordPrompt( "Password: "******"Basic", new NetworkCredential( (string)switchValues[ "username" ], Marshal.PtrToStringAuto( Marshal.SecureStringToBSTR( securePassword ) ) ) );
                webRequest.Credentials = credentialCache;

                webRequest.Method = "GET";
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                if ( webResponse.StatusCode != HttpStatusCode.OK )
                    {
                    Console.Error.WriteLine( webResponse.StatusDescription );
                    return;
                    }

                XmlDocument doc = new XmlDocument();
                string xml = new StreamReader( webResponse.GetResponseStream() ).ReadToEnd();
                if ( (bool)switchValues[ "xml" ] )
                    using ( new gmailConsoleColor( ConsoleColor.DarkCyan ) )
                        Console.WriteLine( xml );
                doc.LoadXml( xml );

                XmlNamespaceManager nsmgr = new XmlNamespaceManager( new NameTable() );
                nsmgr.AddNamespace( "atom", "http://purl.org/atom/ns#" );

                XmlNodeList nodes = doc.SelectNodes( "atom:feed/atom:entry", nsmgr );
                foreach ( XmlNode node in nodes )
                    {
                    DateTime received = DateTime.Parse( node.SelectSingleNode( "atom:issued", nsmgr ).InnerText );

                    using ( new gmailConsoleColor( ConsoleColor.Cyan ) )
                        Console.Write( "{0,8}", received.ToShortTimeString() );

                    using ( new gmailConsoleColor( ConsoleColor.Yellow ) )
                        Console.Write( " {0}", node.SelectSingleNode( "atom:title", nsmgr ).InnerText );

                    using ( new gmailConsoleColor( ConsoleColor.Magenta ) )
                        Console.WriteLine( " {0} <{1}>", node.SelectSingleNode( "atom:author/atom:name", nsmgr ).InnerText, node.SelectSingleNode( "atom:author/atom:email", nsmgr ).InnerText );

                    if ( (bool)switchValues[ "summary" ] )
                        using ( new gmailConsoleColor( ConsoleColor.Gray ) )
                            Console.WriteLine( "         {0}", node.SelectSingleNode( "atom:summary", nsmgr ).InnerText );
                    }
                }
            catch ( Exception ex )
                {
                Console.Error.WriteLine( ex.Message );
                }
        }
示例#30
0
        public static async Task <bool> DownloadRemoteImageFileAsync(string uri, string fileName, string username = null, string password = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            if (!string.IsNullOrEmpty(username))
            {
                //CredentialCacheの作成
                System.Net.CredentialCache cache = new System.Net.CredentialCache();
                //基本認証の情報を追加
                cache.Add(new Uri(uri),
                          "Basic",
                          new System.Net.NetworkCredential(username, password));
                //認証の設定
                request.Credentials = cache;
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                return(false);
            }

            // Check that the remote file was found. The ContentType
            // check is performed since a request for a non-existent
            // image file might be redirected to a 404-page, which would
            // yield the StatusCode "OK", even though the image was not
            // found.
            if ((response.StatusCode == HttpStatusCode.OK ||
                 response.StatusCode == HttpStatusCode.Moved ||
                 response.StatusCode == HttpStatusCode.Redirect) &&
                response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
            {
                // if the remote file was found, download it
                using (Stream inputStream = response.GetResponseStream())
                    using (Stream outputStream = File.OpenWrite(fileName))
                    {
                        byte[] buffer = new byte[4096];
                        int    bytesRead;
                        do
                        {
                            bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                            await outputStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                        } while (bytesRead != 0);
                    }
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#31
0
        public List <string> CreateLicenseServer(string id, string companyName, string productLine, int qty = 1, int currentDeviceCount = 0)
        {
            var devices = new List <string>();
            var fnoWs   = new v1ManageDeviceService();

            fnoWs.Url = EndPointUrl + "ManageDeviceService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;
            var deviceRq = new deviceDataType[qty];

            for (int i = 0; i < qty; i++)
            {
                deviceRq[i] = new deviceDataType();
                deviceRq[i].deviceIdentifier = new createDeviceIdentifier
                {
                    deviceType            = WSDeviceType.SERVER,
                    publisherName         = "oncenter",
                    deviceIdType          = deviceIdTypeType.STRING,
                    deviceId              = companyName + "-" + productLine + "-CLM-0" + (currentDeviceCount + 1).ToString(),
                    deviceIdTypeSpecified = true,
                };
                deviceRq[i].deployment          = deployment.CLOUD;
                deviceRq[i].deploymentSpecified = true;
                deviceRq[i].channelPartners     = new Devices.channelPartnerDataType[1];
                deviceRq[i].channelPartners[0]  = new Devices.channelPartnerDataType();
                deviceRq[i].channelPartners[0].organizationUnit                  = new Devices.organizationIdentifierType();
                deviceRq[i].channelPartners[0].organizationUnit.primaryKeys      = new Devices.organizationPKType();
                deviceRq[i].channelPartners[0].organizationUnit.primaryKeys.name = id;
                deviceRq[i].channelPartners[0].currentOwner          = true;
                deviceRq[i].channelPartners[0].currentOwnerSpecified = true;
                deviceRq[i].channelPartners[0].tierName = "bo.constants.partnertiernames.endcustomer";
                deviceRq[i].publisherIdName             = new publisherIdentifier
                {
                    name = "OnCenter"
                };
            }
            var resp = fnoWs.createDevice(deviceRq);

            if (resp.statusInfo.status == OpsEmbeddedStatusType.SUCCESS)
            {
                foreach (var d in resp.responseData)
                {
                    devices.Add(d.deviceId);
                }
            }
            else
            {
                throw new Exception(resp.failedData[0].reason);
            }

            return(devices);
        }
示例#32
0
        public ICredentials For(Uri location)
        {
            var networkCredential = new NetworkCredential(_username, _password);

            var credentials = new CredentialCache();
            credentials.Add(location, "Basic", networkCredential);

            return credentials;
        }
示例#33
0
        public Proxy(ProxyConfig _pxc)
        {
            pxc = _pxc;

            System.Diagnostics.Trace.WriteLine("Starting Lawmate gateway...");

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

            System.Uri u = new Uri(pxc.serverR.remoteUrl);// + "/");

            cc = new System.Net.CredentialCache();
            if (pxc.user.Contains("\\"))
            {
                cc.Add(u, "Negotiate", CredentialCache.DefaultNetworkCredentials);
            }
            else
            {
                System.Net.NetworkCredential nc = new System.Net.NetworkCredential(pxc.user, pxc.password);
                cc.Add(u, "Digest", nc);
                cc.Add(u, "Basic", nc);
            }

            System.Net.HttpWebRequest wcinit = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(u);
            jar = new CookieContainer();

            wcinit.CookieContainer = jar;
            wcinit.Credentials     = cc;
            wcinit.PreAuthenticate = true;
            wcinit.UnsafeAuthenticatedConnectionSharing = true; //for kerberos
            try
            {
                System.Net.HttpWebResponse hwinit = (System.Net.HttpWebResponse)wcinit.GetResponse();

                hwinit.Close();
                System.Diagnostics.Trace.WriteLine("Ready to start Lawmate...");
            }
            catch (Exception x)
            {
                System.Diagnostics.Trace.WriteLine(x.Message);

                return;
            }
        }
 private static HttpWebResponse RequestWithBasicAuth(string requestUriString, string userName, string password)
 {
     var request = (HttpWebRequest)WebRequest.Create(requestUriString);
     var credentialCache = new CredentialCache();
     credentialCache.Add(new Uri(new Uri(requestUriString).GetLeftPart(UriPartial.Authority)), "Basic", new NetworkCredential(userName, password));
     request.Credentials = credentialCache;
     request.PreAuthenticate = true;
     var response = (HttpWebResponse)request.GetResponse();
     return response;
 }
示例#35
0
 static CredentialCache Authorization(string username, string password)
 {
     CredentialCache cache = new CredentialCache ();
     NetworkCredential nc = new NetworkCredential ();
     nc.UserName = username;
     nc.Password = password;
     nc.Domain = String.Empty;
     cache.Add (baseUrl, "Basic", nc);
     return cache;
 }
示例#36
0
		public void SetUp (HttpClientTestContext ctx)
		{
			var config = (WebDavConfiguration)ctx.Fixture.Configuration;

			Server = new Uri (config.Server);

			var cache = new CredentialCache ();
			cache.Add (Server, "Digest", new NetworkCredential (config.UserName, config.Password));
			ctx.Handler.Credentials = cache;
		}
 public Logic()
 {
     this._Service = new ws_test.Test();
     CookieContainer cooks = new CookieContainer();
     _Service.CookieContainer = cooks;
     CredentialCache cache = new CredentialCache();
     cache.Add(new System.Uri(_Service.Url), "NTLM", new NetworkCredential("***", "***", "***.**"));
     _Service.UseDefaultCredentials=false;
     _Service.Credentials = cache;
     _Service.PreAuthenticate=true;
 }
示例#38
0
        static void Main(string[] args)
        {
            string WSKey = "WOpmr3C4RwHfRfDacAa8tHlrMwbVBc+YKJuyo5OXNls=";

            //Create an instance of the D365BC SOAP WS
            Customer_Service ws = new Customer_Service();

            ws.Url = "https://api.businesscentral.dynamics.com/v1.0/194e87bd-73c6-43c6-95d7-1ca48985db5e/WS/CRONUS%20IT/Page/Customer";
            //Handling authentication
            System.Net.CredentialCache myCredentials = new System.Net.CredentialCache();
            NetworkCredential          netCred       = new NetworkCredential("sdemiliani", WSKey);

            myCredentials.Add(new Uri(ws.Url), "Basic", netCred);
            ws.Credentials = myCredentials;

            //Read Customers
            List <Customer_Filter> filters = new List <Customer_Filter>();
            Customer_Filter        filter  = new Customer_Filter();

            filter.Field    = Customer_Fields.Country_Region_Code;
            filter.Criteria = "IT";
            filters.Add(filter);
            try
            {
                foreach (Customer customer in ws.ReadMultiple(filters.ToArray(), "", 0))
                {
                    Console.WriteLine("No: {0} Name: {1}", customer.No, customer.Name);
                }

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error retrieving Customers: {0} InnerException: {1}", ex.Message, ex.InnerException);
            }

            //Create the Customer record
            //Customer customer = new Customer();
            //customer.Name = "SOAP Customer 1";
            //customer.Address = "Viale Kennedy 87, Novara";
            //customer.Country_Region_Code = "IT";
            //customer.Blocked = Blocked.Invoice;
            //try
            //{
            //    //Start the Create method
            //    ws.Create(ref customer);
            //    Console.WriteLine("Customer {0} created successfully.", customer.No);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("Customer creation error: {0} InnerException: {1}", ex.Message, ex.InnerException);
            //}
        }
        public static string SendDataToSrv(string XmlRequest, out string StatusDescription, out HttpStatusCode StatusCode)
        {
            StatusDescription = "";
            StatusCode        = HttpStatusCode.OK;
            try
            {
                Utils.ToCardLog("FayRetailClient.SendDataToSrv Xml: " + XmlRequest);
                string     Login   = iniFile.FayRetailLogin;
                string     Pass    = iniFile.FayRetailPass;
                WebRequest request = WebRequest.Create(iniFile.FayRetailServer);

                System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
                credentialCache.Add(
                    new System.Uri(iniFile.FayRetailServer),
                    "Basic",
                    new System.Net.NetworkCredential(Login, Pass)
                    );

                request.Credentials = credentialCache;

                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(XmlRequest);
                request.ContentType   = "text/xml; encoding='utf-8'";
                request.ContentLength = byteArray.Length;
                request.Headers.Add(HttpRequestHeader.ContentEncoding, "UTF-8");
                //request.PreAuthenticate = true;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);

                Utils.ToCardLog("FayRetailClient.SendDataToSrv send xml2 " + iniFile.FayRetailServer);
                WebResponse response = request.GetResponse();
                dataStream.Close();
                StatusDescription = ((HttpWebResponse)response).StatusDescription;
                StatusCode        = ((HttpWebResponse)response).StatusCode;
                Utils.ToCardLog(String.Format("FayRetailClient.SendDataToSrv send xml StatusCode: {0}, StatusDescription: {1} ", StatusCode, StatusDescription));
                dataStream = response.GetResponseStream();
                StreamReader reader             = new StreamReader(dataStream);
                string       responseFromServer = reader.ReadToEnd();
                Utils.ToCardLog("FayRetailClient.SendDataToSrv response " + responseFromServer);
                reader.Close();
                dataStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (Exception e)
            {
                StatusCode        = HttpStatusCode.NoContent;
                StatusDescription = "Error FayRetailClient.SendDataToSrv " + e.Message;
                Utils.ToCardLog("Error FayRetailClient.SendDataToSrv " + e.Message);
                return("");
            }
        }
示例#40
0
        /// <summary>
        /// Cancels an appointment on someone's calendar
        /// </summary>
        public virtual void CancelAppointment()
        {
            System.Net.HttpWebRequest PROPPATCHRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(ServerName + "/exchange/" + Directory + "/Calendar/" + MeetingGUID.ToString() + ".eml");

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(ServerName + "/exchange/" + Directory + "/Calendar/" + MeetingGUID.ToString() + ".eml"),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(ServerName + "/exchange/" + Directory + "/Calendar/" + MeetingGUID.ToString() + ".eml"),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }

            PROPPATCHRequest.Credentials = MyCredentialCache;
            PROPPATCHRequest.Method      = "DELETE";
            System.Net.WebResponse PROPPATCHResponse = (System.Net.HttpWebResponse)PROPPATCHRequest.GetResponse();
            PROPPATCHResponse.Close();
        }
示例#41
0
        public List <string> GetLicenseServers(string accountNumber)
        {
            var respLicenseServers = new List <string>();
            var fnoWs = new v1ManageDeviceService();

            fnoWs.Url = EndPointUrl + "ManageDeviceService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;
            var getDeviceRq = new getDevicesRequestType();

            getDeviceRq.batchSize            = "100";
            getDeviceRq.pageNumber           = "1";
            getDeviceRq.deviceResponseConfig = new deviceResponseConfigRequestType {
                soldTo          = true,
                soldToSpecified = true,
            };
            getDeviceRq.queryParams = new getDevicesParametersType {
                isServer             = true,
                isServerSpecified    = true,
                organizationUnitName = new Devices.PartnerTierQueryType
                {
                    partnerTier = "bo.constants.partnertiernames.endcustomer",
                    searchType  = Devices.simpleSearchType.EQUALS,
                    value       = accountNumber
                }
            };
            var resp = fnoWs.getDevicesQuery(getDeviceRq);

            if (resp.statusInfo.status == OpsEmbeddedStatusType.SUCCESS)
            {
                foreach (var device in resp.responseData)
                {
                    if (device.soldTo != null)
                    {
                        if (device.soldTo.id == accountNumber)
                        {
                            respLicenseServers.Add(device.deviceIdentifier.deviceId);
                        }
                    }
                }
            }

            return(respLicenseServers);
        }
示例#42
0
        public bool  UpdateEntitlementLineItem(OrderEntitlementLineItem lineItem)
        {
            var fnoWs = new v1EntitlementOrderService();

            fnoWs.Url             = EndPointUrl + "EntitlementOrderService";
            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;

            var updateRq = new updateEntitlementLineItemDataType();

            updateRq.entitlementIdentifier = new entitlementIdentifierType {
                primaryKeys = new entitlementPKType {
                    entitlementId = lineItem.EntitlementId
                }
            };

            updateRq.autoDeploy          = true;
            updateRq.autoDeploySpecified = true;
            updateRq.lineItemData        = new updateLineItemDataType[] {
                new updateLineItemDataType {
                    activationId = new idType {
                        id                    = lineItem.ActivationId,
                        autoGenerate          = false,
                        autoGenerateSpecified = true
                    },
                    numberOfCopies = lineItem.Quantity.ToString(),
                    partNumber     = new partNumberIdentifierType
                    {
                        primaryKeys = new partNumberPKType
                        {
                            partId = lineItem.PartNumber
                        }
                    }
                }
            };

            var resp = fnoWs.updateEntitlementLineItem(new updateEntitlementLineItemDataType[] { updateRq });

            if (resp.statusInfo.status == Entitlement.StatusType.SUCCESS)
            {
                return(true);
            }
            return(false);
        }
示例#43
0
        public string CreateEntitlement(
            string organizationId, string ProductFamily = "")
        {
            List <createSimpleEntitlementDataType> rqData = new List <createSimpleEntitlementDataType>();
            var entitlementId = string.Empty;

            var fnoWs = new v1EntitlementOrderService();

            fnoWs.Url = EndPointUrl + "EntitlementOrderService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;

            var rqType = new createSimpleEntitlementRequestType();

            rqType.simpleEntitlement = new createSimpleEntitlementDataType[] {
                new createSimpleEntitlementDataType {
                    autoDeploy          = true,
                    autoDeploySpecified = true,
                    soldTo = organizationId,
                    entitlementAttributes = new Entitlement.attributeDescriptorType[] {
                        new Entitlement.attributeDescriptorType()
                        {
                            attributeName = "OCS_ProductFamily",
                            stringValue   = ProductFamily
                        }
                    },
                    entitlementId = new idType
                    {
                        autoGenerateSpecified = true,
                        autoGenerate          = true,
                    }
                }
            };
            var resp = fnoWs.createSimpleEntitlement(rqType);

            if (resp.statusInfo.status == Entitlement.StatusType.SUCCESS)
            {
                entitlementId = resp.responseData[0].entitlementId;
            }
            return(entitlementId);
        }
示例#44
0
        public string GetOrganization(string accountNumber)
        {
            var fnoWs = new v1UserOrgHierarchyService();

            fnoWs.Url = EndPointUrl + "UserOrgHierarchyService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;

            var rqType = new getOrganizationsQueryRequestType();

            rqType.batchSize   = "10";
            rqType.pageNumber  = "1";
            rqType.queryParams = new organizationQueryParametersType
            {
                orgName = new UserOrganizationHierachy.SimpleQueryType
                {
                    searchType = UserOrganizationHierachy.simpleSearchType.EQUALS,
                    value      = accountNumber
                }
            };

            var resp = fnoWs.getOrganizationsQuery(rqType);

            if (resp.statusInfo.status == UserOrganizationHierachy.StatusType.SUCCESS)
            {
                if (resp.responseData != null)
                {
                    return(resp.responseData[0].organization.uniqueId);
                }
                else
                {
                    return(string.Empty);
                }
            }
            else
            {
                return(string.Empty);
            }
        }
示例#45
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string username         = "******";
        string password         = "******";
        string usernamePassword = username + ":" + password;

        string url        = "http://api.t.sina.com.cn/statuses/update.json";
        string news_title = "VS2010网剧合集:讲述程序员的爱情故事";
        int    news_id    = 62747;
        string t_news     = string.Format("{0},http://news.cnblogs.com/n/{1}/", news_title, news_id);
        string data       = "source=3854961754&status=" + System.Web.HttpUtility.UrlEncode(t_news);

        System.Net.WebRequest     webRequest  = System.Net.WebRequest.Create(url);
        System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest;

        System.Net.CredentialCache myCache = new System.Net.CredentialCache();
        myCache.Add(new Uri(url), "Basic", new System.Net.NetworkCredential(username, password));
        httpRequest.Credentials = myCache;
        httpRequest.Headers.Add("Authorization", "Basic " +
                                Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(usernamePassword)));


        httpRequest.Method      = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        System.Text.Encoding encoding = System.Text.Encoding.ASCII;
        byte[] bytesToPost            = encoding.GetBytes(data);
        httpRequest.ContentLength = bytesToPost.Length;
        System.IO.Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytesToPost, 0, bytesToPost.Length);
        requestStream.Close();

        System.Net.WebResponse wr            = httpRequest.GetResponse();
        System.IO.Stream       receiveStream = wr.GetResponseStream();
        using (System.IO.StreamReader reader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8))
        {
            string responseContent = reader.ReadToEnd();
            Response.Write(responseContent);
        }
    }
示例#46
0
        public string GetLicenseServerAccountNumber(string deviceId)
        {
            var accountNumber = string.Empty;
            var fnoWs         = new v1ManageDeviceService();

            fnoWs.Url = EndPointUrl + "ManageDeviceService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;
            var getDeviceRq = new getDevicesRequestType();

            getDeviceRq.batchSize            = "1";
            getDeviceRq.pageNumber           = "1";
            getDeviceRq.deviceResponseConfig = new deviceResponseConfigRequestType
            {
                soldTo          = true,
                soldToSpecified = true,
            };
            getDeviceRq.queryParams = new getDevicesParametersType
            {
                deviceId = new Devices.SimpleQueryType
                {
                    searchType = Devices.simpleSearchType.EQUALS,
                    value      = deviceId
                },
            };
            var resp = fnoWs.getDevicesQuery(getDeviceRq);

            if (resp.statusInfo.status == OpsEmbeddedStatusType.SUCCESS)
            {
                accountNumber = resp.responseData[0].soldTo.id;
            }

            return(accountNumber);
        }
示例#47
0
        public string CreateOrganization(string CompanyName, string accountNumber)
        {
            var fnoWs = new v1UserOrgHierarchyService();

            fnoWs.Url = EndPointUrl + "UserOrgHierarchyService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;

            var rqType = new createOrgRequestType();


            var orgDataType = new List <organizationDataType>();

            orgDataType.Add(new organizationDataType
            {
                name        = accountNumber,
                displayName = CompanyName,
                orgType     = OrgType.CUSTOMER
            });

            rqType.organization = orgDataType.ToArray();
            var resp = fnoWs.createOrganization(rqType);

            if (resp.statusInfo.status == UserOrganizationHierachy.StatusType.SUCCESS)
            {
                return(resp.responseData[0].uniqueId);
            }
            else
            {
                throw new Exception(resp.statusInfo.reason);
            }
        }
        /// <summary>
        /// Returns a user's contacts
        /// </summary>
        /// <param name="UserName">User name</param>
        /// <param name="Password">Password</param>
        /// <param name="Directory">Directory</param>
        /// <param name="Server">Server name</param>
        /// <returns></returns>
        public static List <VCard> GetContacts(string UserName, string Password, string Directory, string Server)
        {
            List <VCard> ReturnArray = new List <VCard>();
            string       Uri         = string.Format("http://{0}/exchange/{1}/contacts/", Server, Directory);

            byte[] Contents = System.Text.Encoding.UTF8.GetBytes(string.Format(
                                                                     @"<?xml version=""1.0""?>
                    <g:searchrequest xmlns:g=""DAV:"">
                        <g:sql>
                            SELECT
                                ""urn:schemas:contacts:givenName"", ""urn:schemas:contacts:sn"",
                                ""urn:schemas:contacts:email1"",""urn:schemas:contacts:businesshomepage"",
                                ""urn:schemas:contacts:title"",""urn:schemas:contacts:telephoneNumber"",
                                ""urn:schemas:contacts:o""
                            FROM
                                Scope('SHALLOW TRAVERSAL OF ""http://{0}/exchange/{1}/contacts/""')
                        </g:sql>
                    </g:searchrequest>",
                                                                     Server, Directory));



            HttpWebRequest Request = HttpWebRequest.Create(Uri) as HttpWebRequest;

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(Uri),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(Uri),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }
            Request.Credentials   = MyCredentialCache;
            Request.Method        = "SEARCH";
            Request.ContentLength = Contents.Length;
            Request.ContentType   = "text/xml";

            using (System.IO.Stream RequestStream = Request.GetRequestStream())
            {
                RequestStream.Write(Contents, 0, Contents.Length);
                using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse)
                {
                    using (System.IO.Stream ResponseStream = Response.GetResponseStream())
                    {
                        XmlDocument Document = new XmlDocument();
                        Document.Load(ResponseStream);
                        foreach (XmlElement PropStat in Document.GetElementsByTagName("a:propstat"))
                        {
                            if (PropStat.GetElementsByTagName("a:status")[0].InnerText.Contains("200 OK"))
                            {
                                foreach (XmlElement Element in PropStat.GetElementsByTagName("a:prop"))
                                {
                                    VCard TempCard = new VCard();
                                    if (Element["d:sn"] != null)
                                    {
                                        TempCard.LastName = Element["d:sn"].InnerText;
                                    }
                                    if (Element["d:givenName"] != null)
                                    {
                                        TempCard.FirstName = Element["d:givenName"].InnerText;
                                    }
                                    if (Element["d:email1"] != null)
                                    {
                                        TempCard.Email = Element["d:email1"].InnerText.Replace("\"", "");
                                    }
                                    if (Element["d:businesshomepage"] != null)
                                    {
                                        TempCard.Url = Element["d:businesshomepage"].InnerText;
                                    }
                                    if (Element["d:title"] != null)
                                    {
                                        TempCard.Title = Element["d:title"].InnerText;
                                    }
                                    if (Element["d:telephoneNumber"] != null)
                                    {
                                        TempCard.DirectDial = Element["d:telephoneNumber"].InnerText;
                                    }
                                    if (Element["d:o"] != null)
                                    {
                                        TempCard.Organization = Element["d:o"].InnerText;
                                    }
                                    ReturnArray.Add(TempCard);
                                }
                            }
                        }
                    }
                }
            }
            return(ReturnArray);
        }
示例#49
0
        ////////////////////////////////////////////////////////
        // Startup
        public bool Start(string sServerAddress, string sUserName, string sUserPassword)
        {
            m_PSI     = new PSI();
            m_sPSIUrl = sServerAddress;
            m_PSI.Url = m_sPSIUrl;

            m_sPSIUser = sUserName;
            m_sPSIPass = sUserPassword;

            m_log.Log("BcmControl.Start PSIUrl=" + m_sPSIUrl);

            if (Util.IsNullOrEmpty(m_sPSIUser) || Util.IsNullOrEmpty(m_sPSIPass))
            {
                m_log.Log("Using empty credentials for PSI (no user/password set)");
            }
            else
            {
                m_log.Log("Using credentials for PSI " + m_sPSIUser + "," + m_sPSIPass);
                m_CCache = new System.Net.CredentialCache();
                m_CCache.Add(new System.Uri(m_sPSIUrl), "Basic", new System.Net.NetworkCredential(m_sPSIUser, m_sPSIPass));
                m_PSI.Credentials = m_CCache;
            }

            try
            {
                CreateSessionResult r;
                string stmp;

                r = m_PSI.CreateSession();

                m_PSI_Session = r.SessionID;
                m_log.Log("Created PSI session " + m_PSI_Session);


                if (GetProfileConfig() == false)
                {
                    m_log.Log("Cannot get profile configuration, ending...");
                    return(false);
                }
                if (GetUserConfig() == false)
                {
                    m_log.Log("Cannot get user configuration, ending...");
                    return(false);
                }

                m_EvtFlags = EventFlags.All;
                string stype = m_CFG.GetParameter("EventFlags", "All");
                if (stype == "Call_and_Login")
                {
                    m_EvtFlags = EventFlags.Call_and_Login;
                }
                if (stype == "Call")
                {
                    m_EvtFlags = EventFlags.Call;
                }
                if (stype == "Call_and_Service")
                {
                    m_EvtFlags = EventFlags.Call_and_Service;
                }
                if (stype == "Login")
                {
                    m_EvtFlags = EventFlags.Login;
                }
                if (stype == "Login_and_Service")
                {
                    m_EvtFlags = EventFlags.Login_and_Service;
                }

                stmp = m_CFG.GetParameter("BCM_LyncStateAsEntry", "0");
                if (stmp == "1")
                {
                    stmp = m_CFG.GetParameter("BCM_DB_Directory", "none");
                    if (stmp.Length > 0 && stmp != "none")
                    {
                        m_BcmDB = new Bcm_DB();
                        m_BcmDB.init(m_CFG, m_log, stmp);
                        m_use_dir_entry = 1;
                    }
                }
            }
            catch (Exception x)
            {
                m_log.Log("Error in Bcm_Control start - cannot create session for PSI (" + x + ")");
                return(false);
            }
            return(true);
        }
示例#50
0
        /// <summary>
        /// Sends the service request.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public bool SendServiceRequest(IHttpCommand context)
        {
            bool success = false;

            SetSslConfiguration();

            // Create user task folder url
            System.Net.HttpWebRequest req = CreateServiceRequest(context);

            // Setting security properties
            // Validate if uses BasicAuthentication
            if (context.BasicAuthentication == null)
            {
                if (context.CurrentHttpSettings.UseNetworkCredentials)
                {
                    req.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    req.Credentials = CredentialCache.DefaultCredentials;
                }
            }
            else
            {
                System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
                credentialCache.Add(req.RequestUri, "Basic", context.BasicAuthentication);
                req.Credentials = credentialCache;
            }

            // HttpClient properties
            // req.Headers.Add("Cookie", cookies);
            req.AllowAutoRedirect      = true;
            req.Method                 = context.Method;
            req.ContentType            = context.CurrentHttpSettings.ContentType;
            req.AutomaticDecompression = DecompressionMethods.GZip;
            req.Referer                = context.Referer;
            req.KeepAlive              = context.KeepAlive;

            // Cookie handling
            if (coookieContainer.Count > 0)
            {
                if (context.Cookies != null)
                {
                    coookieContainer.Add(context.Cookies);
                }
                req.CookieContainer = coookieContainer;
            }

            // Set the user-agent headers
            req.UserAgent = _userAgent;

            if (context.CurrentHttpSettings.UserAgent.Length > 0)
            {
                req.UserAgent = context.CurrentHttpSettings.UserAgent;
            }

            // Write message
            if (context.DoWriteStream)
            {
                byte[] bytes = context.StreamMessage;
                req.ContentLength = bytes.Length;
                Stream requestStream = req.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }

            // Get web response
            HttpWebResponse response      = null;
            string          messageResult = string.Empty;

            try
            {
                //req.Timeout = 1000 * 60;
                response = (HttpWebResponse)req.GetResponse();
                using (Stream resStream = response.GetResponseStream())
                {
                    Encoding encode = System.Text.Encoding.GetEncoding(context.CurrentHttpSettings.ResponseEncoding);
                    using (StreamReader sr = new StreamReader(resStream, encode))
                    {
                        messageResult = sr.ReadToEnd();
                    }
                }
            }
            catch
            {
                if (response != null)
                {
                    response.Close();
                }
                throw;
            }

            // Validate set-cookie
            if (response.Headers["Set-Cookie"] != null)
            {
                try
                {
                    string[] cookie = response.Headers["Set-Cookie"].Split(';');
                    coookieContainer.Add(
                        new Cookie(cookie[0].Split('=')[0], cookie[0].Split('=')[1], "/", response.ResponseUri.Authority)
                        );
                }
                catch
                {
                    // ignore
                }
            }

            coookieContainer.Add(response.Cookies);

            context.WebHeaders        = response.Headers;
            context.ResponseUri       = response.ResponseUri;
            context.StatusCode        = response.StatusCode;
            context.StatusDescription = response.StatusDescription;

            response.Close();


            // Validate result
            try
            {
                if (context.ValidateMethod != null)
                {
                    context.ValidateMethod(messageResult, context);
                }
                success = true;
            }
            catch
            {
                success = false;
            }


            return(success);
        }
示例#51
0
        public Data executeRequest(string name, List <Parameter> parameters, string connectionString)
        {
            var parametros = "";

            foreach (var p in parameters)
            {
                if (p.localizacion == 2)
                {
                    parametros += p.valor + ",";
                }
            }

            var uri = new Uri(connectionString + name + "/" + (parametros.Length > 0 ? parametros.Substring(0, parametros.Length - 1) : ""));


            var http      = (HttpWebRequest)HttpWebRequest.Create(uri);
            var byteArray = new UTF8Encoding().GetBytes(ConfigurationManager.AppSettings["UserSICOM"] + ":" + ConfigurationManager.AppSettings["PasswordSICOM"]);

            http.Method = "POST";
            if (ConfigurationManager.AppSettings["ApiCredentials"] == "True")
            {
                var credentialCache = new System.Net.CredentialCache();
                credentialCache.Add(
                    uri,
                    "Basic",
                    new System.Net.NetworkCredential(ConfigurationManager.AppSettings["User"], ConfigurationManager.AppSettings["Password"])
                    );
                http.Credentials = credentialCache;
            }



            http.ContentType = "application/json; charset=utf-8";
            foreach (var p in parameters)
            {
                if (p.localizacion == 1)
                {
                    http.Headers.Add(p.nombre, p.valor);
                }
                if (p.localizacion == 3)
                {
                    using (var streamWriter = new StreamWriter(http.GetRequestStream()))
                    {
                        streamWriter.Write(p.valor);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                }
            }
            try
            {
                var response = (HttpWebResponse)http.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                {
                    var Data = new Data();
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        var responseJson = sr.ReadToEnd();

                        var jObj = JObject.Parse(responseJson);
                        return(DataBuilder.getData(jObj));
                    }
                }
                else
                {
                    var jObj = JObject.Parse("{\"estado\":\"" + response.StatusDescription + "\"}");
                    return(DataBuilder.getData(jObj));
                }
            }
            catch (Exception e)
            {
                JObject jObj = JObject.Parse("{\"estado\":\"error\"}");
                return(DataBuilder.getData(jObj));
            }
        }
示例#52
0
        /// <summary>
        /// Adds an appointment to a user's calendar
        /// </summary>
        public virtual void AddAppointment()
        {
            string XMLNSInfo = "xmlns:g=\"DAV:\" "
                               + "xmlns:e=\"http://schemas.microsoft.com/exchange/\" "
                               + "xmlns:mapi=\"http://schemas.microsoft.com/mapi/\" "
                               + "xmlns:mapit=\"http://schemas.microsoft.com/mapi/proptag/\" "
                               + "xmlns:x=\"xml:\" xmlns:cal=\"urn:schemas:calendar:\" "
                               + "xmlns:dt=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\" "
                               + "xmlns:header=\"urn:schemas:mailheader:\" "
                               + "xmlns:mail=\"urn:schemas:httpmail:\"";

            string CalendarInfo = "<cal:location>" + Location + "</cal:location>"                                                                               // + Location + "</cal:location>"
                                  + "<cal:dtstart dt:dt=\"dateTime.tz\">" + StartDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.000Z") + "</cal:dtstart>" // + StartDate.ToUniversalTime().ToString("yyyyMMddTHHmmssZ") + "</cal:dtstart>"
                                  + "<cal:dtend dt:dt=\"dateTime.tz\">" + EndDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.000Z") + "</cal:dtend>"       // + EndDate.ToUniversalTime().ToString("yyyyMMddTHHmmssZ") + "</cal:dtend>"
                                  + "<cal:instancetype dt:dt=\"int\">0</cal:instancetype>"
                                  + "<cal:busystatus>" + Status + "</cal:busystatus>"
                                  + "<cal:meetingstatus>CONFIRMED</cal:meetingstatus>"
                                  + "<cal:alldayevent dt:dt=\"boolean\">0</cal:alldayevent>"
                                  + "<cal:responserequested dt:dt=\"boolean\">1</cal:responserequested>"
                                  + "<cal:reminderoffset dt:dt=\"int\">900</cal:reminderoffset>"
                                  + "<cal:uid>" + MeetingGUID.ToString("B") + "</cal:uid>";

            string HeaderInfo = "<header:to>" + AttendeeList.ToString() + "</header:to>";

            string MailInfo = "<mail:subject>" + Subject + "</mail:subject>"
                              + "<mail:htmldescription>" + Summary + "</mail:htmldescription>";

            string AppointmentRequest = "<?xml version=\"1.0\"?>"
                                        + "<g:propertyupdate " + XMLNSInfo + ">"
                                        + "<g:set><g:prop>"
                                        + "<g:contentclass>urn:content-classes:appointment</g:contentclass>"
                                        + "<e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>"
                                        + MailInfo
                                        + CalendarInfo
                                        + HeaderInfo
                                        + "<mapi:finvited dt:dt=\"boolean\">1</mapi:finvited>"
                                        + "</g:prop></g:set>"
                                        + "</g:propertyupdate>";

            System.Net.HttpWebRequest PROPPATCHRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(ServerName + "/exchange/" + Directory + "/Calendar/" + MeetingGUID.ToString() + ".eml");

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(ServerName + "/exchange/" + Directory + "/Calendar/" + MeetingGUID.ToString() + ".eml"),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(ServerName + "/exchange/" + Directory + "/Calendar/" + MeetingGUID.ToString() + ".eml"),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }

            PROPPATCHRequest.Credentials = MyCredentialCache;
            PROPPATCHRequest.Method      = "PROPPATCH";
            byte[] bytes = Encoding.UTF8.GetBytes((string)AppointmentRequest);
            PROPPATCHRequest.ContentLength = bytes.Length;
            using (System.IO.Stream PROPPATCHRequestStream = PROPPATCHRequest.GetRequestStream())
            {
                PROPPATCHRequestStream.Write(bytes, 0, bytes.Length);
                PROPPATCHRequestStream.Close();
                PROPPATCHRequest.ContentType = "text/xml";
                System.Net.WebResponse PROPPATCHResponse = (System.Net.HttpWebResponse)PROPPATCHRequest.GetResponse();
                PROPPATCHResponse.Close();
            }
        }
        /// <summary>
        /// Checks if a person/group of people are free for a specified time
        /// </summary>
        /// <param name="People">The people to check on</param>
        /// <param name="StartTime">The start time</param>
        /// <param name="EndTime">The end time</param>
        /// <param name="Interval">The interval in minutes at which to check (the minimum is 10 minutes)</param>
        /// <param name="UserName">The username of the person checking</param>
        /// <param name="Password">The password of the person checking</param>
        /// <param name="TimeZoneDifference">Time zone difference</param>
        /// <param name="Server">Server name</param>
        /// <returns>returns an array of bytes stating whether someone is free or not, a 1 means they are not free during that time and a 0 means they are free</returns>
        public static byte[] GetFreeBusyData(StringDictionary People, DateTime StartTime, DateTime EndTime, int Interval,
                                             string UserName, string Password, string Server, string TimeZoneDifference)
        {
            if (People.Count < 1)
            {
                return(null);
            }
            if (StartTime >= EndTime)
            {
                return(null);
            }
            string EmailAddresses = "";

            foreach (string Person in People.Values)
            {
                EmailAddresses += "&u=SMTP:" + Person;
            }
            string Url = Server + "/public/?cmd=freebusy&start=" + StartTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss") + TimeZoneDifference + "&end=" + EndTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss") + TimeZoneDifference + "&interval=" + Interval.ToString() + EmailAddresses;

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(Url),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password, "")
                                      );
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(Url),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }

            System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(Url);
            Request.Credentials       = MyCredentialCache;
            Request.Method            = "GET";
            Request.ContentType       = "text/xml; encoding='utf-8'";
            Request.UserAgent         = "Mozilla/4.0(compatible;MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)";
            Request.KeepAlive         = true;
            Request.AllowAutoRedirect = false;

            System.Net.WebResponse Response = (HttpWebResponse)Request.GetResponse();
            byte[] bytes = null;
            using (System.IO.Stream ResponseStream = Response.GetResponseStream())
            {
                XmlDocument ResponseXmlDoc = new XmlDocument();
                ResponseXmlDoc.Load(ResponseStream);
                XmlNodeList DisplayNameNodes = ResponseXmlDoc.GetElementsByTagName("a:item");
                if (DisplayNameNodes.Count > 0)
                {
                    for (int i = 0; i < DisplayNameNodes.Count; i++)
                    {
                        XmlNodeList Nodes = DisplayNameNodes[i].ChildNodes;
                        foreach (XmlNode Node in Nodes)
                        {
                            if (Node.Name == "a:fbdata")
                            {
                                bytes = new byte[Node.InnerText.Length];
                                for (int x = 0; x < Node.InnerText.Length; ++x)
                                {
                                    bytes[x] = byte.Parse(Node.InnerText[x].ToString());
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("Could not get free/busy data from the exchange server");
                }
                // Clean up.
                ResponseStream.Close();
                Response.Close();
            }
            return(bytes);
        }
        /// <summary>
        /// Returns a list of the user's calendar items.
        /// </summary>
        /// <param name="UserName">User name used for logging in</param>
        /// <param name="Password">Password for logging in</param>
        /// <param name="Directory">User's directory</param>
        /// <param name="StartDate">Date to start at</param>
        /// <param name="EndDate">Date to end at</param>
        /// <param name="Server">Server Name</param>
        /// <returns>A list of the user's calendar items in VCalendar format, between two date ranges</returns>
        public static List <VCalendar> GetCalendarItems(string UserName, string Password, string Server, string Directory, DateTime StartDate, DateTime EndDate)
        {
            List <VCalendar> ReturnArray = new List <VCalendar>();
            string           Uri         = string.Format("http://{0}/exchange/{1}/calendar/", Server, Directory);

            string Query = "<?xml version=\"1.0\"?>"
                           + "<g:searchrequest xmlns:g=\"DAV:\">"
                           + "<g:sql>SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\", "
                           + "\"urn:schemas:httpmail:textdescription\", "
                           + "\"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\", "
                           + "\"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\" "
                           + "FROM Scope('SHALLOW TRAVERSAL OF \"" + Uri + "\"') "
                           + "WHERE ((\"urn:schemas:calendar:dtstart\" &gt;= '" + StartDate.ToString("yyyy/MM/dd hh:mm:ss") + "' "
                           + "AND \"urn:schemas:calendar:dtstart\" &lt;= '" + EndDate.ToString("yyyy/MM/dd hh:mm:ss") + "') "
                           + "OR (\"urn:schemas:calendar:dtend\" &gt;= '" + StartDate.ToString("yyyy/MM/dd hh:mm:ss") + "' "
                           + "AND \"urn:schemas:calendar:dtstart\" &lt;= '" + EndDate.ToString("yyyy/MM/dd hh:mm:ss") + "')) "
                           + "AND \"DAV:contentclass\" = 'urn:content-classes:appointment' "
                           + "AND NOT \"urn:schemas:calendar:instancetype\" = 1 "
                           + "ORDER BY \"urn:schemas:calendar:dtstart\" ASC"
                           + "</g:sql></g:searchrequest>";

            byte[] Contents = System.Text.Encoding.UTF8.GetBytes(Query);

            HttpWebRequest Request = HttpWebRequest.Create(Uri) as HttpWebRequest;

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(Uri),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(Uri),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }
            Request.Credentials   = MyCredentialCache;
            Request.Method        = "SEARCH";
            Request.ContentLength = Contents.Length;
            Request.ContentType   = "text/xml";

            using (System.IO.Stream RequestStream = Request.GetRequestStream())
            {
                RequestStream.Write(Contents, 0, Contents.Length);

                using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse)
                {
                    using (System.IO.Stream ResponseStream = Response.GetResponseStream())
                    {
                        XmlDocument Document = new XmlDocument();
                        Document.Load(ResponseStream);
                        foreach (XmlElement Element in Document.GetElementsByTagName("a:prop"))
                        {
                            VCalendar Cal = new VCalendar();
                            if (Element["e:textdescription"] != null)
                            {
                                Cal.Description = Element["e:textdescription"].InnerText;
                            }
                            if (Element["e:subject"] != null)
                            {
                                Cal.Subject = Element["e:subject"].InnerText;
                            }
                            if (Element["d:location"] != null)
                            {
                                Cal.Location = Element["d:location"].InnerText;
                            }
                            if (Element["d:dtstart"] != null)
                            {
                                Cal.StartTime = DateTime.Parse(Element["d:dtstart"].InnerText);
                            }
                            if (Element["d:dtend"] != null)
                            {
                                Cal.EndTime = DateTime.Parse(Element["d:dtend"].InnerText);
                            }
                            ReturnArray.Add(Cal);
                        }
                    }
                }
            }
            return(ReturnArray);
        }
示例#55
0
        public EntitlementLineItemResponse AddLineItemToEntitlement(string entitlementId, OrderEntitlementLineItem lineItem)
        {
            var lineItemResp = new EntitlementLineItemResponse();
            var fnoWs        = new v1EntitlementOrderService();

            fnoWs.Url = EndPointUrl + "EntitlementOrderService";

            fnoWs.PreAuthenticate = true;
            CredentialCache   credCache = new System.Net.CredentialCache();
            NetworkCredential netCred   = new NetworkCredential(UserName, Password);

            credCache.Add(new Uri(fnoWs.Url), "Basic", netCred);
            fnoWs.Credentials = credCache;
            var entLineItem = new addOnlyEntitlementLineItemRequestType();

            entLineItem.opType   = Entitlement.CreateOrUpdateOperationType.CREATE_OR_UPDATE;
            entLineItem.lineItem = new addEntitlementLineItemDataType[] {
                new addEntitlementLineItemDataType {
                    autoDeploy            = true,
                    autoDeploySpecified   = true,
                    entitlementIdentifier = new entitlementIdentifierType {
                        primaryKeys = new entitlementPKType
                        {
                            entitlementId = entitlementId
                        }
                    },

                    lineItems = new createEntitlementLineItemDataType[] {
                        new createEntitlementLineItemDataType {
                            activationId = new idType
                            {
                                autoGenerate          = true,
                                autoGenerateSpecified = true
                            },
                            isPermanent          = lineItem.IsPerpertual,
                            isPermanentSpecified = true,
                            orderId        = lineItem.ProductRatePlanChargeId,
                            numberOfCopies = lineItem.Quantity.ToString(),

                            partNumber = new partNumberIdentifierType
                            {
                                primaryKeys = new partNumberPKType {
                                    partId = lineItem.PartNumber
                                }
                            },
                            startDate               = lineItem.EffectiveDate,
                            expirationDate          = lineItem.ExpirationDate,
                            expirationDateSpecified = lineItem.IsPerpertual? false : true
                        }
                    }
                }
            };
            var resp = fnoWs.createEntitlementLineItem(entLineItem);

            if (resp.statusInfo.status == Entitlement.StatusType.SUCCESS)
            {
                lineItemResp.ActivationCode        = resp.responseData[0].lineItemIdentifiers[0].primaryKeys.activationId;
                lineItemResp.EntitlementId         = resp.responseData[0].entitlementIdentifier.primaryKeys.entitlementId;
                lineItemResp.EntitlementLineItemId = resp.responseData[0].lineItemIdentifiers[0].uniqueId;
                lineItemResp.PartNumber            = lineItem.PartNumber;
                lineItemResp.ProductRateChargeId   = lineItem.ProductRatePlanChargeId;
                lineItemResp.TotalQty = lineItem.Quantity;
            }

            return(lineItemResp);
        }
        /// <summary>
        /// Returns a user's email messages from their inbox
        /// </summary>
        /// <param name="UserName">User name</param>
        /// <param name="Password">Password</param>
        /// <param name="Directory">Directory</param>
        /// <param name="Server">Server using</param>
        /// <returns>a list of messages</returns>
        public static List <Utilities.Web.Email.Message> GetEmail(string UserName, string Password, string Directory, string Server)
        {
            List <Utilities.Web.Email.Message> ReturnArray = new List <Utilities.Web.Email.Message>();
            string Uri = string.Format("http://{0}/exchange/{1}/inbox", Server, Directory);

            byte[] Contents = System.Text.Encoding.UTF8.GetBytes(string.Format(
                                                                     @"<?xml version=""1.0""?>
                    <g:searchrequest xmlns:g=""DAV:"">
                        <g:sql>
                            SELECT
                                ""urn:schemas:httpmail:subject"", ""urn:schemas:httpmail:to"",
                                ""urn:schemas:httpmail:from"",""urn:schemas:httpmail:htmldescription""
                            FROM
                                Scope('DEEP TRAVERSAL OF ""http://{0}/exchange/{1}/inbox""')
                            WHERE
                                ""DAV:contentclass"" = 'urn:content-classes:message'
                        </g:sql>
                    </g:searchrequest>",
                                                                     Server, Directory));



            HttpWebRequest Request = HttpWebRequest.Create(Uri) as HttpWebRequest;

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(Uri),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(Uri),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }
            Request.Credentials   = MyCredentialCache;
            Request.Method        = "SEARCH";
            Request.ContentLength = Contents.Length;
            Request.ContentType   = "text/xml";

            using (System.IO.Stream RequestStream = Request.GetRequestStream())
            {
                RequestStream.Write(Contents, 0, Contents.Length);

                using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse)
                {
                    using (System.IO.Stream ResponseStream = Response.GetResponseStream())
                    {
                        XmlDocument Document = new XmlDocument();
                        Document.Load(ResponseStream);
                        foreach (XmlElement Element in Document.GetElementsByTagName("a:prop"))
                        {
                            Utilities.Web.Email.Message TempMessage = new Utilities.Web.Email.Message();
                            if (Element["d:subject"] != null)
                            {
                                TempMessage.Subject = Element["d:subject"].InnerText;
                            }
                            if (Element["d:htmldescription"] != null)
                            {
                                TempMessage.Body = Element["d:htmldescription"].InnerText;
                            }
                            if (Element["d:to"] != null)
                            {
                                TempMessage.To = Element["d:to"].InnerText;
                            }
                            if (Element["d:from"] != null)
                            {
                                TempMessage.From = Element["d:from"].InnerText;
                            }
                            ReturnArray.Add(TempMessage);
                        }
                    }
                }
            }
            return(ReturnArray);
        }
示例#57
0
        //// start
        private void enumAttachments(string strMessageURI, string strUserName, string strPassword, string strDomain)
        {
            // Variables.
            System.Net.HttpWebRequest  Request;
            System.Net.WebResponse     Response;
            System.Net.CredentialCache MyCredentialCache;
            //string strMessageURI = "http://server/exchange/username/inbox/TestMessage.eml/";
            //string strUserName = "******";
            //string strPassword = "******";
            //string strDomain = "Domain";
            System.IO.Stream               ResponseStream = null;
            System.Xml.XmlDocument         ResponseXmlDoc = null;
            System.Xml.XmlNode             root           = null;
            System.Xml.XmlNamespaceManager nsmgr          = null;
            System.Xml.XmlNodeList         PropstatNodes  = null;
            System.Xml.XmlNodeList         HrefNodes      = null;
            System.Xml.XmlNode             StatusNode     = null;
            System.Xml.XmlNode             PropNode       = null;

            try
            {
                // Create a new CredentialCache object and fill it with the network
                // credentials required to access the server.
                MyCredentialCache = new System.Net.CredentialCache();
                MyCredentialCache.Add(new System.Uri(strMessageURI),
                                      "NTLM",
                                      new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
                                      );

                // Create the HttpWebRequest object.
                Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strMessageURI);

                // Add the network credentials to the request.
                Request.Credentials = MyCredentialCache;

                // Specify the method.
                Request.Method = "X-MS-ENUMATTS";

                // Send the X-MS-ENUMATTS method request and get the
                // response from the server.
                Response = (HttpWebResponse)Request.GetResponse();

                // Get the XML response stream.
                ResponseStream = Response.GetResponseStream();

                // Create the XmlDocument object from the XML response stream.
                ResponseXmlDoc = new System.Xml.XmlDocument();

                // Load the XML response stream.
                ResponseXmlDoc.Load(ResponseStream);

                // Get the root node.
                root = ResponseXmlDoc.DocumentElement;

                // Create a new XmlNamespaceManager.
                nsmgr = new System.Xml.XmlNamespaceManager(ResponseXmlDoc.NameTable);

                // Add the DAV: namespace, which is typically assigned the a: prefix
                // in the XML response body.  The namespaceses and their associated
                // prefixes are listed in the attributes of the DAV:multistatus node
                // of the XML response.
                nsmgr.AddNamespace("a", "DAV:");

                // Add the http://schemas.microsoft.com/mapi/proptag/ namespace, which
                // is typically assigned the d: prefix in the XML response body.
                nsmgr.AddNamespace("d", "http://schemas.microsoft.com/mapi/proptag/");

                // Use an XPath query to build a list of the DAV:propstat XML nodes,
                // corresponding to the returned status and properties of
                // the file attachment(s).
                PropstatNodes = root.SelectNodes("//a:propstat", nsmgr);

                // Use an XPath query to build a list of the DAV:href nodes,
                // corresponding to the URIs of the attachement(s) on the message.
                // For each DAV:href node in the XML response, there is an
                // associated DAV:propstat node.
                HrefNodes = root.SelectNodes("//a:href", nsmgr);

                // Attachments found?
                if (HrefNodes.Count > 0)
                {
                    // Display the number of attachments on the message.
                    Console.WriteLine(HrefNodes.Count + " attachments found...");

                    // Iterate through the attachment properties.
                    for (int i = 0; i < HrefNodes.Count; i++)
                    {
                        // Use an XPath query to get the DAV:status node from the DAV:propstat node.
                        StatusNode = PropstatNodes[i].SelectSingleNode("a:status", nsmgr);

                        // Check the status of the attachment properties.
                        if (StatusNode.InnerText != "HTTP/1.1 200 OK")
                        {
                            Console.WriteLine("Attachment: " + HrefNodes[i].InnerText);
                            Console.WriteLine("Status: " + StatusNode.InnerText);
                            Console.WriteLine("");
                        }
                        else
                        {
                            Console.WriteLine("Attachment: " + HrefNodes[i].InnerText);
                            Console.WriteLine("Status: " + StatusNode.InnerText);

                            // Get the CdoPR_ATTACH_FILENAME_W MAPI property tag,
                            // corresponding to the attachment file name.  The
                            // http://schemas.microsoft.com/mapi/proptag/ namespace is typically
                            // assigned the d: prefix in the XML response body.
                            PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x3704001f", nsmgr);
                            Console.WriteLine("Attachment name: " + PropNode.InnerText);

                            // Get the CdoPR_ATTACH_EXTENSION_W MAPI property tag,
                            // corresponding to the attachment file extension.
                            PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x3703001f", nsmgr);
                            Console.WriteLine("File extension: " + PropNode.InnerText);

                            // Get the CdoPR_ATTACH_SIZE MAPI property tag,
                            // corresponding to the attachment file size.
                            PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x0e200003", nsmgr);
                            Console.WriteLine("Attachment size: " + PropNode.InnerText);

                            Console.WriteLine("");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No attachments found.");
                }

                // Clean up.
                ResponseStream.Close();
                Response.Close();
            }
            catch (Exception ex)
            {
                // Catch any exceptions. Any error codes from the X-MS-ENUMATTS
                // method request on the server will be caught here, also.
                Console.WriteLine(ex.Message);
            }
        }