/// <summary> /// Unfavorites a tweet /// </summary> /// <param name="provider">credential provider</param> /// <param name="id">the id of the tweet to unffavorite.</param> public static TwitterStatus DestroyFavorites(this CredentialProvider provider, long id) { var para = CreateParamList(); para.Add(new KeyValuePair <string, string>("id", id.ToString())); return(provider.GetStatus("favorites/destroy.json", CredentialProvider.RequestMethod.POST, para)); }
/// <summary> /// Get users /// </summary> private static IEnumerable <long> GetUserIds(this CredentialProvider provider, string partialUri, IEnumerable <KeyValuePair <string, string> > para, out long prevCursor, out long nextCursor) { prevCursor = 0; nextCursor = 0; var doc = provider.RequestAPIv1(partialUri, CredentialProvider.RequestMethod.GET, para); if (doc == null) { return(null); // request returns error ? } List <TwitterUser> users = new List <TwitterUser>(); var nc = doc.Root.Element("next_cursor"); if (nc != null) { nextCursor = (long)nc.ParseLong(); } var pc = doc.Root.Element("previous_cursor"); if (pc != null) { prevCursor = (long)pc.ParseLong(); } if (doc.Root.Element("ids") != null) { return(doc.Root.Element("ids").Elements().Select(n => n.ParseLong()).Where(n => n != 0)); } else { return(doc.Root.Elements().Select(n => n.ParseLong()).Where(n => n != 0)); } }
/// <summary> /// Get timeline with full parameters /// </summary> private static IEnumerable <TwitterStatus> GetTimeline(this CredentialProvider provider, string partialUri, long?sinceId, long?maxId, long?count, long?page, long?userId, string screenName) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); if (sinceId != null && sinceId.HasValue) { para.Add(new KeyValuePair <string, string>("since_id", sinceId.Value.ToString())); } if (maxId != null && maxId.HasValue) { para.Add(new KeyValuePair <string, string>("max_id", maxId.Value.ToString())); } if (count != null) { para.Add(new KeyValuePair <string, string>("count", count.ToString())); } if (page != null) { para.Add(new KeyValuePair <string, string>("page", page.ToString())); } if (userId != null) { para.Add(new KeyValuePair <string, string>("user_id", userId.ToString())); } para.Add(new KeyValuePair <string, string>("include_entities", "true")); return(provider.GetTimeline(partialUri, para)); }
/// <summary> /// Get friends timeline with full params /// </summary> public static IEnumerable <TwitterStatus> GetFriendsTimeline(this CredentialProvider provider, string id = null, long?sinceId = null, long?maxId = null, long?count = null, long?page = null) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); if (sinceId != null && sinceId.HasValue) { para.Add(new KeyValuePair <string, string>("since_id", sinceId.Value.ToString())); } if (maxId != null && maxId.HasValue) { para.Add(new KeyValuePair <string, string>("max_id", maxId.Value.ToString())); } if (count != null) { para.Add(new KeyValuePair <string, string>("count", count.ToString())); } if (page != null) { para.Add(new KeyValuePair <string, string>("page", page.ToString())); } if (!String.IsNullOrEmpty(id)) { para.Add(new KeyValuePair <string, string>("id", id.ToString())); } para.Add(new KeyValuePair <string, string>("include_entities", "true")); return(provider.GetTimeline("statuses/friends_timeline.json", para)); }
/// <summary> /// Get favorite timeline with full params /// </summary> public static IEnumerable <TwitterStatus> GetFavorites(this CredentialProvider provider, int count = 20) { var kvp = new List <KeyValuePair <string, string> >(); kvp.Add(new KeyValuePair <string, string>("count", count.ToString())); return(provider.GetTimeline("favorites/list.json", kvp)); }
private async Task RegisterUserCredential(HttpRequest request) { if (!request.Headers.ContainsKey("X-MS-TOKEN-AAD-ID-TOKEN")) { return; } var idToken = request.Headers["X-MS-TOKEN-AAD-ID-TOKEN"].FirstOrDefault(); var client = new HttpClient(); var expando = new System.Dynamic.ExpandoObject(); var dict = new Microsoft.AspNetCore.Routing.RouteValueDictionary(new { grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer", client_id = Environment.GetEnvironmentVariable("CLIENT_ID", EnvironmentVariableTarget.Process), client_secret = Environment.GetEnvironmentVariable("CLIENT_SECRET", EnvironmentVariableTarget.Process), assertion = request.Headers["X-MS-TOKEN-AAD-ID-TOKEN"].FirstOrDefault(), resource = "https://management.core.windows.net", requested_token_use = "on_behalf_of" }); var result = await client.PostAsync("https://login.microsoftonline.com/" + Environment.GetEnvironmentVariable("TENANT_ID", EnvironmentVariableTarget.Process) + "/oauth2/token", new FormUrlEncodedContent(dict.ToDictionary(k => k.Key, v => v.Value as string).ToList())); var resultObj = JsonConvert.DeserializeObject <TokenExchangeResponse>( await result.Content.ReadAsStringAsync()); CredentialProvider.Register( MultiCredentialProvider.CredentialType.UserCredential, resultObj.AccessToken, resultObj.ExpiresOnDateTime); }
internal StreamingConnection(StreamingCore core, CredentialProvider provider, HttpWebRequest usedRequest, Stream strm, int timeoutSec) { if (core == null) { throw new ArgumentNullException("core"); } if (provider == null) { throw new ArgumentNullException("provider"); } if (usedRequest == null) { throw new ArgumentException("usedRequest"); } if (strm == null) { throw new ArgumentNullException("strm"); } this.timeoutValue = timeoutSec; this.parentCore = core; this.Provider = provider; this.receiveStream = strm; this.usedRequest = usedRequest; this.streamReceiver = new Thread(StreamingThread); this.streamReceiver.Start(); // タイムアウト用タイマー timeoutTimer = new Timer(TimeoutCountUp, null, 1000, 1000); }
/// <summary> /// ストリーミング接続を行います。 /// </summary> public StreamingConnection ConnectNew( CredentialProvider provider, StreamingDescription desc) { HttpWebRequest request; var streaming = provider.RequestStreamingAPI( GetStreamingUri(desc.Type), GetStreamingMethod(desc.Type), BuildArguments(desc), out request); if (streaming == null) { throw new InvalidOperationException("接続に失敗しました。"); } var con = new StreamingConnection(this, provider, request, streaming, desc.Timeout); if (con == null) { throw new InvalidOperationException("受信開始に失敗しました。"); } lock (conLock) { connections.Add(con); } return(con); }
/// <summary> /// Get users /// </summary> private static IEnumerable <TwitterUser> GetUsers(this CredentialProvider provider, string partialUri, IEnumerable <KeyValuePair <string, string> > para, out long prevCursor, out long nextCursor) { prevCursor = 0; nextCursor = 0; var doc = provider.RequestAPIv1(partialUri, CredentialProvider.RequestMethod.GET, para); if (doc == null) { return(null); // request returns error ? } var users = new List <TwitterUser>(); var nc = doc.Root.Element("next_cursor"); if (nc != null) { nextCursor = (long)nc.ParseLong(); } var pc = doc.Root.Element("previous_cursor"); if (pc != null) { prevCursor = (long)pc.ParseLong(); } System.Diagnostics.Debug.WriteLine("GetUser:::" + Environment.NewLine + doc.ToString()); return(doc.Root.Element("users").Elements().Select(TwitterUser.FromNode).Where(s => s != null)); }
/// <exception cref="System.Exception"/> public static void ProvisionPasswordsToCredentialProvider() { FilePath testDir = new FilePath(Runtime.GetProperty("test.build.data", "target/test-dir" )); Configuration conf = new Configuration(); Path jksPath = new Path(testDir.ToString(), "test.jks"); string ourUrl = JavaKeyStoreProvider.SchemeName + "://file" + jksPath.ToUri(); FilePath file = new FilePath(testDir, "test.jks"); file.Delete(); conf.Set(CredentialProviderFactory.CredentialProviderPath, ourUrl); CredentialProvider provider = CredentialProviderFactory.GetProviders(conf)[0]; char[] keypass = new char[] { 'k', 'e', 'y', 'p', 'a', 's', 's' }; char[] storepass = new char[] { 's', 't', 'o', 'r', 'e', 'p', 'a', 's', 's' }; // create new aliases try { provider.CreateCredentialEntry(FileBasedKeyStoresFactory.ResolvePropertyName(SSLFactory.Mode .Server, FileBasedKeyStoresFactory.SslKeystorePasswordTplKey), storepass); provider.CreateCredentialEntry(FileBasedKeyStoresFactory.ResolvePropertyName(SSLFactory.Mode .Server, FileBasedKeyStoresFactory.SslKeystoreKeypasswordTplKey), keypass); // write out so that it can be found in checks provider.Flush(); } catch (Exception e) { Runtime.PrintStackTrace(e); throw; } }
/// <summary> /// Destroy friendship with someone /// </summary> /// <param name="provider">credential provider</param> /// <param name="userId">target user id</param> /// <param name="screenName">target user screen name</param> /// <remarks> /// user id or user screeen name must set. /// </remarks> public static TwitterUser DestroyFriendship(this CredentialProvider provider, long?userId = null, string screenName = null) { if (userId == null && String.IsNullOrEmpty(screenName)) { throw new ArgumentException("User id or screen name is must set."); } List <KeyValuePair <string, string> > arg = new List <KeyValuePair <string, string> >(); if (userId != null) { arg.Add(new KeyValuePair <string, string>("user_id", userId.ToString())); } if (!String.IsNullOrEmpty(screenName)) { arg.Add(new KeyValuePair <string, string>("screen_name", screenName)); } var ret = provider.RequestAPIv1("friendships/destroy.json", CredentialProvider.RequestMethod.POST, arg); if (ret != null && ret.Root != null) { return(TwitterUser.FromNode(ret.Root)); } else { return(null); } }
/// <summary> /// Create friendship with someone /// </summary> /// <param name="provider">credential provider</param> /// <param name="userId">target user id</param> /// <param name="screenName">target user screen name</param> /// <param name="follow">send his tweet to specified device</param> /// <remarks> /// user id or user screeen name must set. /// </remarks> public static TwitterUser CreateFriendship(this CredentialProvider provider, long?userId = null, string screenName = null, bool follow = false) { if (userId == null && String.IsNullOrEmpty(screenName)) { throw new ArgumentException("User id or screen name is must set."); } var para = CreateParamList(); if (userId != null) { para.Add(new KeyValuePair <string, string>("user_id", userId.ToString())); } if (!String.IsNullOrEmpty(screenName)) { para.Add(new KeyValuePair <string, string>("screen_name", screenName)); } if (follow) { para.Add(new KeyValuePair <string, string>("follow", "true")); } var ret = provider.RequestAPIv1("friendships/create.json", CredentialProvider.RequestMethod.POST, para); if (ret != null && ret.Root != null) { return(TwitterUser.FromNode(ret.Root)); } else { return(null); } }
/// <summary> /// Get direct messages with full params /// </summary> private static IEnumerable <TwitterDirectMessage> GetDirectMessages(this CredentialProvider provider, string partialUri, long?sinceId, long?maxId, long?count, long?page) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); if (sinceId != null && sinceId.HasValue) { para.Add(new KeyValuePair <string, string>("since_id", sinceId.Value.ToString())); } if (maxId != null && maxId.HasValue) { para.Add(new KeyValuePair <string, string>("max_id", maxId.Value.ToString())); } if (count != null && count.HasValue) { para.Add(new KeyValuePair <string, string>("count", count.Value.ToString())); } if (page != null && page.HasValue) { para.Add(new KeyValuePair <string, string>("page", page.Value.ToString())); } para.Add(new KeyValuePair <string, string>("include_entities", "true")); return(provider.GetDirectMessages(partialUri, para)); }
internal void EnqueueReceivedObject(CredentialProvider source, string json) { lock (waiterQueue) { waiterQueue.Enqueue(new Tuple <CredentialProvider, string>(source, json)); } jsonParseWaiter.Set(); }
public virtual void TestGetPassword() { FilePath testDir = new FilePath(Runtime.GetProperty("test.build.data", "target/test-dir" )); Configuration conf = new Configuration(); Path jksPath = new Path(testDir.ToString(), "test.jks"); string ourUrl = JavaKeyStoreProvider.SchemeName + "://file" + jksPath.ToUri(); FilePath file = new FilePath(testDir, "test.jks"); file.Delete(); conf.Set(CredentialProviderFactory.CredentialProviderPath, ourUrl); CredentialProvider provider = CredentialProviderFactory.GetProviders(conf)[0]; char[] keypass = new char[] { 'k', 'e', 'y', 'p', 'a', 's', 's' }; char[] storepass = new char[] { 's', 't', 'o', 'r', 'e', 'p', 'a', 's', 's' }; char[] trustpass = new char[] { 't', 'r', 'u', 's', 't', 'p', 'a', 's', 's' }; // ensure that we get nulls when the key isn't there NUnit.Framework.Assert.AreEqual(null, provider.GetCredentialEntry(DFSConfigKeys.DfsServerHttpsKeypasswordKey )); NUnit.Framework.Assert.AreEqual(null, provider.GetCredentialEntry(DFSConfigKeys.DfsServerHttpsKeystorePasswordKey )); NUnit.Framework.Assert.AreEqual(null, provider.GetCredentialEntry(DFSConfigKeys.DfsServerHttpsTruststorePasswordKey )); // create new aliases try { provider.CreateCredentialEntry(DFSConfigKeys.DfsServerHttpsKeypasswordKey, keypass ); provider.CreateCredentialEntry(DFSConfigKeys.DfsServerHttpsKeystorePasswordKey, storepass ); provider.CreateCredentialEntry(DFSConfigKeys.DfsServerHttpsTruststorePasswordKey, trustpass); // write out so that it can be found in checks provider.Flush(); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); throw; } // make sure we get back the right key directly from api Assert.AssertArrayEquals(keypass, provider.GetCredentialEntry(DFSConfigKeys.DfsServerHttpsKeypasswordKey ).GetCredential()); Assert.AssertArrayEquals(storepass, provider.GetCredentialEntry(DFSConfigKeys.DfsServerHttpsKeystorePasswordKey ).GetCredential()); Assert.AssertArrayEquals(trustpass, provider.GetCredentialEntry(DFSConfigKeys.DfsServerHttpsTruststorePasswordKey ).GetCredential()); // use WebAppUtils as would be used by loadSslConfiguration NUnit.Framework.Assert.AreEqual("keypass", DFSUtil.GetPassword(conf, DFSConfigKeys .DfsServerHttpsKeypasswordKey)); NUnit.Framework.Assert.AreEqual("storepass", DFSUtil.GetPassword(conf, DFSConfigKeys .DfsServerHttpsKeystorePasswordKey)); NUnit.Framework.Assert.AreEqual("trustpass", DFSUtil.GetPassword(conf, DFSConfigKeys .DfsServerHttpsTruststorePasswordKey)); // let's make sure that a password that doesn't exist returns null NUnit.Framework.Assert.AreEqual(null, DFSUtil.GetPassword(conf, "invalid-alias")); }
/// <summary> /// Starting streaming and get streaming controller. /// </summary> /// <param name="provider">using credential</param> /// <param name="type">type of streaming</param> /// <param name="delimitered">delimiter length</param> /// <param name="count">backlog count</param> /// <param name="follow">following user's id</param> /// <param name="track">tracking keywords</param> /// <param name="locations">location area of tweet</param> /// <param name="repliesAll">use @replies=all option</param> public static StreamingController BeginStreaming (CredentialProvider provider, StreamingType type, int? delimitered = null, int? count = null, string follow = null, string track = null, string locations = null, bool repliesAll = false) { CredentialProvider.RequestMethod reqmethod = CredentialProvider.RequestMethod.GET; // argument check switch (type) { case StreamingType.firehose: if (!String.IsNullOrWhiteSpace(follow) || !String.IsNullOrWhiteSpace(track) || !String.IsNullOrWhiteSpace(locations)) throw new ArgumentException("Invalid argument is setted."); break; case StreamingType.gardenhose: if (count != null && !String.IsNullOrWhiteSpace(follow) || !String.IsNullOrWhiteSpace(track) || !String.IsNullOrWhiteSpace(locations)) throw new ArgumentException("Invalid argument is setted."); break; case StreamingType.sample: if (count != null && !String.IsNullOrWhiteSpace(follow) || !String.IsNullOrWhiteSpace(track) || !String.IsNullOrWhiteSpace(locations)) throw new ArgumentException("Invalid argument is setted."); break; case StreamingType.birddog: if (!String.IsNullOrWhiteSpace(track) || !String.IsNullOrWhiteSpace(locations)) throw new ArgumentException("Invalid argument is setted."); reqmethod = CredentialProvider.RequestMethod.POST; break; case StreamingType.shadow: if (!String.IsNullOrWhiteSpace(track) || !String.IsNullOrWhiteSpace(locations)) throw new ArgumentException("Invalid argument is setted."); reqmethod = CredentialProvider.RequestMethod.POST; break; case StreamingType.filter: if (String.IsNullOrWhiteSpace(track) && String.IsNullOrWhiteSpace(follow)) throw new ArgumentException("You must set follow or track argument."); reqmethod = CredentialProvider.RequestMethod.POST; break; } List<KeyValuePair<string, string>> args = new List<KeyValuePair<string, string>>(); if (delimitered != null) args.Add(new KeyValuePair<string, string>("delimitered", delimitered.Value.ToString())); if (count != null) args.Add(new KeyValuePair<string, string>("count", count.Value.ToString())); if (!String.IsNullOrWhiteSpace(follow)) args.Add(new KeyValuePair<string, string>("follow", Tweak.CredentialProviders.OAuth.UrlEncode(follow, Encoding.UTF8, true))); if (!String.IsNullOrWhiteSpace(track)) args.Add(new KeyValuePair<string, string>("track", Tweak.CredentialProviders.OAuth.UrlEncode(track, Encoding.UTF8, true))); if (!String.IsNullOrWhiteSpace(locations)) args.Add(new KeyValuePair<string, string>("locations", Tweak.CredentialProviders.OAuth.UrlEncode(locations, Encoding.UTF8, true))); if (repliesAll) args.Add(new KeyValuePair<string, string>("replies", "all")); var strm = provider.RequestStreamingAPI(GetStreamingUri(type), reqmethod, args); if (strm != null) return new StreamingController(strm); else return null; }
/// <summary> /// Get status /// </summary> private static TwitterStatus GetStatus(this CredentialProvider provider, string partialUri, CredentialProvider.RequestMethod method, IEnumerable <KeyValuePair <string, string> > para) { var doc = provider.RequestAPIv1(partialUri, method, para); if (doc == null) { return(null); } return(TwitterStatus.FromNode(doc.Root)); }
public void ShouldProvideWithASecretKey() { //Given ICredentialProvider sut = new CredentialProvider(); //When var secretKey = sut.ClientSecret; //Then secretKey.Should().NotBeNullOrEmpty(); }
/// <summary> /// Get lists you following /// </summary> /// <param name="provider">credential provider</param> /// <param name="userScreenName">target user id</param> public static IEnumerable <TwitterList> GetFollowingListsAll(this CredentialProvider provider, string userScreenName) { var partialUri = "lists/list.json"; var para = new List <KeyValuePair <string, string> >(); if (!String.IsNullOrEmpty(userScreenName)) { para.Add(new KeyValuePair <string, string>("screen_name", userScreenName)); } return(provider.GetListsAll(partialUri, para)); }
public void ShouldProvideWithAClientId() { //Given ICredentialProvider sut = new CredentialProvider(); //When var clientId = sut.ClientId; //Then clientId.Should().NotBeNullOrEmpty(); }
/// <summary> /// Get users /// </summary> private static IEnumerable <TwitterUser> GetUsers(this CredentialProvider provider, string partialUri, IEnumerable <KeyValuePair <string, string> > para) { var doc = provider.RequestAPIv1(partialUri, CredentialProvider.RequestMethod.GET, para); if (doc == null) { return(null); // request returns error ? } System.Diagnostics.Debug.WriteLine("GetUsers ::: " + Environment.NewLine + doc); return(doc.Root.Element("users").Elements().Select(u => TwitterUser.FromNode(u)).Where(u => u != null)); }
/// <summary> /// Get user timeline with full params /// </summary> public static IEnumerable <TwitterStatus> GetUserTimeline(this CredentialProvider provider, string id = null, long?userId = null, string screenName = null, long?sinceId = null, long?maxId = null, long?count = null, long?page = null, bool?trimUser = null, bool?includeRts = null) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); if (sinceId != null && sinceId.HasValue) { para.Add(new KeyValuePair <string, string>("since_id", sinceId.Value.ToString())); } if (maxId != null && maxId.HasValue) { para.Add(new KeyValuePair <string, string>("max_id", maxId.Value.ToString())); } if (count != null) { para.Add(new KeyValuePair <string, string>("count", count.ToString())); } if (page != null) { para.Add(new KeyValuePair <string, string>("page", page.ToString())); } if (userId != null) { para.Add(new KeyValuePair <string, string>("user_id", userId.ToString())); } if (!String.IsNullOrEmpty(id)) { para.Add(new KeyValuePair <string, string>("id", id.ToString())); } if (!String.IsNullOrEmpty(screenName)) { para.Add(new KeyValuePair <string, string>("screen_name", screenName.ToString())); } if (trimUser != null) { para.Add(new KeyValuePair <string, string>("trim_user", "true")); } if (includeRts != null) { para.Add(new KeyValuePair <string, string>("include_rts", "true")); } para.Add(new KeyValuePair <string, string>("include_entities", "true")); return(provider.GetTimeline("statuses/user_timeline.json", para)); }
/// <summary> /// Get twitter timeline /// </summary> /// <param name="provider">credential provider</param> /// <param name="partialUri">partial uri</param> /// <param name="param">parameters</param> private static IEnumerable <TwitterStatus> GetTimeline(this CredentialProvider provider, string partialUri, IEnumerable <KeyValuePair <string, string> > param) { var doc = provider.RequestAPIv1(partialUri, CredentialProvider.RequestMethod.GET, param); if (doc == null) { return(null); } return(doc.Root.Elements() .Select(n => TwitterStatus.FromNode(n)) .Where(s => s != null)); }
private void ReinitConnections() { CredentialProvider.DeteteCredentialProviders(); ConnectionHandler.instance.OnConnectionStatusChanged -= OnConnectionStatusChanged; ConnectionHandler.Destroy(); if (ApplicationConfig.haapiAllowed) { HaapiManager.Initialize(); } ConnectionHandler.Initialize(); ConnectionHandler.instance.OnConnectionStatusChanged += OnConnectionStatusChanged; }
public void ShouldReturnAViagogoClient() { //Given var credentialProvider = new CredentialProvider(); var sut = new ViagogoApiProvider(credentialProvider, "MyApplication"); //When var client = sut.GetViagogoApiClient(); //Then client.Should().NotBe(null); }
public void ShouldInitANewToken() { //Given var credentialProvider = new CredentialProvider(); var sut = new ViagogoApiProvider(credentialProvider, "MyApplication"); //When var token = sut.GetToken(); //Then token.Should().NotBe(null); }
public async Task ShouldReceiveResultsFromViagogoApi() { var credentialProvider = new CredentialProvider(); //Given var sut = new ViagogoClient(new ProductHeaderValue(AppName), credentialProvider.ClientId, credentialProvider.ClientSecret); //When var root = await sut.Hypermedia.GetRootAsync(); //Then root.Should().NotBe(null); }
/// <summary> /// Get direct messages /// </summary> private static IEnumerable <TwitterDirectMessage> GetDirectMessages(this CredentialProvider provider, string partialUri, IEnumerable <KeyValuePair <string, string> > param) { var doc = provider.RequestAPIv1(partialUri, CredentialProvider.RequestMethod.GET, param); if (doc == null) { return(null); } List <TwitterStatus> statuses = new List <TwitterStatus>(); HashSet <string> hashes = new HashSet <string>(); return(doc.Root.Elements().Select(n => TwitterDirectMessage.FromNode(n)).Where(d => d != null)); }
public virtual void TestConfGetPassword() { FilePath testDir = new FilePath(Runtime.GetProperty("test.build.data", "target/test-dir" )); Configuration conf = new Configuration(); Path jksPath = new Path(testDir.ToString(), "test.jks"); string ourUrl = JavaKeyStoreProvider.SchemeName + "://file" + jksPath.ToUri(); FilePath file = new FilePath(testDir, "test.jks"); file.Delete(); conf.Set(CredentialProviderFactory.CredentialProviderPath, ourUrl); CredentialProvider provider = CredentialProviderFactory.GetProviders(conf)[0]; char[] bindpass = new char[] { 'b', 'i', 'n', 'd', 'p', 'a', 's', 's' }; char[] storepass = new char[] { 's', 't', 'o', 'r', 'e', 'p', 'a', 's', 's' }; // ensure that we get nulls when the key isn't there Assert.Equal(null, provider.GetCredentialEntry(LdapGroupsMapping .BindPasswordKey)); Assert.Equal(null, provider.GetCredentialEntry(LdapGroupsMapping .LdapKeystorePasswordKey)); // create new aliases try { provider.CreateCredentialEntry(LdapGroupsMapping.BindPasswordKey, bindpass); provider.CreateCredentialEntry(LdapGroupsMapping.LdapKeystorePasswordKey, storepass ); provider.Flush(); } catch (Exception e) { Runtime.PrintStackTrace(e); throw; } // make sure we get back the right key Assert.AssertArrayEquals(bindpass, provider.GetCredentialEntry(LdapGroupsMapping. BindPasswordKey).GetCredential()); Assert.AssertArrayEquals(storepass, provider.GetCredentialEntry(LdapGroupsMapping .LdapKeystorePasswordKey).GetCredential()); LdapGroupsMapping mapping = new LdapGroupsMapping(); Assert.Equal("bindpass", mapping.GetPassword(conf, LdapGroupsMapping .BindPasswordKey, string.Empty)); Assert.Equal("storepass", mapping.GetPassword(conf, LdapGroupsMapping .LdapKeystorePasswordKey, string.Empty)); // let's make sure that a password that doesn't exist returns an // empty string as currently expected and used to trigger a call to // extract password Assert.Equal(string.Empty, mapping.GetPassword(conf, "invalid-alias" , string.Empty)); }
internal StreamingConnection(StreamingCore core, CredentialProvider provider, Stream strm) { if (core == null) throw new ArgumentNullException("core"); if (provider == null) throw new ArgumentNullException("provider"); if (strm == null) throw new ArgumentNullException("strm"); this.parentCore = core; this.Provider = provider; this.receiveStream = strm; this.streamReceiver = new Thread(StreamingThread); this.streamReceiver.Start(); }
/// <summary> /// Delete a direct message which you sent /// </summary> /// <param name="provider">credential provider</param> /// <param name="id">destroy id</param> public static TwitterDirectMessage DestroyDirectMessage(this CredentialProvider provider, long id) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); para.Add(new KeyValuePair <string, string>("id", id.ToString())); var xmlDoc = provider.RequestAPIv1("direct_messages/destroy.json", CredentialProvider.RequestMethod.POST, para); if (xmlDoc == null) { return(null); } return(TwitterDirectMessage.FromNode(xmlDoc.Root)); }
/// <summary> /// ユーザー情報を取得します。 /// </summary> public static IEnumerable <TwitterUser> LookupUsers(this CredentialProvider provider, string[] screenNames = null, long[] ids = null) { if (screenNames == null && ids == null) { throw new ArgumentNullException("screenNameとid,両方をnullに設定することはできません。"); } if (screenNames != null) { return(provider.GetUsers("users/lookup.json", new[] { new KeyValuePair <string, string>("screen_name", String.Join(",", screenNames)) })); } else { return(provider.GetUsers("users/lookup.json", new[] { new KeyValuePair <string, string>("user_id", String.Join(",", ids.Select(l => l.ToString()))) })); } }
public override sealed System.Xml.Linq.XDocument RequestAPI(string uriParticle, CredentialProvider.RequestMethod method, IEnumerable<KeyValuePair<string, string>> param) { if (String.IsNullOrEmpty(uriParticle)) throw new ArgumentNullException(uriParticle); else if (uriParticle.Length < 5) throw new ArgumentException("uri is too short."); string target = TwitterUri + (uriParticle.EndsWith("/") ? uriParticle.Substring(1) : uriParticle); if (target.EndsWith("format")) target = target.Substring(0, target.Length - 6) + "xml"; else if (target.EndsWith("json")) target = target.Substring(0, target.Length - 4) + "xml"; try { var req = Http.CreateRequest(new Uri(target), true); req.Credentials = new System.Net.NetworkCredential(UserName, Password); var ret = Http.WebConnect<XDocument>( req, method.ToString(), null, new Http.DStreamCallbackFull<XDocument>((res) => { int rateLimit; if (int.TryParse(res.Headers["X-RateLimit-Limit"], out rateLimit)) { this.RateLimitMax = rateLimit; } int rateLimitRemaining; if (int.TryParse(res.Headers["X-RateLimit-Remaining"], out rateLimitRemaining)) { this.RateLimitRemaining = rateLimitRemaining; } long rateLimitReset; if (long.TryParse(res.Headers["X-RateLimit-Reset"], out rateLimitReset)) { this.RateLimitReset = UnixEpoch.GetDateTimeByUnixEpoch(rateLimitReset); } XDocument xd = null; try { using (var s = res.GetResponseStream()) { using (var sr = new StreamReader(s)) { xd = XDocument.Load(sr); } } } catch (XmlException) { throw; } return xd; })); if (ret.Succeeded && ret.Data != null) { return ret.Data; } else { if (ret.Exception != null) throw ret.Exception; else throw new WebException(ret.Message); } } catch (WebException we) { System.Diagnostics.Debug.WriteLine(we.ToString()); } catch (XmlException xe) { throw new Exceptions.TwitterXmlParseException(xe); } catch (IOException) { throw; } return null; }
//Implementation public override sealed XDocument RequestAPI(string uriParticle, CredentialProvider.RequestMethod method, IEnumerable<KeyValuePair<string,string>> param) { if (String.IsNullOrEmpty(uriParticle)) throw new ArgumentNullException(uriParticle); else if (uriParticle.Length < 5) throw new ArgumentException("uri is too short."); string target = TwitterUri + (uriParticle.EndsWith("/") ? uriParticle.Substring(1) : uriParticle); if (target.EndsWith("format")) target = target.Substring(0, target.Length - 6) + "json"; else if (target.EndsWith("xml")) target = target.Substring(0, target.Length - 3) + "json"; if(String.IsNullOrEmpty(Token) || String.IsNullOrEmpty(Secret)) { throw new Exceptions.TwitterOAuthRequestException("OAuth is not validated."); } var authuri = CreateUrl(target, method, param); try { var ret = Http.WebConnect<XDocument>( Http.CreateRequest(new Uri(authuri), true), method.ToString(), null, new Http.DStreamCallbackFull<XDocument>((res) => { int rateLimit; if (int.TryParse(res.Headers["X-RateLimit-Limit"], out rateLimit)) { this.RateLimitMax = rateLimit; } int rateLimitRemaining; if (int.TryParse(res.Headers["X-RateLimit-Remaining"], out rateLimitRemaining)) { this.RateLimitRemaining = rateLimitRemaining; } long rateLimitReset; if (long.TryParse(res.Headers["X-RateLimit-Reset"], out rateLimitReset)) { this.RateLimitReset = UnixEpoch.GetDateTimeByUnixEpoch(rateLimitReset); } XDocument xd = null; try { using (var s = res.GetResponseStream()) { using (var r = JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max)) { xd = XDocument.Load(r); } } } catch (XmlException) { throw; } return xd; })); if (ret.Succeeded && ret.Data != null) { return ret.Data; } else { if (ret.Exception != null) throw ret.Exception; else throw new WebException(ret.Message); } } catch (WebException we) { System.Diagnostics.Debug.WriteLine(we.ToString()); } catch (XmlException xe) { throw new Exceptions.TwitterXmlParseException(xe); } catch (IOException) { throw; } return null; }