public OAuthTokenResponse(WebResponse httpWebResponse)
        {
            using (var stream = httpWebResponse.GetResponseStream())
            {
                var reader = new StreamReader(stream);
                ResponseBody = reader.ReadToEnd();
                reader.Close();
            }

            if (string.IsNullOrEmpty(ResponseBody))
            {
                return;
            }

            Items = new NameValueCollection();

            foreach (string item in ResponseBody.Split('&'))
            {
                if (item.IndexOf('=') > -1)
                {
                    string[] temp = item.Split('=');
                    Items.Add(temp[0], temp[1]);
                }
                else
                {
                    Items.Add(item, string.Empty);
                }
            }

            Token = new OAuthToken() { Token = Items["oauth_token"], TokenSecret = Items["oauth_token_secret"] };
        }
        public void CanRedeemToken()
        {
            const string accessToken = "asdnakjsdnas";
            const int expiresIn = 3600;
            const string newRefreshToken = "jerwpmsdkjngvdsk";
            const string scope = "read_events create_event delete_event";

            http.Stub(
                HttpPost
                    .Url("https://app.cronofy.com/oauth/token")
                    .RequestHeader("Content-Type", "application/json; charset=utf-8")
                    .RequestBodyFormat(
                        "{{\"client_id\":\"{0}\",\"client_secret\":\"{1}\",\"grant_type\":\"refresh_token\",\"refresh_token\":\"{2}\"}}",
                        clientId, clientSecret, refreshToken)
                    .ResponseCode(200)
                    .ResponseBodyFormat(
                        "{{\"token_type\":\"bearer\",\"access_token\":\"{0}\",\"expires_in\":{1},\"refresh_token\":\"{2}\",\"scope\":\"{3}\"}}",
                        accessToken, expiresIn, newRefreshToken, scope)
            );

            var actualToken = client.GetTokenFromRefreshToken(refreshToken);
            var expectedToken = new OAuthToken(accessToken, newRefreshToken, expiresIn, scope.Split(new[] { ' ' }));

            Assert.AreEqual(expectedToken, actualToken);
        }
    public string UploadFile()
    {
        DropboxServiceProvider dropboxServiceProvider =
            new DropboxServiceProvider(DropboxAppKey, DropboxAppSecret, AccessLevel.AppFolder);

        // Authenticate the application (if not authenticated) and load the OAuth token
        //if (!File.Exists(OAuthTokenFileName))
        //{
        //    AuthorizeAppOAuth(dropboxServiceProvider);
        //}
        OAuthToken oauthAccessToken = new OAuthToken("fvjpvp0isfjsgyd7", "2u9zc9h1r0say01");

        // Login in Dropbox
        IDropbox dropbox = dropboxServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);

        // Display user name (from his profile)
        DropboxProfile profile = dropbox.GetUserProfileAsync().Result;
        Console.WriteLine("Hi " + profile.DisplayName + "!");

        // Create new folder
        string newFolderName = "RecipeImages";

        Directory.CreateDirectory("../../DropboxLisa");
        using (FileStream output = File.OpenWrite("../../DropboxLisa/" + DateTime.Now.Ticks + this.fileName ))
        {
            CopyStream(imageStream, output);
        }

        // Upload a file
        string[] files = Directory.GetFiles("../../DropboxLisa");
        List<Entry> uploadedFiles = new List<Entry>();
        foreach (var file in files)
        {
            Entry uploadFileEntry = dropbox.UploadFileAsync(
                new FileResource(Path.GetFullPath(file)),
                "/" + newFolderName + "/" + Path.GetFileName(file)).Result;
            uploadedFiles.Add(uploadFileEntry);
            Console.WriteLine("Uploaded a file: {0}", uploadFileEntry.Path);
        }

        //Delete the file
        DeleteDirectory("\\DropboxLisa");

        string fileUrl = string.Empty;

        foreach (var file in uploadedFiles)
        {
            DropboxLink fileShareUrl = dropbox.GetMediaLinkAsync(file.Path).Result; // files
            fileUrl = fileShareUrl.Url;
        }

        return fileUrl;
    }
Beispiel #4
0
        public KuaipanClient(OAuthConsumer consumer, OAuthToken token, bool isRoot)
            : base(consumer)
        {
            _Root = isRoot ? "kuaipan" : "app_folder";

            Token = token;
            _Server = new KuaipanServer();

            Name = "金山快盘";
            Root = "kuaipan:/";
            //Icon = Image.FromFile(@"D:\Temp\i1\Icon.png");
        }
Beispiel #5
0
			public async Task GetAccessTokenAsync(IRestClient client, string authCode)
			{
				var request = new RestRequest("oauth/token", HttpMethod.Post)
					.AddJsonBody(new 
						{
							code = authCode,
							client_id = ClientId,
							client_secret = ClientSecret,
							redirect_uri = RedirectUri.AbsoluteUri,
							grant_type = "authorization_code"
						});

				var response = await client.Execute<OAuthToken>(request);
				token = response.Data;
			}
Beispiel #6
0
    /// <summary>
    /// Use the app account settings from developer.att.com for the following values.
    /// Make sure ADS is enabled for the App Key and the App Secret.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string appKey = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string appSecret = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        //Set the scope to ADS
        string scope = "ADS";

        // Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, appKey, appSecret, scope);

        // Get the OAuth access token using the Client Credentials.
        if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials))
        {
            // Get access token
            OAuthToken at = new OAuthToken();
            var accessToken = at.getAccessToken(oauth.accessTokenJson);

            // Create the service for making the method request.
            var ads = new Ads(fqdn, accessToken);

            // Set params:
            string category = "Auto";
            string udid = "123456789012345678901234567890";
            string userAgent ="Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19";

            try
            {
                // Make an Make a method call to the Advertising API.
                // param 1 category
                // param 2 udid
                // param 3 user agent
                AdsObj.RootObject ads_obj = ads.GetAds(category, udid, userAgent);
            }
            catch (Exception ex)
            {
                string error = ex.StackTrace;
            }
        }
    }
Beispiel #7
0
 private void SaveToken(OAuthToken token)
 {
     TextBox1.Text += "token:" + token.Token + '\n';
     TextBox1.Text += "token:" + token.Secret + '\n';
     DBAccess dba = new DBAccess();
     dba.AddTable(DBConst.C3010A00);
     dba.AddParam(DBConst.C3010A01, 0);
     dba.AddParam(DBConst.C3010A02, HashUtil.UtcTimeInHex(false));
     dba.AddParam(DBConst.C3010A03, UserModel.Current(Session).Code);
     dba.AddParam(DBConst.C3010A04, KuaipanServer.TYPE);
     dba.AddParam(DBConst.C3010A05, KuaipanServer.CONSUMER_KEY);
     dba.AddParam(DBConst.C3010A06, KuaipanServer.CONSUMER_SECRET);
     dba.AddParam(DBConst.C3010A07, CharUtil.Text2DB(token.Token));
     dba.AddParam(DBConst.C3010A08, CharUtil.Text2DB(token.Secret));
     dba.AddParam(DBConst.C3010A09, 1);
     dba.AddParam(DBConst.C3010A0A, DBConst.SQL_NOW, false);
     dba.AddParam(DBConst.C3010A0B, DBConst.SQL_NOW, false);
     dba.ExecuteInsert();
 }
Beispiel #8
0
        public ActionResult Home(string id)
        {
            access = UserManager.GetToken();
            if ((HttpContext.Request["oauth_token"] != null) && (access == null))
                oAuthExecute();

            if ((string.IsNullOrEmpty(id)) && (access == null))
                id="iamhonger";

            IEnumerable<TwitterStatus> statuses;

            if (!(string.IsNullOrEmpty(id)))
                statuses =StatusesService.RetrieveStatusesByUser(id);
            else
                //Assume login in already
                statuses = StatusesService.RetrieveStatusesByUser(access);

            if (statuses!=null)
                return View(statuses);
            else
                return Redirect("http://twitter.com/" + id);
        }
Beispiel #9
0
        public OAuthDialog()
        {
            InitializeComponent();

            pinTextBox.Visibility = Visibility.Hidden;
            pinLbl.Visibility = Visibility.Hidden;
            pinInstruction.Visibility = Visibility.Hidden;

            _consumerKey = Settings.Default.ConsumerKey;
            _consumerSecret = Settings.Default.ConsumerSecret;
            //get a request token.  this is only used during
            //this process.
            var getRequestTokenRequest = FluentTwitter.CreateRequest()
               .Authentication.GetRequestToken(_consumerKey, _consumerSecret);

            var response = getRequestTokenRequest.Request();
            _requestToken = response.AsToken();

            //TODO: handle the case where the token is NULL because
            //twitter is down or broken in a manner suitable to your app

            //wait for the user to click the "Authorize button"
        }
        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, msg) =>
                                                           this.GuiAsync(() => MessageBox.Show(this, msg.Error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, 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();
            }
        }
Beispiel #11
0
 public void Authorize(OAuthToken accessToken)
 {
     _client.Authorize(accessToken);
 }
 public ImageMetadataEntity(OAuthToken oauthToken) : base(oauthToken)
 {
 }
 partial void DeleteOAuthToken(OAuthToken instance);
    public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
    {
        RequestScopedTokenMessage scopedRequest = (RequestScopedTokenMessage)request;
        var consumer = Global.DataContext.OAuthConsumers.Single(consumerRow => consumerRow.ConsumerKey == request.ConsumerKey);
        string scope = scopedRequest.Scope;
        OAuthToken newToken = new OAuthToken {
            OAuthConsumer = consumer,
            Token = response.Token,
            TokenSecret = response.TokenSecret,
            IssueDate = DateTime.UtcNow,
            Scope = scope,
        };

        Global.DataContext.OAuthTokens.InsertOnSubmit(newToken);
    }
Beispiel #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string clientId = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string secretKey = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        //Set the scope to MMS
        string scope = "MMS";

        //Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, clientId, secretKey, scope);

        //Get the OAuth access token using client Credential method.
        if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials))
        {
            // Get access token
            OAuthToken at = new OAuthToken();
            string accessToken = at.getAccessToken(oauth.accessTokenJson);

            // Create the service for making the method request.
            var mms = new MMS(fqdn, accessToken);

            // Set params:
            string mmsAddress = Server.UrlEncode("tel:10000000000") + "&"; //e.g.tel:1234567890
            string mmsMessage = Server.UrlEncode("msg txt context");
            string mmsFile = Server.MapPath("~/")+"attachments/att.jpg"; //Attachement path
            string mmsContentType = "image/jpeg";
            string messageId = "";

            try
            {
                // Make an Make a method call to the MMS API.
                // Method takes:
                // param 1: string mmsAddress (phone number(s))
                // param 2: message text content
                // param 3: file path
                // param 4: multipart content type
                OutboundMessageResponseObj.RootObject SendMMSResponseObj = mms.sendMMS(mmsAddress, mmsMessage, mmsFile, mmsContentType);
                messageId = SendMMSResponseObj.outboundMessageResponse.messageId;
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }

            try
            {
                // Make an Make a method call to the MMS API.
                // Method takes:
                // param 1: string message id
                DeliveryInfoObj.RootObject getStatusResponseObj = mms.getMMSDeliveryStatus(messageId);
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }

        }
    }
Beispiel #16
0
 public static Task <IList <Player> > GetPlayers(this IBattleNetClient battleNetClient, ulong accountId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <IList <Player> >($"/sc2/player/{accountId}", authToken));
 }
Beispiel #17
0
 public static Task <Season> GetSeasonAsync(this IBattleNetClient battleNetClient, int regionId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <Season>($"/sc2/ladder/season/{regionId}", authToken));
 }
Beispiel #18
0
 public static Task <GrandmasterLeaderboardRoot> GetGrandmasterLeaderBoardAsync(this IBattleNetClient battleNetClient, int regionId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <GrandmasterLeaderboardRoot>($"/sc2/ladder/grandmaster/{regionId}", authToken));
 }
Beispiel #19
0
 public DropboxApi(string consumerKey, string consumerSecret, OAuthToken accessToken)
 {
     _consumerKey    = consumerKey;
     _consumerSecret = consumerSecret;
     _accessToken    = accessToken;
 }
Beispiel #20
0
 public TokenClient(OAuthToken token, String clientId, String clientSecret)
 {
     this.mOAuthToken   = token;
     this.mClientId     = clientId;
     this.mClientSecret = clientSecret;
 }
Beispiel #21
0
 public static void SetToken(OAuthToken token, bool serviceAccount)
 {
     SetToken(token.AccessToken, token.RefreshToken, serviceAccount);
 }
Beispiel #22
0
        public async Task <IList <IdentityRef> > GetTeamMembers(string account, string projectId, string teamId, OAuthToken token)
        {
            token.ThrowIfNull(nameof(token));

            using (var client = await this.ConnectAsync <TeamHttpClient>(token, account))
            {
                return(await client.GetTeamMembersAsync(projectId, teamId));
            }
        }
Beispiel #23
0
 public ApplyAlbumTemplateEntity(OAuthToken oauthToken) : base(oauthToken)
 {
 }
Beispiel #24
0
 public static Task <Player> GetPlayer(this IBattleNetClient battleNetClient, int regionId, int realmId, long profileId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <Player>($"/sc2/metadata/profile/{regionId}/{realmId}/{profileId}", authToken));
 }
Beispiel #25
0
        private OAuthToken LoadOAuthToken()
        {
            OAuthToken oauthAccessToken = new OAuthToken("hsmlwuul3nbd72go", "z183wdbxk9dj49i");

            return(oauthAccessToken);
        }
Beispiel #26
0
 public static Task <StaticRoot> GetStatic(this IBattleNetClient battleNetClient, int regionId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <StaticRoot>($"/sc2/static/profile/{regionId}", authToken));
 }
 partial void InsertOAuthToken(OAuthToken instance);
Beispiel #28
0
 public static Task <LadderRoot> GetLadder(this IBattleNetClient battleNetClient, int regionId, int realmId, long profileId, long ladderId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <LadderRoot>($"/sc2/profile/{regionId}/{realmId}/{profileId}/ladder/{ladderId}", authToken));
 }
Beispiel #29
0
 public static void GrantToken(OAuthToken access)
 {
     HttpContext.Current.Session["accessToken"] = access;
 }
Beispiel #30
0
 public static Task <AchievementsRoot> GetLegacyAchievementsAsync(this IBattleNetClient battleNetClient, int regionId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <AchievementsRoot>($"/sc2/legacy/data/achievements/{regionId}", authToken));
 }
Beispiel #31
0
        private void oAuthExecute()
        {
            _consumerKey = ConfigurationManager.AppSettings["consumerKey"];
            _consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];

            TwitterClientInfo myClientInfo = new TwitterClientInfo();
            myClientInfo.ClientName = "TwistHelloKitty";
            myClientInfo.ClientUrl = "http://www.hellokittyland.com";
            myClientInfo.ClientVersion = "0.0.0.1";
            myClientInfo.ConsumerKey = _consumerKey;
            myClientInfo.ConsumerSecret = _consumerSecret;

            FluentTwitter.SetClientInfo(myClientInfo);

            requestToken = HttpContext.Request["oauth_token"];

            if (requestToken == null && ( Session["accessToken"] == null))
            {
                var request = GetRequestToken();
                // retrieve a URL used to direct the user to authorize, and
                // return to this page with a token

                var authorizeUrl = FluentTwitter.CreateRequest().Authentication.GetAuthorizationUrl(request.Token, "http://localhost:1113");
                Response.Redirect(authorizeUrl);
            }
            else
            {
                // exchange returned request token for access token
                if (access==null)
                access = GetAccessToken(requestToken);
                UserManager.GrantToken(access);
                // make an oauth-authenticated call with the access token,
                // and remember you need to persist this token for this user&apos;s auth
                //var query = FluentTwitter.CreateRequest().AuthenticateWith(_consumerKey, _consumerSecret, access.Token, access.TokenSecret)
                //    .Account().VerifyCredentials().AsXml();
                //// use as normal
                //var response = query.Request();
                //GetResponse(response);
            }
        }
Beispiel #32
0
 public static Task <LegacyRewardsRoot> GetLegacyRewards(this IBattleNetClient battleNetClient, int regionId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <LegacyRewardsRoot>($"/sc2/legacy/data/rewards/{regionId}", authToken));
 }
Beispiel #33
0
        public ActionResult Update(FormCollection form)
        {
            string text;

            double? lat=null;
            double? lng=null;

            access = (OAuthToken)UserManager.GetToken();

            text= form[0];

            //Get ReplyToID
            long replyTo;

            if (form[1] != "")
            {
                lat = Math.Round(Convert.ToDouble(form[1]), 6);
                lng = Math.Round(Convert.ToDouble(form[2]), 6);
            }

            Int64.TryParse(form[3], out replyTo);

            var status = StatusesService.AddStatuses(lat, lng, text, replyTo);

            IList<TwitterStatus> statuses = new List<TwitterStatus>();
            statuses.Add(status);

            StatusesService.FormatTweetForNearBy(statuses);

            return PartialView("TweetDetail", statuses);
        }
        /// <summary>
        /// Converts the response into a <see cref="Cronofy.OAuthToken"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="Cronofy.OAuthToken"/> based upon the response.
        /// </returns>
        public OAuthToken ToToken()
        {
            var token = new OAuthToken(
                this.AccessToken,
                this.RefreshToken,
                this.ExpiresIn,
                this.GetScopeArray());

            token.AccountId = this.AccountId;

            if (this.LinkingProfile != null)
            {
                token.LinkingProfile = this.LinkingProfile.ToLinkingProfile();
            }

            return token;
        }
        public void CanRedeemTokenWithLinkingProfileInfo()
        {
            const string accessToken = "asdnakjsdnas";
            const int expiresIn = 3600;
            const string refreshToken = "jerwpmsdkjngvdsk";
            const string scope = "read_events create_event delete_event";
            const string accountId = "acc_567236000909002";
            const string providerName = "google";
            const string profileId = "pro_n23kjnwrw2";
            const string profileName = "*****@*****.**";

            http.Stub(
                HttpPost
                    .Url("https://app.cronofy.com/oauth/token")
                    .RequestHeader("Content-Type", "application/json; charset=utf-8")
                    .RequestBodyFormat(
                        "{{\"client_id\":\"{0}\",\"client_secret\":\"{1}\",\"grant_type\":\"authorization_code\",\"code\":\"{2}\",\"redirect_uri\":\"{3}\"}}",
                        clientId, clientSecret, oauthCode, redirectUri)
                    .ResponseCode(200)
                    .ResponseBodyFormat(
                        "{{" +
                        "\"token_type\":\"bearer\"," +
                        "\"access_token\":\"{0}\"," +
                        "\"expires_in\":{1}," +
                        "\"refresh_token\":\"{2}\"," +
                        "\"scope\":\"{3}\"," +
                        "\"account_id\":\"{4}\"," +
                        "\"linking_profile\":" +
                            "{{" +
                            "\"provider_name\":\"{5}\"," +
                            "\"profile_id\":\"{6}\"," +
                            "\"profile_name\":\"{7}\"" +
                            "}}" +
                        "}}",
                        accessToken, expiresIn, refreshToken, scope,
                        accountId, providerName, profileId, profileName)
            );

            var actualToken = client.GetTokenFromCode(oauthCode, redirectUri);
            var expectedToken = new OAuthToken(accessToken, refreshToken, expiresIn, scope.Split(new[] { ' ' }))
            {
                AccountId = accountId,
                LinkingProfile = new LinkingProfile()
                {
                    ProviderName = providerName,
                    Id = profileId,
                    Name = profileName,
                },
            };

            Assert.AreEqual(expectedToken, actualToken);
        }
    public void RequestSpeech(AudioClip audio, GameObject receiver, string callback)
    {
        float[] clipData = new float[audio.samples * audio.channels];
        audio.GetData(clipData, 0);
        WaveGen.WaveFormatChunk format = new WaveGen().MakeFormat(audio);
        
        try
        {
            string filename = GetTempFileName() + ".wav";
            FileStream stream = File.OpenWrite(filename);
            new WaveGen().Write(clipData, format, stream);
            stream.Close();

            Debug.Log("Request Start time: " + DateTime.Now.ToLongTimeString());

            if (requestFactory == null)
            {
                requestFactory = BuildRequestFactory(RequestFactory.ScopeTypes.Speech);
            }

            if (clientToken ==  null)
            {
                clientToken = GetAccessToken();
            }

            if (null != clientToken)
            {
                requestFactory.ClientCredential = clientToken;
            }

            ATT_MSSDK.Speechv3.SpeechResponse response = SpeechToTextService(filename, "Generic", "audio/wav");
            string speechOutput = response.Recognition.NBest[0].ResultText;
            if (clientToken == null)
            {
                clientToken = requestFactory.ClientCredential;
                SaveAccessToken();
            }

            Debug.Log("Response received time: " + DateTime.Now.ToLongTimeString());
            showProcess = false;
            Debug.Log("response: " + speechOutput);
            File.Delete(filename);
        }
        catch (System.Exception e)
        {
            Debug.LogError(e);
        }
    }
Beispiel #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string clientId = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string secretKey = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        //Set the scope to AAB
        string scope = "SMS";

        //Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, clientId, secretKey, scope);

        //Get the OAuth access token using the Client Credentials.
        if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials))
        {
            // Get access token
            OAuthToken at = new OAuthToken();
            string accessToken = at.getAccessToken(oauth.accessTokenJson);

            // Create the service for making the method request.
            var sms = new SMS(fqdn, accessToken);

            //*************************************************************************
            // Operation: Send SMS

            // Set params:
            string address = "tel:+10000000000";
            string message = "<Enter message>";

            string messageId = String.Empty;
            try
            {
                // Make an Make a method call to the SMS API.
                // Method takes:
                // param 1: address
                // param 1: message
                OutboundSMSResponseObj.RootObject sendSMSresponseObj = sms.sendSMS(address, message);
                messageId = sendSMSresponseObj.outboundSMSResponse.messageId;
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }

            //*************************************************************************
            // Operation: Get SMS

            string RegistrationID = "00000000";

            try
            {
                // Make an Make a method call to the SMS API.
                // Method takes:
                // param 1: RegistrationID
                InboundSmsMessageObj.RootObject getSMSresponseObj = sms.getSMS(RegistrationID);
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }

            //*************************************************************************
            // Operation: Get SMS Delivery Status

            try
            {
                // Make an Make a method call to the SMS API.
                // Method takes:
                // param 1: messageID
                DeliveryInfoObj.RootObject deliveryStatusResponse = sms.getSMSDeliveryStatus(messageId);
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }

        }
    }
Beispiel #38
0
 public WatermarkEntity(OAuthToken oauthToken) : base(oauthToken)
 {
 }
Beispiel #39
0
 public static Task <ProfileLegacyRoot> GetLegacyProfile(this IBattleNetClient battleNetClient, int regionId, int realmId, long profileId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <ProfileLegacyRoot>($"/sc2/legacy/profile/{regionId}/{realmId}/{profileId}", authToken));
 }
 public StatusImageEntity(OAuthToken oauthToken) : base(oauthToken)
 {
 }
Beispiel #41
0
        public async static Task<string> PostStatusAsync(string status, OAuthToken TwitterAccessToken, string ConsumerKey, string ConsumerSecret)
        {
            SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
            string oauth_nonce = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(DateTime.Now.Ticks.ToString()));
            string utc_time = Globalv.unix_timestamp().ToString();
            sd.Add("status", Uri.EscapeDataString(status));
            sd.Add("include_entities", "true");
            sd.Add("oauth_version", "1.0");
            sd.Add("oauth_consumer_key", ConsumerKey);
            sd.Add("oauth_nonce", oauth_nonce);
            sd.Add("oauth_signature_method", "HMAC-SHA1");
            sd.Add("oauth_timestamp", utc_time);
            sd.Add("oauth_token", TwitterAccessToken.Token);

            string baseString = String.Empty;
            baseString += "POST" + "&";
            baseString += Uri.EscapeDataString(
                "http://api.twitter.com/1/statuses/update.json")
                + "&";

            foreach (KeyValuePair<string, string> entry in sd)
            {
                baseString += Uri.EscapeDataString(entry.Key +
                    "=" + entry.Value + "&");
            }

            baseString =
                baseString.Substring(0, baseString.Length - 3);

            //shh... secrets here!
            string consumerSecret = ConsumerSecret;

            string oauth_token_secret = TwitterAccessToken.TokenSecret;

            string signingKey = Uri.EscapeDataString(consumerSecret) + "&" + Uri.EscapeDataString(oauth_token_secret);

            // Create a MacAlgorithmProvider object for the specified algorithm.
            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");

            // Demonstrate how to retrieve the name of the algorithm used.
            String strNameUsed = objMacProv.AlgorithmName;

            // Create a buffer that contains the the message to be signed.
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(baseString, encoding);

            // Create a key to be signed with the message.
            IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(signingKey, BinaryStringEncoding.Utf8);
            CryptographicKey hmacKey = objMacProv.CreateKey(keyMaterial);

            // Sign the key and message together.
            IBuffer buffHMAC = CryptographicEngine.Sign(hmacKey, buffMsg);

            // Verify that the HMAC length is correct for the selected algorithm
            if (buffHMAC.Length != objMacProv.MacLength)
            {
                throw new Exception("Error computing digest");
            }

            string signatureString = CryptographicBuffer.EncodeToBase64String(buffHMAC);

            //prepare for sending
            HttpClient cli = new HttpClient();
            cli.DefaultRequestHeaders.ExpectContinue = false;
            cli.DefaultRequestHeaders.ConnectionClose = true;

            //auth headers
            string authorizationHeaderParams = String.Empty;
            //authorizationHeaderParams += "OAuth ";
            authorizationHeaderParams += "oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",";
            authorizationHeaderParams += "oauth_signature_method=" + "\"" + Uri.EscapeDataString("HMAC-SHA1") + "\",";
            authorizationHeaderParams += "oauth_timestamp=" + "\"" + Uri.EscapeDataString(utc_time) + "\",";
            authorizationHeaderParams += "oauth_consumer_key=" + "\"" + Uri.EscapeDataString(ConsumerKey) + "\",";
            authorizationHeaderParams += "oauth_token=" + "\"" + Uri.EscapeDataString(TwitterAccessToken.Token) + "\",";
            authorizationHeaderParams += "oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",";
            authorizationHeaderParams += "oauth_version=" + "\"" + Uri.EscapeDataString("1.0") + "\"";
            cli.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth", authorizationHeaderParams);

            string postBody = "status=" + Uri.EscapeDataString(status) + "&include_entities=true";
            HttpContent tweet = new StringContent(postBody);
            tweet.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var MuTweetResponse = await cli.PostAsync(new Uri(@"http://api.twitter.com/1/statuses/update.json", UriKind.Absolute), tweet);
            return await MuTweetResponse.Content.ReadAsStringAsync();
        }
Beispiel #42
0
 public static Task <LadderLegacyRoot> GetLegacyLadder(this IBattleNetClient battleNetClient, int regionId, long ladderId, OAuthToken authToken)
 {
     return(battleNetClient.QueryBlizzardApiAsync <LadderLegacyRoot>($"/sc2/legacy/ladder/{regionId}/{ladderId}", authToken));
 }
    private OAuthToken GetAccessToken()
    {
        FileStream fileStream = null;
        StreamReader streamReader = null;       
        
        Debug.Log("Filepath: " + accessTokenFilePath);

        try
        {
            if (System.IO.File.Exists(accessTokenFilePath))
            {
                fileStream = new FileStream(accessTokenFilePath, FileMode.OpenOrCreate, FileAccess.Read);
                streamReader = new StreamReader(fileStream);
                string accessToken = streamReader.ReadLine();
                string refreshToken = streamReader.ReadLine();
                string expiresIn = streamReader.ReadLine();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    clientToken = new OAuthToken(accessToken, refreshToken, expiresIn);
                }
            }
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
        }
        finally
        {
            if (null != streamReader)
            {
                streamReader.Close();
            }

            if (null != fileStream)
            {
                fileStream.Close();
            }
        }

        return clientToken;

    }
Beispiel #44
0
 public ApiAnalyzer(OAuthToken oauthToken)
 {
     _token = oauthToken;
 }
Beispiel #45
0
    /// <summary>
    /// Use the app account settings from developer.att.com for the following values.
    /// Make sure MIM,IMMN is enabled for the app key/secret
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string clientId = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string secretKey = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        // Set the redirect URI for returning after consent flow.
        string authorizeRedirectUri = "";

        //Set the scope to MIM,IMMN
        string scope = "MIM,IMMN";

        //Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, clientId, secretKey, authorizeRedirectUri, scope);

        // If there's no access token yet go through the concent flow.
        if (Request["code"] == null)
        {
            // Authenticate the user. Note: This requires a Web browser.
            // Obtain the url string that is used for consent flow.
            if (!oauth.GetAuthCode())
            {
                //Get any error codes returned by the API Gateway.
                 string authCodeError = oauth.getAuthCodeError;
            }
        }
        else
        {
            // Get code in the query parameters after doing consent flow
            oauth.authCode = Request["code"].ToString();

            // Get the OAuth access token using the OAuth authentication code.
            if (oauth.GetAccessToken(OAuth.AccessTokenType.AuthorizationCode))
            {
                // Get access token
                OAuthToken at = new OAuthToken();
                var accessToken = at.getAccessToken(oauth.accessTokenJson);

                // Create the service for making the method request.
                var mymessages = new MyMessages(fqdn, accessToken);

                // Create an instance for JavaScriptSerializer.
                var serializer = new JavaScriptSerializer();

                //*************************************************************************
                // Operation: Create Message Index
                // The Create Message Index method allows the developer to create an index
                // cache for the user's AT&T Message inbox with prior consent.

                try
                {
                    // Make an Make a method call to the In-App Messaging API.
                    // Method takes no param
                    mymessages.createMessageIndex();
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Get Message List
                // Get meta-data for one or more messages from the customer's AT&T Message inbox.

                string limit = "<Enter limit>"; // e.g 500
                string offset = "<Enter pffset>"; // e.g. 50

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes no param
                    MessageObj.MessageList responseData = mymessages.getMessageList(limit, offset);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Get Message
                // Get one specific message from a user's AT&T Message inbox.

                var getMsg_messageId = "<Enter Message Id>";

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string message id
                    MessageObj.Message responseData = mymessages.getMessage(getMsg_messageId);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Get Message Content
                // Get media associated with a user message.

                string getMsgCtntMessageId = "<Enter Message Id>";
                string getMsgCtntPartId = "<Enter Part Id>"; // e.g. 0

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string message id
                    // param 2: string part id
                    string responseData = mymessages.getMessageContent(getMsgCtntMessageId, getMsgCtntPartId);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Get Message Index Info
                // Get the state, status, and message count of the index cache.

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes no param
                    string responseData = mymessages.getMessageIndexInfo();
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Delete Message
                // The Delete Message method gives the developer the ability to delete one
                // specific message from a user's AT&T Message inbox with prior consent.

                var delMsg_messageId = "<Enter Message Id>";

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string message id
                    mymessages.deleteMessage(delMsg_messageId);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Delete Messages
                // The Delete Message method gives the developer the ability to delete one
                // or more specific messages.

                var delMsg_messageId1 = "<Enter Message ID>";
                var delMsg_messageId2 = "<Enter Message ID>";
                var delMsg_messageId3 = "<Enter Message ID>";
                var queryString = "messageIds=" + delMsg_messageId1 + "%2" + delMsg_messageId2 + "%2" + delMsg_messageId3;

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string query string
                    mymessages.deleteMessage(queryString);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Get Message Delta
                // provides the capability to check for updates by passing in a client state.

                string state = "1403732028949";

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes no param
                    string responseData = mymessages.getMessageDelta(state);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Get Message Notification Connection Details
                // Retrieves details about the credentials, endpoint, and resource information
                // to required to set up a notification connection.

                string queues = "MMS";//MMS or TEXT

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes param 1: queues
                    string responseData = mymessages.getMessageNotificationConnectionDetails(queues);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Send Message
                // The Send Message method sends messages on behalf of an AT&T Wireless user.

                //Convert Message request object to JSON
                string smAddress = "<Enter address>";//e.g. tel:2060000000
                string smText = "<Enter messgae>"; // message content

                var addressesList = new List<string>();
                addressesList.Add(smAddress);

                var sendMsgObj = new MessageRequestObj.RootObject()
                {
                    messageRequest = new MessageRequestObj.MessageRequest()
                    {
                        addresses = addressesList,
                        text = smText
                    }
                };

                var sendMsgJson = serializer.Serialize(sendMsgObj);

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string json
                    mymessages.SendMessage(sendMsgJson);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Update Message
                // Update some flags related to one of the messages in a user's AT&T Message inbox.

                var isUnread = true;

                //Convert Message object to JSON
                var updateMsgObj = new MessageObj.RootObject()
                {
                    message = new MessageObj.Message()
                    {
                        isUnread = isUnread
                    }
                };
                var updateMsgJson = serializer.Serialize(updateMsgObj);

                string umMessageId = "<Enter Message Id>";

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string json
                    // param 2: string message id
                    mymessages.updateMessage(updateMsgJson, umMessageId);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                //*************************************************************************
                // Operation: Update Messages
                // Update some flags related to one of the messages in a user's AT&T Message inbox.

                //Convert Message object to JSON
                bool umIsUnread = true;
                var umMessages = new List<MessageObj.Message>();

                umMessages.Add(new MessageObj.Message()
                {
                    messageId = "<Enter Message Id>",
                    isUnread = umIsUnread
                });

                var updateMsgsObj = new MessageObj.RootObject();
                updateMsgsObj.messages = umMessages;

                var updateMsgsJson = serializer.Serialize(updateMsgsObj);

                try
                {
                    // Make a method call to the In-App Messaging API.
                    // Method takes:
                    // param 1: string json
                    mymessages.updateMessages(updateMsgsJson);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }
            }
        }
    }
Beispiel #46
0
 internal DropBoxRequestToken(OAuthToken realToken)
 {
     RealToken = realToken;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string clientId = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string secretKey = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        //Set the scope to Payment
        string scope = "Payment";

        // Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, clientId, secretKey, scope);

        // Get the OAuth access token using Client Credential method.
        if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials))
        {
            // Get access token
            OAuthToken at = new OAuthToken();
            string accessToken = at.getAccessToken(oauth.accessTokenJson);

            // Create the service for making the method request.
            var payment = new Payment(fqdn, accessToken);
            if (string.IsNullOrEmpty((string)Session["NewSubscription"]))
            {
                /// <summary>
                /// Create new subscription
                /// </summary>
                /// <param name="apiKey">apiKey</param>
                /// <param name="secretKey">secretKey</param>
                /// <param name="amount">amount</param>
                /// <param name="category">category</param>
                /// <param name="channel">channel</param>
                /// <param name="description">description</param>
                /// <param name="merchantTransactionId">merchantTransactionId</param>
                /// <param name="merchantProductId">merchantProductId</param>
                /// <param name="merchantRedirectURI">merchantRedirectURI</param>
                /// <param name="merchantSubscriptionId">merchantSubscriptionId</param>
                /// <param name="isPurchaseOnNoActiveSubscription">isPurchaseOnNoActiveSubscription</param>
                /// <param name="subscriptionRecurringNumber">subscriptionRecurringNumber</param>
                /// <param name="subscriptionRecurringPeriod">subscriptionRecurringPeriod</param>
                /// <param name="subscriptionRecurringPeriodAmount">subscriptionRecurringPeriodAmount</param>
                string redirectUrl = payment.createNewSubscriptionRedirectUrl(
                    clientId,
                    secretKey,
                    0.01,
                    3,
                    "MOBILE_WEB",
                    "description",
                    merchantTransactionId,
                    "merchantProductId000111",
                    "http://localhost/PaymentNewSubscription.aspx",
                    merchantSubscriptionId,
                    false,
                    99999,
                    "MONTHLY",
                    1);
                Session["NewSubscription"] = "created";
                //Response.Redirect(redirectUrl);
            }

            if ((Request["success"] != null) && Request.QueryString["success"].ToString() == "false")
            {
                errorCreateNew = new Dictionary<string, string>();

                foreach (String key in Request.QueryString.AllKeys)
                {
                    errorCreateNew.Add(key, Request.QueryString[key]);
                }
                throw new Exception(Request.QueryString["faultDescription"]);
            }

            if ((Request["SubscriptionAuthCode"] != null))
            {
                SubscriptionAuthCode = Request.QueryString["SubscriptionAuthCode"].ToString();
            }

            /// <summary>
            /// Call getSubscriptionStatus operation return getSubscriptionStatus object
            /// </summary>
            /// <param name="idType">idType</param>
            /// <param name="id">id</param>

            SubscriptionStatusResponseObj.RootObject getSubscriptionStatus =
                payment.getSubscriptionStatus("SubscriptionAuthCode", SubscriptionAuthCode);

            /// <summary>
            /// Call SubscriptionDetail operation return SubscriptionDetailResponse object
            /// </summary>
            /// <param name="MerchantSubscriptionId">MerchantSubscriptionId</param>
            /// <param name="ConsumerId">ConsumerId</param>

            SubscriptionDetailResponseObj.RootObject getSubscriptionDetail =
                payment.getSubscriptionDetail(getSubscriptionStatus.MerchantSubscriptionId,
                                                getSubscriptionStatus.ConsumerId);

        }
    }
Beispiel #48
0
 public UserCouponEntity(OAuthToken oauthToken)
     : base(oauthToken)
 {
 }
        protected async void OnNavigated(object sender, WebNavigatedEventArgs e)
        {
            progress.IsVisible = false;

            try
            {
                if (e.Url.StartsWith("http://35.202.198.25:81/RazorPayAPI/Charge.aspx"))
                {
                    await GetTransaction();

                    using (HttpClient client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(Convert.ToString(App.Current.Properties["BaseURL"]));
                        // We want the response to be JSON.
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        List <System.Collections.Generic.KeyValuePair <string, string> > postData = new List <KeyValuePair <string, string> >();
                        postData.Add(new KeyValuePair <string, string>("grant_type", "password"));
                        postData.Add(new KeyValuePair <string, string>("username", "Kiran"));
                        postData.Add(new KeyValuePair <string, string>("password", "1234"));
                        FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
                        // Post to the Server and parse the response.
                        var response = client.PostAsync("Token", content).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            var        jsonString   = response.Content.ReadAsStringAsync();
                            OAuthToken responseData = JsonConvert.DeserializeObject <OAuthToken>(jsonString.Result);
                            string     Access_Token = responseData.access_token;
                            App.Current.Properties["apitoken"] = Access_Token;
                        }
                    }

                    if (App.Current.Properties.ContainsKey("apitoken"))
                    {
                        if (obj_CustomerParkingSlot != null && obj_CustomerVehiclePass == null)
                        {
                            if (obj_CustomerParkingSlot.LocationName != null && obj_CustomerParkingSlot.LocationName != "")
                            {
                                if (obj_CustomerParkingSlot.LocationName.ToUpper() == "CHECKOUT")
                                {
                                    if (transactionID == "")
                                    {
                                        DisplayAlert("", "Payment Failed", "Ok");
                                        App.Current.Properties["CustomerParkingSlotID"] = Convert.ToString(obj_CustomerParkingSlot.CustomerParkingSlotID);
                                        App.Current.Properties["CustomerID"]            = Convert.ToString(obj_CustomerParkingSlot.CustomerID);
                                        return;
                                    }

                                    obj_CustomerParkingSlot.TransactionID = transactionID;
                                    var json    = JsonConvert.SerializeObject(obj_CustomerParkingSlot);
                                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                                    CustomerParkingSlotDetails resultObj = dal_Customer.UpdateCheckOut(Convert.ToString(App.Current.Properties["apitoken"]), obj_CustomerParkingSlot);

                                    if (resultObj.CustomerParkingSlotID != 0)
                                    {
                                        App.Current.Properties["CustomerParkingSlotID"] = "0";
                                        App.Current.Properties["CustomerID"]            = obj_CustomerParkingSlot.CustomerID;
                                        Application.Current.SavePropertiesAsync();
                                        DisplayAlert("", "Thank you for parking with us!", "Ok");
                                        int CustomerID = 0;
                                        if (App.Current.Properties.ContainsKey("CustomerID"))
                                        {
                                            CustomerID = Convert.ToInt32(App.Current.Properties["CustomerID"]);
                                        }

                                        await Navigation.PushAsync(new Home(null, CustomerID));
                                    }
                                    else
                                    {
                                        DisplayAlert("", "Insert Payment Failed", "Ok");
                                        App.Current.Properties["CustomerID"] = obj_CustomerParkingSlot.CustomerID;
                                        await Application.Current.SavePropertiesAsync();
                                    }
                                }
                                else
                                {
                                    if (transactionID == "")
                                    {
                                        DisplayAlert("", "Payment Failed", "Ok");
                                        App.Current.Properties["CustomerParkingSlotID"] = Convert.ToString(obj_CustomerParkingSlot.CustomerParkingSlotID);
                                        App.Current.Properties["CustomerID"]            = Convert.ToString(obj_CustomerParkingSlot.CustomerID);
                                        return;
                                    }

                                    obj_CustomerParkingSlot.TransactionID = transactionID;
                                    var json    = JsonConvert.SerializeObject(obj_CustomerParkingSlot);
                                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                                    CustomerParkingSlotDetails resultObj = dal_Customer.InsertCustomerParkingSlot(Convert.ToString(App.Current.Properties["apitoken"]), obj_CustomerParkingSlot);

                                    if (resultObj.CustomerParkingSlotID != 0)
                                    {
                                        App.Current.Properties["CustomerParkingSlotID"] = Convert.ToString(resultObj.CustomerParkingSlotID);
                                        App.Current.Properties["CustomerID"]            = Convert.ToString(obj_CustomerParkingSlot.CustomerID);
                                        await Application.Current.SavePropertiesAsync();

                                        await Navigation.PushAsync(new SessionHomeReceipt(resultObj));
                                    }
                                    else
                                    {
                                        DisplayAlert("", "Insert Payment Failed", "Ok");
                                        App.Current.Properties["CustomerID"] = obj_CustomerParkingSlot.CustomerID;
                                        await Application.Current.SavePropertiesAsync();
                                    }
                                }
                            }
                            else
                            {
                                if (transactionID == "")
                                {
                                    DisplayAlert("", "Payment Failed", "Ok");
                                    App.Current.Properties["CustomerParkingSlotID"] = Convert.ToString(obj_CustomerParkingSlot.CustomerParkingSlotID);
                                    App.Current.Properties["CustomerID"]            = Convert.ToString(obj_CustomerParkingSlot.CustomerID);
                                    return;
                                }

                                obj_CustomerParkingSlot.TransactionID = transactionID;
                                var json    = JsonConvert.SerializeObject(obj_CustomerParkingSlot);
                                var content = new StringContent(json, Encoding.UTF8, "application/json");
                                CustomerParkingSlotDetails resultObj = dal_Customer.InsertCustomerParkingSlot(Convert.ToString(App.Current.Properties["apitoken"]), obj_CustomerParkingSlot);

                                if (resultObj.CustomerParkingSlotID != 0)
                                {
                                    App.Current.Properties["CustomerParkingSlotID"] = Convert.ToString(resultObj.CustomerParkingSlotID);
                                    App.Current.Properties["CustomerID"]            = obj_CustomerParkingSlot.CustomerID;
                                    await Application.Current.SavePropertiesAsync();

                                    await Navigation.PushAsync(new SessionHomeReceipt(resultObj));
                                }
                                else
                                {
                                    DisplayAlert("", "Insert Payment Failed", "Ok");
                                    App.Current.Properties["CustomerID"] = obj_CustomerParkingSlot.CustomerID;
                                    await Application.Current.SavePropertiesAsync();
                                }
                            }
                        }
                        else if (obj_CustomerParkingSlot == null && obj_CustomerVehiclePass != null)
                        {
                            if (transactionID == "")
                            {
                                DisplayAlert("", "Payment Failed", "Ok");
                                App.Current.Properties["CustomerID"] = Convert.ToString(obj_CustomerVehiclePass.CustomerID);
                                return;
                            }

                            obj_CustomerVehiclePass.TransactionID = transactionID;
                            var json    = JsonConvert.SerializeObject(obj_CustomerVehiclePass);
                            var content = new StringContent(json, Encoding.UTF8, "application/json");
                            OCustomerVehiclePass resultObj;

                            if (obj_CustomerVehiclePass.IsMultiLot)
                            {
                                resultObj = dal_Pass.InsertMultiStationCustomerVehiclePass(Convert.ToString(App.Current.Properties["apitoken"]), obj_CustomerVehiclePass);
                            }
                            else
                            {
                                resultObj = dal_Pass.InsertCustomerVehiclePass(Convert.ToString(App.Current.Properties["apitoken"]), obj_CustomerVehiclePass);
                            }

                            if (resultObj.CustomerVehiclePassID != 0)
                            {
                                App.Current.Properties["CustomerID"] = obj_CustomerVehiclePass.CustomerID;
                                await Navigation.PushAsync(new PassReceipt(resultObj));
                            }
                            else
                            {
                                DisplayAlert("", "Insert Payment Failed", "Ok");
                                App.Current.Properties["CustomerID"] = obj_CustomerVehiclePass.CustomerID;
                                await Application.Current.SavePropertiesAsync();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayAlert("Failed - RazorPay", Convert.ToString(ex.Message), "Ok");
            }
        }
Beispiel #50
0
        public DataTable TokenGetCredencDt(string tokenValue)
        {
            DataTable dt = new DataTable();

            dt.TableName = "Joson";

            #region Columns

            //dt.Columns.Add("TokenVal", Type.GetType("System.String"));
            //dt.Columns["TokenVal"].Unique = true;

            //dt.Columns.Add("ID", Type.GetType("System.String"));
            //dt.Columns["ID"].DefaultValue = null;

            //dt.Columns.Add("AccountID", Type.GetType("System.String"));
            //dt.Columns["AccountID"].DefaultValue = null;

            //dt.Columns.Add("AccountName", Type.GetType("System.String"));
            //dt.Columns["AccountName"].DefaultValue = null;

            //dt.Columns.Add("AccountPassWords", Type.GetType("System.String"));
            //dt.Columns["AccountPassWords"].DefaultValue = null;

            //dt.Columns.Add("isLogin", Type.GetType("System.String"));
            //dt.Columns["isLogin"].DefaultValue = null;

            //DataColumn[] keys = new DataColumn[1];
            //keys[0] = dt.Columns["TokenVal"];
            //dt.PrimaryKey = keys;

            #endregion

            DataTable CacheTable = TokenCache.GetCacheTable();

            if (dt != null)
            {
                DataRow[] dr = CacheTable.Select("token = '" + tokenValue + "'");

                #region Temp

                //int i = 0;
                //foreach (DataRow dtRow in dr)
                //{
                //    OAuthToken OAuth = (OAuthToken)dr[i]["info"];

                //    DataRow DtNewRow = dt.NewRow();

                //    DtNewRow["TokenVal"] = dr[i]["token"];

                //    DtNewRow["ID"] = OAuth.ID;
                //    DtNewRow["AccountID"] = OAuth.AccountID;
                //    DtNewRow["AccountName"] = OAuth.AccountName;
                //    DtNewRow["AccountPassWords"] = OAuth.AccountPassWords;

                //    DtNewRow["isLogin"] = OAuth.isLogin;

                //    dt.Rows.Add(DtNewRow);

                //    i++;

                //}

                #endregion

                OAuthToken OAuth = dr[0]["info"].ToStrings().Deserialize <OAuthToken>();

                dt           = OAuth.ToDataTable();
                dt.TableName = "OAuth";
            }

            return(dt);

            //DataSet DtSet = new DataSet();
            //DtSet.Tables.Add(dt);
            //return DtSet;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string clientId = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string secretKey = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        //Set the scope to AAB
        string scope = "Payment";

        // Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, clientId, secretKey, scope);

        // Get the OAuth access token using the Client Credentials.
        if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials))
        {
            // Get access token
            OAuthToken at = new OAuthToken();
            string accessToken = at.getAccessToken(oauth.accessTokenJson);

            // Create the service for making the method request.
            var payment = new Payment(fqdn, accessToken);

            if (string.IsNullOrEmpty((string)Session["NewTransaction"]))
            {
                /// <summary>
                /// Create new transaction
                /// </summary>
                /// <param name="apiKey">apiKey</param>
                /// <param name="secretKey">secretKey</param>
                /// <param name="description">description</param>
                /// <param name="amount">amount</param>
                /// <param name="category">category</param>
                /// <param name="channel">channel</param>
                /// <param name="merchantRedirectURI">merchantRedirectURI</param>
                /// <param name="merchantProductId">merchantProductId</param>
                /// <param name="merchantTransactionId">merchantTransactionId</param>

                var redirectUrl = payment.createNewTransactionRedirectUrl(
                    clientId,
                    secretKey,
                    "Sample Product",
                    0.01,
                    2,
                    "MOBILE_WEB",
                    "http://localhost/PaymentNewTransaction.aspx",
                    "whateverprod",
                    merchantTransactionId);

                Session["NewTransaction"] = "created";
                Response.Redirect(redirectUrl);
            }

            if (Request.QueryString["success"] != null && Request.QueryString["success"].ToString() == "false")
            {
                errorCreateNew = new Dictionary<string, string>();

                foreach (String key in Request.QueryString.AllKeys)
                {
                    errorCreateNew.Add(key, Request.QueryString[key]);
                }
                throw new Exception(Request.QueryString["faultDescription"]);
            }

            if ((Request["TransactionAuthCode"] != null))
            {
                TransactionAuthCode = Request.QueryString["TransactionAuthCode"].ToString();
            }

            /// <summary>
            /// Call getTransactionStatus operation return getTransactionStatus object
            /// </summary>
            /// <param name="idType">idType</param>
            /// <param name="id">id</param>
            TransactionStatusResponseObj.RootObject getTransactionStatus
                = payment.getTransactionStatus("TransactionAuthCode", TransactionAuthCode);

            //Get Payment notification
            //Stream inputstream = Request.InputStream;
            //int streamLength = Convert.ToInt32(inputstream.Length);
            //byte[] stringArray = new byte[streamLength];
            //inputstream.Read(stringArray, 0, streamLength);

            //string xmlString = System.Text.Encoding.UTF8.GetString(stringArray);

            string xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ownershipEvent type=\"revoke\" timestamp=\"2014-05-02T06:12:33+00:00\" effective=\"2014-05-02T06:12:18+00:00\"><networkOperatorId>cingular</networkOperatorId><ownerIdentifier>N_NBI_PNW_1369816836000116729061</ownerIdentifier><purchaseDate>2014-05-02T06:12:05+00:00</purchaseDate><productIdentifier>Onetime_Cat1</productIdentifier><purchaseActivityIdentifier>Z89EZXmzjy2yu6s7wFY88cZM9lgztD6PRyo8</purchaseActivityIdentifier><instanceIdentifier>ada820f1-ce48-499b-8b46-eac60ef28a2a-CTASTransactionP1</instanceIdentifier><minIdentifier>4256586023</minIdentifier><sequenceNumber>178</sequenceNumber><reasonCode>1760</reasonCode><reasonMessage>CP Requested Refund</reasonMessage><vendorPurchaseIdentifier>M789819033</vendorPurchaseIdentifier></ownershipEvent>";

            XmlSerializer deserializer = new XmlSerializer(typeof(ownershipEvent));
            TextReader textReader = new StringReader(xmlString);
            ownershipEvent notificationObj;
            notificationObj = (ownershipEvent)deserializer.Deserialize(textReader);
            textReader.Close();

            //create refund transaction object
            RefundTransactionRequestObj.RootObject refund
                = new RefundTransactionRequestObj.RootObject()
            {
                TransactionOperationStatus = "Refunded",
                RefundReasonCode = 1,
                RefundReasonText = "Customer was not happy"
            };

            var serializer = new JavaScriptSerializer();
            var refundJSON = serializer.Serialize(refund);

            RefundTransactionResponseObj.RootObject refundResponse
                = payment.RefundTransaction(refundJSON, getTransactionStatus.TransactionId);

        }
    }
 public static bool IsSet(this OAuthToken token)
 {
     return(token != null && !string.IsNullOrWhiteSpace(token.Token) && !string.IsNullOrWhiteSpace(token.Secret));
 }
	private void attach_OAuthTokens(OAuthToken entity)
	{
		this.SendPropertyChanging();
		entity.User = this;
	}
Beispiel #54
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Enter the value from the 'App Key' field obtained at developer.att.com in your
        // app account.
        string clientId = "";

        // Enter the value from the 'App Secret' field obtained at developer.att.com
        // in your app account.
        string secretKey = "";

        // Set the fully-qualified domain name to: https://api.att.com
        string fqdn = "https://api.att.com";

        //Set the scope to MMS
        string scope = "MMS";

        //Create the service for requesting an OAuth access token.
        var oauth = new OAuth(fqdn, clientId, secretKey, scope);

        //Get the OAuth access token using client Credential method.
        if (oauth.GetAccessToken(OAuth.AccessTokenType.ClientCredentials))
        {
            // Get access token
            OAuthToken at          = new OAuthToken();
            string     accessToken = at.getAccessToken(oauth.accessTokenJson);

            // Create the service for making the method request.
            var mms = new MMS(fqdn, accessToken);

            // Set params:
            string mmsAddress     = Server.UrlEncode("tel:10000000000") + "&";    //e.g.tel:1234567890
            string mmsMessage     = Server.UrlEncode("msg txt context");
            string mmsFile        = Server.MapPath("~/") + "attachments/att.jpg"; //Attachement path
            string mmsContentType = "image/jpeg";
            string messageId      = "";

            try
            {
                // Make an Make a method call to the MMS API.
                // Method takes:
                // param 1: string mmsAddress (phone number(s))
                // param 2: message text content
                // param 3: file path
                // param 4: multipart content type
                OutboundMessageResponseObj.RootObject SendMMSResponseObj = mms.sendMMS(mmsAddress, mmsMessage, mmsFile, mmsContentType);
                messageId = SendMMSResponseObj.outboundMessageResponse.messageId;
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }

            try
            {
                // Make an Make a method call to the MMS API.
                // Method takes:
                // param 1: string message id
                DeliveryInfoObj.RootObject getStatusResponseObj = mms.getMMSDeliveryStatus(messageId);
            }
            catch (Exception respex)
            {
                string error = respex.StackTrace;
            }
        }
    }
 partial void UpdateOAuthToken(OAuthToken instance);
Beispiel #56
0
        /// <summary>
        /// 微信公众号引导页 使用微信AccessToken获取微信用户信息,但不包括用户UnionID信息
        /// </summary>
        /// <returns>成功时,返回带有用户信息的URL并重定向</returns>
        public ActionResult GetUserInfo1()
        {
            string code  = Request.QueryString["code"];
            string state = Request.QueryString["state"];

            try
            {
                if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
                {
                    OAuthToken oauthToken = JsonConvert.DeserializeObject <OAuthToken>(new WXHelper().Request(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code), "", "GET"));

                    string      accesstoken = string.Empty;
                    AccessToken token       = JsonConvert.DeserializeObject <AccessToken>(new WXHelper().Request(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, secret), "", "GET"));

                    if (token != null && !string.IsNullOrEmpty(token.access_token))
                    {
                        accesstoken = token.access_token;
                    }

                    if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid))
                    {
                        OAuthUserInfo userInfo = JsonConvert.DeserializeObject <OAuthUserInfo>(new WXHelper().Request(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, oauthToken.openid), "", "GET"));
                        if (userInfo != null)
                        {
                            ViewData["headImage"] = userInfo.headimgurl;
                            ViewData["openid"]    = userInfo.openid;
                            ViewData["nickName"]  = userInfo.nickname;
                            if (userInfo.sex == 0)
                            {
                                ViewData["sex"] = "未知";
                            }
                            else if (userInfo.sex == 1)
                            {
                                ViewData["sex"] = "男";
                            }
                            else
                            {
                                ViewData["sex"] = "女";
                            }
                            ViewData["province"] = userInfo.province;
                            ViewData["city"]     = userInfo.city;

                            object objUrl = CacheHelper.GetCache(state);
                            if (objUrl != null)
                            {
                                UriBuilder URL = new UriBuilder(objUrl.ToString());
                                if (!string.IsNullOrEmpty(URL.Query))
                                {
                                    URL.Query += string.Format("&unionid={0}&openid={1}&appid={2}",
                                                               userInfo.unionid, userInfo.openid, appId);
                                }
                                else
                                {
                                    URL.Query += string.Format("unionid={0}&openid={1}&appid={2}",
                                                               userInfo.unionid, userInfo.openid, appId);
                                }

                                return(Redirect(URL.ToString()));
                            }
                            else
                            {
                                ViewData["errmsg"] = "重定向URL获取失败!";
                            }
                        }
                        else
                        {
                            ViewData["errmsg"] = "用户信息获取失败!";
                        }
                    }
                    else
                    {
                        ViewData["errmsg"] = "Token获取失败!";
                    }
                }
                else
                {
                    ViewData["errmsg"] = "用户code获取失败!";
                }
            }
            catch (Exception ex)
            {
                ViewData["errmsg"] = ex.Message;
            }

            return(View());
        }
	private void detach_OAuthTokens(OAuthToken entity)
	{
		this.SendPropertyChanging();
		entity.OAuthConsumer = null;
	}
Beispiel #58
0
 public async static Task<Uri> GetAuthURLAsync(OAuthToken TwitterRequestToken)
 {
     string auth_url = @"https://api.twitter.com/oauth/authenticate?oauth_token=" + TwitterRequestToken.Token;
     Uri auth = new Uri(auth_url);
     return auth;
 }
	private static OAuthToken LoadOAuthToken()
	{
		string[] lines = File.ReadAllLines(OAuthTokenFileName);
		OAuthToken oauthAccessToken = new OAuthToken(lines[0], lines[1]);
		return oauthAccessToken;
	}
 public DeletedFolderEntity(OAuthToken oauthToken)
     : base(oauthToken)
 {
 }