/// <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> /// <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); } }
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; } }
/// <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); } }
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; }
public ActionResult CustomerGetAll() { var requestUri = new Uri("http://localhost:44354//v1/Customers"); var credCache = new CredentialCache { { requestUri, "Basic",// "Digest", new NetworkCredential("Test", "Test_123", "localhost") } }; using (var clientHander = new HttpClientHandler { Credentials = credCache, PreAuthenticate = true }) using (var httpClient = new HttpClient(clientHander)) { for (var i = 0; i < 5; i++) { var responseTask = httpClient.GetAsync(requestUri); var bb = responseTask.Result.Content.ReadAsStringAsync(); responseTask.Result.EnsureSuccessStatusCode(); } } return Json(""); }
/// <summary> /// Initializes a new instance of the <see cref="GatewayWebRequester"/> class. /// </summary> /// <param name="credentials">The credentials.</param> /// <param name="contentType">Type of the content.</param> public GatewayWebRequester(ClusterCredentials credentials, string contentType = "application/x-google-protobuf") { _credentials = credentials; _contentType = contentType; _credentialCache = new CredentialCache(); InitCache(); }
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); }
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")); }
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; } } }
public Form1() { InitializeComponent(); Assembly asm = Assembly.GetExecutingAssembly(); Version v = Assembly.GetExecutingAssembly().GetName().Version; DateTime compileDate = new DateTime(2000, 1, 1).Add(new TimeSpan(v.Build * TimeSpan.TicksPerDay + v.Revision * TimeSpan.TicksPerSecond * 2)); if (TimeZone.IsDaylightSavingTime(compileDate, TimeZone.CurrentTimeZone.GetDaylightChanges(compileDate.Year))) { compileDate = compileDate.AddHours(1); } this.labelVersion.Text = String.Format("Build {0}", compileDate); cboVersion.SelectedIndex = 7; cboCorrectionLevel.SelectedIndex = 0; txtSize.Text = "10"; ServicePointManager.Expect100Continue = false; // Ignore Certificate validation failures (aka untrusted certificate + certificate chains) ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); myCredentialCache = new CredentialCache(); }
public string GetContent(string url) { var myReq = WebRequest.Create(url); var mycache = new CredentialCache { { new Uri(url), "Basic", new NetworkCredential(_userName, _password) } }; myReq.Credentials = mycache; myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(UserPass))); using (var wr = myReq.GetResponse()) { using (var receiveStream = wr.GetResponseStream()) { if (receiveStream != null) using (var reader = new StreamReader(receiveStream, Encoding.UTF8)) { return reader.ReadToEnd(); } } return "Error"; } }
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; }
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 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); }
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"); }
/// <summary> /// Method used for making an http GET call /// </summary> /// <param name="credentialsDetails">An object that encapsulates the Constant Contact credentials</param> /// <param name="contactURI">The URL for the call</param> /// <param name="strRequest">The request string representation</param> /// <param name="strResponse">The response string representation</param> /// <returns>The string representation of the response</returns> public static string CallServiceGet(CredentialsDetails credentialsDetails, string contactURI, out string strRequest, out string strResponse) { var loginCredentials = new CredentialCache { { new Uri("https://api.constantcontact.com/ws/customers/" + credentialsDetails.User), "Basic", new NetworkCredential( credentialsDetails.Key + "%" + credentialsDetails.User, credentialsDetails.Password) } }; var request = WebRequest.Create(contactURI); request.Credentials = loginCredentials; var response = (HttpWebResponse) request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); var xmlResponse = reader.ReadToEnd(); reader.Close(); response.Close(); strRequest = PrintRequestString(request, credentialsDetails, string.Empty); strResponse = xmlResponse; return xmlResponse; }
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(); }
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; }
// 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; }
/// <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> /// Constructor /// </summary> /// <param name="authManager">The authorization manager to use.</param> /// <param name="connectionInfo">Connection Information</param> internal HttpService(ApiAuthManager authManager, ConnectionInfo connectionInfo) { if (authManager == null) throw new ArgumentNullException("authManager"); if (connectionInfo == null) throw new ArgumentNullException("connectionInfo"); this.authManager = authManager; this.connectionInfo = connectionInfo; if (connectionInfo.AuthType == AuthorizationType.Basic) { Server = connectionInfo.Server; credentials = new CredentialCache { { connectionInfo.Server, "Basic", new NetworkCredential(connectionInfo.UserName, connectionInfo.Password) } }; } else if (connectionInfo.AuthType == AuthorizationType.ZSessionID) { Server = connectionInfo.Server; credentials = null; } else if (connectionInfo.AuthType == AuthorizationType.ApiKey) { Server = connectionInfo.Server; credentials = new CredentialCache { { connectionInfo.Server, "Basic", new NetworkCredential(connectionInfo.ApiKey, connectionInfo.ApiKey) } }; } }
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 }; } }
// 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; } }
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" }
public void DigestCredentials() { var requestUri = new Uri("http://localhost/DigestAuthDemo/"); var credCache = new CredentialCache { { new Uri("http://localhost/"), "Digest", new NetworkCredential("Test", "Test", "/") } }; using (var clientHander = new HttpClientHandler { Credentials = credCache, PreAuthenticate = true }) using (var httpClient = new HttpClient(clientHander)) { for (var i = 0; i < 5; i++) { var responseTask = httpClient.GetAsync(requestUri); responseTask.Result.EnsureSuccessStatusCode(); } } }
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; }
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; }
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 ); } }
public static int BufferChunkSize = 1024*8; // 8k? public static void AddBasicAuthCredentials(this WebRequest obj, string url, string username, string password) { if (credentialCache == null) { credentialCache = new CredentialCache(); } var uri = new Uri(url); credentialCache.Add(new Uri("{0}://{1}:{2}".format(uri.Scheme, uri.Host, uri.Port)), "Basic", new NetworkCredential(username, password)); }
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); } }
/// <summary> /// Uploads a file to zendesk and returns the corresponding token id. /// To upload another file to an existing token just pass in the existing token. /// </summary> /// <param name="file"></param> /// <param name="token"></param> /// <returns></returns> string UploadAttachment(ZenFile file, string token = "") { var requestUrl = _zenDeskUrl; if (!requestUrl.EndsWith("/")) { requestUrl += "/"; } requestUrl += string.Format("uploads.json?filename={0}", file.FileName); if (!string.IsNullOrEmpty(token)) { requestUrl += string.Format("&token={0}", token); } WebRequest req = WebRequest.Create(requestUrl); req.ContentType = file.ContentType; req.Method = "POST"; req.ContentLength = file.FileData.Length; var credentials = new System.Net.CredentialCache { { new System.Uri(_zenDeskUrl), "Basic", new System.Net.NetworkCredential(_user, _password) } }; req.Credentials = credentials; req.PreAuthenticate = true; req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired; var dataStream = req.GetRequestStream(); dataStream.Write(file.FileData, 0, file.FileData.Length); dataStream.Close(); WebResponse response = req.GetResponse(); dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); return(GetAttachmentToken(responseFromServer)); }
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; } }
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); } }
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); }
/// <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(); }
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 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\" >= '" + StartDate.ToString("yyyy/MM/dd hh:mm:ss") + "' " + "AND \"urn:schemas:calendar:dtstart\" <= '" + EndDate.ToString("yyyy/MM/dd hh:mm:ss") + "') " + "OR (\"urn:schemas:calendar:dtend\" >= '" + StartDate.ToString("yyyy/MM/dd hh:mm:ss") + "' " + "AND \"urn:schemas:calendar:dtstart\" <= '" + 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); }
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> /// 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(); } }
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)); } }
/// <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); }
/// <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); }
//////////////////////////////////////////////////////// // 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); }
/// <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); }
//// 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); } }
/// <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); }