public OAuthParameters( ConsumerKey key, TokenKey tokenKey, string signatureMethod, TimestampSequence timestamps, NonceSequence nonces, string signature, string version, string verifier = null, string session = null, bool renewToken = false ) { _key = key; _tokenKey = tokenKey; _signatureMethod = signatureMethod; _signature = signature; _session = session; _verifier = verifier; _version = version ?? "1.0"; _nonce = nonces.Next(); _timestamp = timestamps.Next(); _renewToken = renewToken; }
public virtual void LoadSettings() { try { string doc = Utils.ResourceHelper.GetEmbeddedTextFile("/OKAPI/ConsumerKeys.xml"); XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(doc); XmlNode n = xdoc.SelectSingleNode(string.Format("/keys/{0}", GeocodePrefix)); if (n != null) { ConsumerKey = n.SelectSingleNode("ConsumerKey").InnerText; ConsumerSecret = n.SelectSingleNode("ConsumerSecret").InnerText; } if (ConsumerKey == null || ConsumerKey.IndexOf(' ') > 0) { ConsumerKey = ""; } if (ConsumerSecret == null || ConsumerSecret.IndexOf(' ') > 0) { ConsumerSecret = ""; } } catch { } }
} //obtained from OKAPI with method services/users/by_username public virtual void LoadSettings() { try { string doc; using (StreamReader textStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("GlobalcachingApplication.Plugins.OKAPI.ConsumerKeys.xml"))) { doc = textStreamReader.ReadToEnd(); } XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(doc); XmlNode n = xdoc.SelectSingleNode(string.Format("/keys/{0}", GeocodePrefix)); if (n != null) { ConsumerKey = n.SelectSingleNode("ConsumerKey").InnerText; ConsumerSecret = n.SelectSingleNode("ConsumerSecret").InnerText; } if (ConsumerKey == null || ConsumerKey.IndexOf(' ') > 0) { ConsumerKey = ""; } if (ConsumerSecret == null || ConsumerSecret.IndexOf(' ') > 0) { ConsumerSecret = ""; } } catch { } }
public OAuthParameters( ConsumerKey key, TokenKey tokenKey, string signatureMethod, TimestampSequence timestamps, NonceSequence nonces, string signature, string version, string verifier = null, string session = null, string callback = null ) { _key = key; _tokenKey = tokenKey; _signatureMethod = signatureMethod; _signature = signature; _session = session; _verifier = verifier; _version = version ?? "1.0"; _nonce = nonces.Next(); _timestamp = timestamps.Next(); _callback = callback; }
// コンストラクタ public ConfigureApiKeyViewModel(DialogService dialogService, AddAccountService addAccountModel) { // DI _dialogService = dialogService; _addAccountService = addAccountModel; // バリデーションを有効化する ConsumerKey.SetValidateAttribute(() => ConsumerKey); ConsumerSecret.SetValidateAttribute(() => ConsumerSecret); // ConsumerKeyとConsumerKeyが正しく入力されているときのみ「次へ」を押せるようにする NextCommand = new[] { ConsumerKey.ObserveHasErrors, ConsumerSecret.ObserveHasErrors } .CombineLatestValuesAreAllFalse() .ToReactiveCommand() .AddTo(Disposables); // 「次へ」が押されたらPinコード設定画面を開く NextCommand .Subscribe(() => { _addAccountService.OpenAuthorizeUrl(ConsumerKey.Value, ConsumerSecret.Value); _dialogService.OpenConfigurePincodeView(); }) .AddTo(Disposables); }
internal void ValidateThrowException() { var missingParams = new List <string>(); if (string.IsNullOrEmpty(ConsumerKey.Trim())) { missingParams.Add(nameof(ConsumerKey)); } if (string.IsNullOrEmpty(ConsumerSecret.Trim())) { missingParams.Add(nameof(ConsumerSecret)); } if (string.IsNullOrEmpty(TokenValue.Trim())) { missingParams.Add(nameof(TokenValue)); } if (string.IsNullOrEmpty(TokenSecret.Trim())) { missingParams.Add(nameof(TokenSecret)); } if (missingParams.Any()) { throw new BricklinkMissingCredentialsException(missingParams); } }
protected override void Execute(CodeActivityContext context) { service = new TwitterService(ConsumerKey.Get(context), ConsumerSecret.Get(context), AccessToken.Get(context), AccessSecret.Get(context)); service.TraceEnabled = true; using (var stream = new FileStream(MediaPath.Get(context), FileMode.Open, FileAccess.Read, FileShare.Read)) { TwitterChunkedMedia uploadedMedia = InitialiseMediaUpload(service, stream); UploadMediaChunks(service, stream, uploadedMedia); FinializeMediaAndWaitForProcessing(service, uploadedMedia); // Now send a tweet with the media attached var twitterStatus = service.SendTweet(new SendTweetOptions() { Status = Message.Get(context), MediaIds = new string[] { uploadedMedia.MediaId.ToString() } }); //AssertResultWas(service, HttpStatusCode.OK); //Assert.IsNotNull(twitterStatus); // Capture Posted Tweet Id TweetId.Set(context, twitterStatus.Id); } }
protected override void Execute(CodeActivityContext context) { service = new TwitterService(ConsumerKey.Get(context), ConsumerSecret.Get(context), AccessToken.Get(context), AccessSecret.Get(context)) { TraceEnabled = true }; var tweetsSearch = service.Search(new SearchOptions { Q = SearchKey.Get(context), Resulttype = TwitterSearchResultType.Recent, Count = Count.Get(context) }); List <TwitterStatus> resultList = new List <TwitterStatus>(tweetsSearch.Statuses); dtTweet.Columns.Add("Tweet Id"); dtTweet.Columns.Add("User Name"); dtTweet.Columns.Add("User Screen Name"); dtTweet.Columns.Add("Text"); dtTweet.Columns.Add("Created Date"); dtTweet.Columns.Add("Retweet Count"); dtTweet.Columns.Add("Favorite Count"); dtTweet.Columns.Add("Profile Image URL"); foreach (var tweet in tweetsSearch.Statuses) { //tweet.Id; //Id of the tweet //tweet.User.ScreenName; //Screen Name of the user //tweet.User.Name; //Name of the User //tweet.Text; // Trimmed Text of the tweet //tweet.FullText; // Full Text of the tweet //tweet.RetweetCount; //No of retweet on twitter //tweet.User.FavouritesCount; //No of Fav mark on twitter //tweet.User.ProfileImageUrl; //Profile Image of Tweet //tweet.CreatedDate; //For Tweet posted time //"https://twitter.com/intent/retweet?tweet_id=" + tweet.Id; //For Retweet //"https://twitter.com/intent/tweet?in_reply_to=" + tweet.Id; //For Reply //"https://twitter.com/intent/favorite?tweet_id=" + tweet.Id; //For Favorite //Above are the things we can also get using TweetSharp. dtTweet.Rows.Add( FetchUserDetails.Get(context) ? tweet.Id : 0L, FetchUserDetails.Get(context) ? tweet.User.Name : "", FetchUserDetails.Get(context) ? tweet.User.ScreenName : "", FetchFullText.Get(context) ? tweet.FullText : tweet.Text, tweet.CreatedDate, tweet.RetweetCount, tweet.FavoriteCount, FetchUserDetails.Get(context) ? tweet.User.ProfileImageUrl : "" ); } OutputResult.Set(context, dtTweet); }
private string GenerateSignature(Uri url, string method, string consumerSecret, out string normalizedUrl, out string normalizedRequestParameters) { var generatedSignature = GenerateSignature(url, ConsumerKey.ToLower(), consumerSecret.ToLower(), Token, null, method, Timestamp, Nonce, out normalizedUrl, out normalizedRequestParameters); return(generatedSignature); }
public async Task <AccessToken> CreateAnonymousAccessToken(ConsumerKey consumerKey, string issuer) { var accessTokenId = IDUtility.GenerateId(); var accessToken = new AccessToken("", "", "", Role.ANONYMOUS.ToString(), consumerKey, accessTokenId, issuer); var accessTokenLog = new UserTokenLog(accessToken); AccessTokenLogService.Save(accessTokenLog); return(accessToken); }
private async Task <LoginResponse> CreateLoginResponse(string userId, string userName, Role role, string profileId, ConsumerKey consumerKey, string issuer) { var refreshToken = await UserTokenService.CreateRefreshToken(userId, userName, role, profileId, consumerKey, issuer); var accessToken = await UserTokenService.CreateAccessToken(refreshToken); return(new LoginResponse(accessToken, refreshToken)); }
protected override void Execute(CodeActivityContext context) { service = new TwitterService(ConsumerKey.Get(context), ConsumerSecret.Get(context), AccessToken.Get(context), AccessSecret.Get(context)); service.Retweet(new RetweetOptions { Id = TweetID.Get(context) }); }
private void ValidateProtectedResourceState() { if (ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } }
//private TraceSource traceSource = new TraceSource("Workflow"); protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) { // traceSource.TraceEvent(TraceEventType.Information, 0, "0"); /* String sfdcConsumerkey = "3MVG9CxwbdV68qJIIz27ukIaKmSfOCVO8I6JbMGHkEt4s5KwlreFqQqE.5UIpNcOds3xKVoib9cEZpUk3f5os"; * String sfdcConsumerSecret = "8782286442880574610"; * String sfdcUserName = "******"; * String sfdcPassword = "******"; * String sfdcSecurityToken = "dg912XkpjYZjhtj2kOMqjh4qU";*/ String sfdcConsumerkey = ConsumerKey.Get(context); String sfdcConsumerSecret = ConsumerSecret.Get(context); String sfdcUserName = UserName.Get(context); String sfdcPassword = Password.Get(context); String sfdcSecurityToken = SecurityToken.Get(context); String SfdcloginPassword = sfdcPassword + sfdcSecurityToken; Boolean TestServer = (ServerType == Type_of_Server.Test) ? true : false; var dictionaryForUrl = new Dictionary <String, String> { { "grant_type", "password" }, { "client_id", sfdcConsumerkey }, { "client_secret", sfdcConsumerSecret }, { "username", sfdcUserName }, { "password", SfdcloginPassword } }; var task = (new CmdRestAPI(dictionaryForUrl, TestServer)).ExecuteAsync(); var tcs = new TaskCompletionSource <CmdRestAPI>(state); task.ContinueWith(t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(t.Result); } if (callback != null) { callback(tcs.Task); } }); return(tcs.Task); }
public async Task <RefreshToken> CreateRefreshToken(string userId, string userName, Role role, string profileId, ConsumerKey consumerKey, string issuer) { var refreshTokenId = IDUtility.GenerateId(); var refreshToken = new RefreshToken(userId, profileId, userName, role.ToString(), consumerKey, refreshTokenId, issuer); var refreshTokenLog = new UserTokenLog(refreshToken); await ValidRefreshTokenService.Save(refreshToken); RefreshTokenLogService.Save(refreshTokenLog); return(refreshToken); }
private void ValidateTokenRequestState() { if (RequestTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify a request token URL"); } if (ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } }
protected override void Execute(CodeActivityContext context) { try { service = new TwitterService(ConsumerKey.Get(context), ConsumerSecret.Get(context), AccessToken.Get(context), AccessSecret.Get(context)); TwitterStatus status; if (ImagePath.Get(context) == null) { // Send Tweet without Image status = service.SendTweet(new SendTweetOptions { Status = Message.Get(context) }); } else { // Send Tweet with Image MediaFile mf = new MediaFile(); Stream stream = new FileStream(ImagePath.Get(context), FileMode.Open); mf.Content = stream; var media = service.UploadMedia(new UploadMediaOptions { Media = mf }); var id = media.Media_Id; List <string> ls = new List <string>(); ls.Add(id.ToString()); status = service.SendTweet(new SendTweetOptions { Status = Message.Get(context), MediaIds = ls, }); } // Capture Posted Tweet Id TweetId.Set(context, status.Id); } catch (Exception e) { TweetId.Set(context, e.Message); } }
public OAuthParameters( ConsumerKey key, TokenKey tokenKey, string signatureMethod, TimestampSequence timestamps, NonceSequence nonces, string signature, string version ) { _key = key; _tokenKey = tokenKey; _signatureMethod = signatureMethod; _signature = signature; _version = version ?? "1.0"; _nonce = nonces.Next(); _timestamp = timestamps.Next(); }
public OAuthParameters( ConsumerKey key, TokenKey tokenKey, string signatureMethod, TimestampSequence timestamps, NonceSequence nonces, string signature, string version ) { _key = key; _tokenKey = tokenKey; _signatureMethod = signatureMethod; _signature = signature; _version = version ?? "1.0"; _nonce = nonces.Next(); _timestamp = timestamps.Next(); }
private void ValidateClientAuthAccessRequestState() { if (AccessTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify an access token URL"); } if (ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } if (ClientUsername.IsNullOrBlank() || ClientPassword.IsNullOrBlank()) { throw new ArgumentException("You must specify user credentials"); } }
private void ValidateAccessRequestState() { if (AccessTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify an access token URL"); } if (ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } if (ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } if (Token.IsNullOrBlank()) { throw new ArgumentException("You must specify a token"); } }
public OAuthToken GetRequestToken() { if (ConsumerKey.IsEmpty() || ConsumerSecret.IsEmpty()) { throw new ETradeException(LocalizedStrings.Str3345); } var client = new RestClient(_baseUrl) { Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret.To <string>(), "oob") }; var response = ExecuteRequest(client, new RestRequest("oauth/request_token")); if (response.ResponseStatus != ResponseStatus.Completed || response.StatusCode != HttpStatusCode.OK) { throw new ETradeAuthorizationFailedException( LocalizedStrings.Str3346Params.Put(response.StatusCode + ": " + response.StatusDescription)); } var qs = HttpUtility.ParseQueryString(response.Content); return(new OAuthToken(ConsumerKey, qs["oauth_token"], qs["oauth_token_secret"])); }
public Consumer(ConsumerKey consumerKey, string secret) { _consumerKey = consumerKey; _secret = secret; }
private void ConnectClick(object sender, RoutedEventArgs e) { var secret = PwdBox.Password; if (!IsConnected) { if (ConsumerKey.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3689); return; } if (secret.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3690); return; } if (Trader == null) { // создаем подключение Trader = new ETradeTrader(); try { Trader.AccessToken = null; var token = OAuthToken.Deserialize(Properties.Settings.Default.AccessToken); if (token != null && token.ConsumerKey.ToLowerInvariant() == ConsumerKey.ToLowerInvariant()) { Trader.AccessToken = token; } } catch (Exception ex) { MessageBox.Show(this, LocalizedStrings.Str3691Params.Put(ex)); } Trader.LogLevel = LogLevels.Debug; _logManager.Sources.Add(Trader); // подписываемся на событие успешного соединения Trader.Connected += () => this.GuiAsync(() => { Properties.Settings.Default.AccessToken = Trader.AccessToken.Serialize(); OnConnectionChanged(true); Trader.StartExport(); }); // подписываемся на событие разрыва соединения Trader.ConnectionError += error => this.GuiAsync(() => { OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false)); // подписываемся на ошибку обработки данных (транзакций и маркет) Trader.ProcessDataError += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // подписываемся на ошибку подписки маркет-данных Trader.MarketDataSubscriptionFailed += (security, type, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // регистрирует портфели на обновление данных portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // подписываемся на событие о неудачной регистрации заявок Trader.OrdersRegisterFailed += OrdersFailed; // подписываемся на событие о неудачном снятии заявок Trader.OrdersCancelFailed += OrdersFailed; // подписываемся на событие о неудачной регистрации стоп-заявок Trader.StopOrdersRegisterFailed += OrdersFailed; // подписываемся на событие о неудачном снятии стоп-заявок Trader.StopOrdersCancelFailed += OrdersFailed; // устанавливаем поставщик маркет-данных _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; } Trader.Sandbox = IsSandbox; //Trader.SandboxSecurities = IsSandbox ? GetSandboxSecurities() : null; Trader.ConsumerKey = ConsumerKey; Trader.ConsumerSecret = secret; Trader.Connect(); } else { Trader.Disconnect(); } }
public bool IsValid() { return(!ConsumerKey.IsNullOrWhiteSpace() && !ConsumerSecret.IsNullOrWhiteSpace()); }
protected override void Execute(NativeActivityContext context) { RestSharp.RestClient client = new RestSharp.RestClient(); MCser.SoapClient soapClient = null; String ExistAuthToken = "" + ExistingAuth.Get(context); String ExistServiceURL = "" + ExistingServ.Get(context); if (ExistAuthToken.Trim().Length > 1) { RespAuthToken = ExistAuthToken.Trim(); RespServiceURL = ExistServiceURL.Trim(); } else { String sfdcConsumerkey = ""; String sfdcConsumerSecret = ""; String sfdcServiceURL = ""; String sfdcUserName = ""; String sfdcPassword = ""; Boolean EnvType = (EnvironmentType == Type_of_Environment.Design_and_Test) ? true : false; if (EnvType) { sfdcConsumerkey = ConsumerKey.Get(context); sfdcConsumerSecret = ConsumerSecret.Get(context); sfdcServiceURL = ServiceURL.Get(context); sfdcUserName = UserName.Get(context); sfdcPassword = Password.Get(context); } else { sfdcConsumerkey = ConsumerKeyProd.Get(context); sfdcConsumerSecret = SecureStringToString(ConsumerSecretProd.Get(context)); sfdcServiceURL = "" + SecureStringToString(ServiceURLProd.Get(context)); sfdcUserName = UserNameProd.Get(context); sfdcPassword = SecureStringToString(PasswordProd.Get(context)); } try { client.BaseUrl = new Uri("https://auth.exacttargetapis.com/v1/requestToken"); var request2 = new RestRequest(Method.POST); request2.RequestFormat = DataFormat.Json; request2.AddParameter("clientId", sfdcConsumerkey); request2.AddParameter("clientSecret", sfdcConsumerSecret); JObject jsonObj = JObject.Parse(client.Post(request2).Content); RespAuthToken = (String)jsonObj["accessToken"]; String ErrorType = ""; ErrorType = (String)jsonObj["error"]; String ErrorMsg = ""; ErrorMsg = (String)jsonObj["error_description"]; if ((RespAuthToken != null && RespAuthToken != "") && ErrorMsg == null) { BasicHttpsBinding binding = new BasicHttpsBinding(); binding.Name = "MyServicesSoap"; binding.CloseTimeout = TimeSpan.FromMinutes(1); binding.OpenTimeout = TimeSpan.FromMinutes(1); binding.ReceiveTimeout = TimeSpan.FromMinutes(60); binding.SendTimeout = TimeSpan.FromMinutes(1); binding.AllowCookies = false; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MaxBufferSize = 20000000; binding.MaxBufferPoolSize = 20000000; binding.MaxReceivedMessageSize = 20000000; binding.MessageEncoding = WSMessageEncoding.Text; binding.TextEncoding = System.Text.Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; binding.ReaderQuotas.MaxDepth = 32; binding.ReaderQuotas.MaxStringContentLength = 8192; binding.ReaderQuotas.MaxArrayLength = 16384; binding.ReaderQuotas.MaxBytesPerRead = 4096; binding.ReaderQuotas.MaxNameTableCharCount = 16384; binding.Security.Mode = BasicHttpsSecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None; binding.Security.Transport.Realm = ""; binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default; String endpointStr = "https://webservice.s10.exacttarget.com/Service.asmx"; EndpointAddress endpoint = new EndpointAddress(endpointStr); soapClient = new MCser.SoapClient(binding, endpoint); soapClient.ClientCredentials.UserName.UserName = sfdcUserName; soapClient.ClientCredentials.UserName.Password = sfdcPassword; soapClient.Endpoint.EndpointBehaviors.Add(new FuelOAuthHeaderBehavior(RespAuthToken)); RespServiceURL = sfdcServiceURL; } else if (RespAuthToken == null && (ErrorMsg != "" && ErrorMsg != null)) { RespAuthToken = "Error Type: " + ErrorType; RespServiceURL = "Error: " + ErrorMsg; } } catch (Exception ex) { RespAuthToken = "Error Type: " + ex.ToString(); RespServiceURL = "Error: " + ex.ToString(); } } var salesForceProperty = new SalesForceProperty(soapClient, true, RespAuthToken, RespServiceURL); if (Body != null) { context.ScheduleAction <SalesForceProperty>(Body, salesForceProperty, OnCompleted, OnFaulted); } }
private void ConnectClick(object sender, RoutedEventArgs e) { var secret = PwdBox.Password; if (!IsConnected) { if (ConsumerKey.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3689); return; } if (secret.IsEmpty()) { MessageBox.Show(this, LocalizedStrings.Str3690); return; } if (Trader == null) { // create connector Trader = new ETradeTrader(); try { Trader.AccessToken = null; var token = OAuthToken.Deserialize(Properties.Settings.Default.AccessToken); if (token != null && token.ConsumerKey.ToLowerInvariant() == ConsumerKey.ToLowerInvariant()) { Trader.AccessToken = token; } } catch (Exception ex) { MessageBox.Show(this, LocalizedStrings.Str3691Params.Put(ex)); } Trader.LogLevel = LogLevels.Debug; _logManager.Sources.Add(Trader); // subscribe on connection successfully event Trader.Connected += () => this.GuiAsync(() => { Properties.Settings.Default.AccessToken = Trader.AccessToken.Serialize(); OnConnectionChanged(true); }); // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false)); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, type, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; Trader.MassOrderCancelFailed += (transId, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716)); // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; } Trader.Sandbox = IsSandbox; //Trader.SandboxSecurities = IsSandbox ? GetSandboxSecurities() : null; Trader.ConsumerKey = ConsumerKey; Trader.ConsumerSecret = secret; Trader.Connect(); } else { Trader.Disconnect(); } }
/// <summary> /// Получить строковое представление контейнера. /// </summary> /// <returns>Строковое представление.</returns> public override string ToString() { return(ConsumerKey.IsEmpty() ? string.Empty : "ConsumerKey = {0}".Put(ConsumerKey)); }
public bool IsConfigured() { return(!ConsumerKey.IsEmpty() && !ConsumerSecret.IsEmpty()); }