当前位置: 首页>>代码示例>>C#>>正文


C# AccessToken类代码示例

本文整理汇总了C#中AccessToken的典型用法代码示例。如果您正苦于以下问题:C# AccessToken类的具体用法?C# AccessToken怎么用?C# AccessToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


AccessToken类属于命名空间,在下文中一共展示了AccessToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: btnAddResources_Click

    protected void btnAddResources_Click(object sender, EventArgs e)
    {
        try
        {
            if (ddlGroupName.SelectedIndex != 0)
            {
                //GetPermission(TireTraxLib.ResourceType.PagePermissions, ref canView, ref canAdd, ref canUpdate, ref canDelete,ddlGroupName.SelectedValue);
                //if (!canUpdate)
                //{
                //    lblInfo.Text = "Sorry, you dont have right to change the premission";
                //}
                //else
                //{
                int groupId = Convert.ToInt32(ddlGroupName.SelectedValue.ToString());
                AccessToken token = new AccessToken();
                string accessToken = AccessToken.ReturnEmptyToken();
                if (chkAdmin.Checked)
                    accessToken = token.AdminToken(64, accessToken);
                else
                    accessToken = ReadPermissions(accessToken, token);

                RoleManagement.UpdateSecurityToken(groupId, accessToken);

                //it is used to update the Security token for Roles
                DataTable dt = RoleManagement.getDistinctRolesByGroupId(groupId);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        int TempRoleId = Conversion.ParseInt(dt.Rows[i]["RoleId"]);
                        int TempSubRoleId = Conversion.ParseInt(dt.Rows[i]["SubRoleId"]);
                        regenerateSecurityTokens(TempRoleId, TempSubRoleId);
                    }
                }
                lblInfo.ForeColor = System.Drawing.Color.Green;
                lblInfo.Text = "Permission is Successfully Added";

                //Update Cookies
                // UserInfo user = UserInfo.GetCurrentUserInfo();
                Response.Cookies["securityToken"].Expires = DateTime.Now.AddMinutes(-1);
                string securityToken = string.Empty;
                securityToken = RoleManagement.GetSecurityTokenByRoleId(groupId);
                //HttpCookie securityCookie = new HttpCookie("securityToken");
                //Decoder d= Encoding.UTF8.GetDecoder();

                //securityCookie.Value = Server.UrlEncode(securityToken);
                //HttpContext.Current.Response.Cookies.Add(securityCookie);
                // }
            }
            else
            {
                lblInfo.ForeColor = System.Drawing.Color.Red;
                lblInfo.Text = "Please Select the Group";
            }
        }
        catch (Exception ex)
        {
            new SqlLog().InsertSqlLog(0, "PagePermission.aspx btnAddResources_Click", ex);
        }
    }
开发者ID:AsmaBabarISL,项目名称:Epr_General,代码行数:60,代码来源:PagePermissions.aspx.cs

示例2: SetupClient

        public virtual void SetupClient()
        {
            Configure();

            FreeAgentClient.UseSandbox = KeyStorage.UseSandbox;
            if (KeyStorage.UseProxy) FreeAgentClient.Proxy = new WebProxy("127.0.0.1", 8888);

            Client = new FreeAgentClient(KeyStorage.AppKey, KeyStorage.AppSecret);

            var sandbox_bttest_token = new AccessToken
            {
                access_token = "",
                refresh_token = KeyStorage.RefreshToken,
                token_type = "bearer"
            };

            Client.CurrentAccessToken = sandbox_bttest_token;

            Token = Client.RefreshAccessToken();

            if (Token == null || string.IsNullOrEmpty(Token.access_token) || string.IsNullOrEmpty(Token.refresh_token))
            {
                throw new Exception("Could not setup the Token");
            }
        }
开发者ID:neilortoo,项目名称:FreeAgent,代码行数:25,代码来源:BaseFixture.cs

示例3: Create

        public ActionResult Create(AccessToken accessToken)
        {
            var accessTokenToCreate = new AccessToken();

            Mapper.Map(accessToken, accessTokenToCreate);

            accessTokenToCreate.SetNewToken();

            accessTokenToCreate.TransferValidationMessagesTo(ModelState);

            if (ModelState.IsValid)
            {
                _accessTokenRepository.EnsurePersistent(accessTokenToCreate);

                Message = "AccessToken Created Successfully";

                return RedirectToAction("Details", new { id = accessTokenToCreate.Id });
            }
            else
            {
                var viewModel = AccessTokenViewModel.Create(Repository);
                viewModel.AccessToken = accessToken;

                return View(viewModel);
            }
        }
开发者ID:ucdavis,项目名称:Catbert,代码行数:26,代码来源:AccessTokenController.cs

示例4: saveAccessToken

        public void saveAccessToken(AccessToken token)
        {

            var accesstokenInsertQuery = Resource.ResourceManager.GetString("socialmedia_insert");
            sql_con = new SQLiteConnection(Common.localDatabasePath, true);
            sql_cmd = new SQLiteCommand(accesstokenInsertQuery, sql_con);

            sql_cmd.Parameters.Add("@id", DbType.String);
            sql_cmd.Parameters["@id"].Value = Common.userName;

            sql_cmd.Parameters.Add("@socialMediaType", DbType.String);
            sql_cmd.Parameters["@socialMediaType"].Value = token.tokenType;

            sql_cmd.Parameters.Add("@user_oauth_token", DbType.String);
            sql_cmd.Parameters["@user_oauth_token"].Value = token.tokenValue;

            sql_cmd.Parameters.Add("@is_user_oauth_done", DbType.Int16);
            sql_cmd.Parameters["@is_user_oauth_done"].Value = 1;

            sql_cmd.Parameters.Add("@user_oauth_token_expire_in", DbType.UInt64);
            sql_cmd.Parameters["@user_oauth_token_expire_in"].Value = 1;

            sql_cmd.Parameters.Add("@user_oauth_token_secret_key", DbType.String);
            sql_cmd.Parameters["@user_oauth_token_secret_key"].Value = token.tokenValue;

            sql_con.Open();
            sql_cmd.ExecuteNonQuery();
            sql_con.Close();

        }
开发者ID:soumyaansh,项目名称:Outlook-Widget,代码行数:30,代码来源:AccessTokenDao.cs

示例5: After

        public override void After( object returnValue, MethodInfo method, object[] args, object target )
        {
            Microblog blog = args[0] as Microblog;

            if (blog == null || blog.ParentId > 0) return;
            if (blog.User == null || blog.User.Id <= 0) return;

            if (QQWeiboJobHelper.IsQQWeiboSync( blog.Id )) return; // 是否已经同步过

            UserConnect uc = connectService.GetConnectInfo( blog.User.Id, typeof( QQConnect ).FullName );

            // 1. 检查:用户是否绑定,是否允许同步
            if (uc == null) return; // 绑定
            if (uc.NoSync == 1) {
                logger.Info( "取消同步,因为用户明确禁止" );
                return;
            }

            // 2. 获取 access token
            AccessToken x = new AccessToken();
            x.Token = uc.AccessToken;
            x.Uid = uc.Uid;

            // 3. 同步
            QQConnect connect = AuthConnectFactory.GetConnect( typeof( QQConnect ).FullName ) as QQConnect;
            connect.Publish( x, _blogContent, getPicDiskPath( blog.Pic ) );

            // 设置已经同步标记
            QQWeiboJobHelper.AddQQWeiboSyncItem( blog.Id );
        }
开发者ID:2014AmethystCat,项目名称:wojilu,代码行数:30,代码来源:QQSync.cs

示例6: SaveUserAccessToken

        /// <summary>
        /// Saves the user access token.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="serviceId">The service id.</param>
        /// <param name="accessToken">The access token.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The task that represents the save action.</returns>
        public Task SaveUserAccessToken(string username, string serviceId, AccessToken accessToken, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(username, "username");
            Requires.NotNullOrEmpty(serviceId, "serviceId");
            Requires.NotNull(accessToken, "accessToken");

            return this.SaveAccessToken(NormalizeUsername(username), serviceId, accessToken, cancellationToken);
        }
开发者ID:rvanlaarhoven,项目名称:OAuth2.Mobile,代码行数:16,代码来源:AccessTokenStore.cs

示例7: SendEmailNotifications

        public static string SendEmailNotifications()
        {
            StringBuilder output = new StringBuilder();

            NetflixConnection conn = new NetflixConnection(ConfigurationManager.AppSettings["NetflixConsumerKey"], ConfigurationManager.AppSettings["NetflixConsumerSecret"]);

            DatabaseDataContext db = new DatabaseDataContext();
            foreach (returnflix.Common.User u in db.Users)
            {
                try
                {
                    output.AppendFormat("Executing Netflix account for {0} {1}...<br />", u.FirstName, u.LastName);

                    AccessToken accTok = new AccessToken(u.NetflixUserID, u.NetflixAccessToken, u.NetflixAccessTokenSecret);

                    System.Xml.Linq.XElement atHomeFeed = conn.RequestXmlResource(NetflixUrls.GetUsersAtHome(accTok, 0, 10, DateTime.Now.AddDays(-7)), accTok);
                    string currentMovie = atHomeFeed.Elements("at_home_item").First().Element("title").Attribute("regular").Value;
                    int currentMovieDays = DateTime.Now.Subtract(UnixTimeToDateTime(atHomeFeed.Elements("at_home_item").First().Element("estimated_arrival_date").Value)).Days;

                    System.Xml.Linq.XElement queueFeed = conn.RequestXmlResource(NetflixUrls.GetUsersQueuesDiscAvailable(accTok, QueueSortOrder.QueueSequence, 0, 10, DateTime.Now.AddYears(-1)), accTok);
                    string nextMovie = queueFeed.Elements("queue_item").First().Element("title").Attribute("regular").Value;

                    output.AppendFormat("\"{0}\" has been at home for {1} days.<br />", currentMovie, currentMovieDays);

                    if (DateTime.Now.Subtract(u.LastNotificationDate).Days >= 3 &&
                        currentMovieDays >= 7)
                    {
                        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                        msg.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["SmtpEmailAddress"], "Returnflix");
                        msg.To.Add(u.EmailAddress);
                        msg.Subject = string.Format("Don't Forget to Return \"{0}\" to Netflix", currentMovie);
                        msg.Body = string.Format("Hi {0},\n\nHave you had a chance to watch \"{1}\"? This movie has been at home for a week now. You should return this DVD to Netflix soon so that you can receive your next movie, \"{2}\".\n\nThanks!\n\n--\nReturnflix\nhttp://returnflix.com\n\nTired of the reminders? Unsubscribe at http://returnflix.com/unsubscribe.aspx?id={3}", u.FirstName, currentMovie, nextMovie, u.NetflixUserID);
                        msg.IsBodyHtml = false;

                        System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                        smtp.Host = ConfigurationManager.AppSettings["SmtpHost"];
                        smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);
                        smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SmtpUsername"], ConfigurationManager.AppSettings["SmtpPassword"]);

                        output.AppendFormat("Sending message to {0} {1} ({2}).<br />", u.FirstName, u.LastName, u.EmailAddress);

                        smtp.Send(msg);

                        u.LastNotificationDate = DateTime.Now;
                    }
                }
                catch (Exception ex)
                {
                    output.AppendFormat("Failed due to {0}.<br />", ex.Message);
                }

                output.AppendFormat("Done.<br /><br />");
            }

            db.SubmitChanges();

            return output.ToString();
        }
开发者ID:mbmccormick,项目名称:returnflix,代码行数:58,代码来源:Execute.aspx.cs

示例8: Publish

 //-----------------------------------------------------------------------------
 public virtual JsonObject Publish( AccessToken accessToken, String content, String absPic )
 {
     if (strUtil.IsNullOrEmpty( absPic )) {
         return PublishPost( accessToken, content );
     }
     else {
         return PublishPic( accessToken, content, absPic );
     }
 }
开发者ID:2014AmethystCat,项目名称:wojilu,代码行数:10,代码来源:QQWeiboConnect.cs

示例9: Execute

        public override BaseResponse Execute()
        {
            if (string.IsNullOrEmpty(appid))
            {
                throw new Exception("invalid appid");
            }

            if (string.IsNullOrEmpty(secret))
            {
                throw new Exception("invalid secret");
            }

            AccessTokenResponse tokenRes = null;
            NameValueCollection col = new NameValueCollection();
            col.Add("grant_type", "client_credential");
            col.Add("appid", this.appid);
            col.Add("secret", this.secret);
            DateTime now = DateTime.Now;
            string res = HttpSercice.PostHttpRequest(this.url, col, RequestType.GET, null);
            if(!string.IsNullOrEmpty(res))
            {
                JObject json = null;
                try
                {
                    json = JObject.Parse(res);
                    if(json!=null)
                    {
                        tokenRes = new AccessTokenResponse();
                        AccessToken accessToken = new AccessToken();
                        accessToken.Access_Token = json["access_token"]!=null? json["access_token"].ToString():"";
                        if(!string.IsNullOrEmpty(accessToken.Access_Token))
                        {
                            accessToken.ExpiresIn = json["expires_in"] != null ? int.Parse(json["expires_in"].ToString()) : 0;
                        }
                        accessToken.ExpiresTime = now.AddSeconds(accessToken.ExpiresIn);
                        if(!string.IsNullOrEmpty(accessToken.Access_Token) && accessToken.ExpiresIn>0)
                        {
                            tokenRes.Access_Token = accessToken;
                        }

                        if(json["errcode"]!=null)
                        {
                            tokenRes.err_code = json["errcode"].ToString();
                        }
                        if (json["errmsg"] != null)
                        {
                            tokenRes.err_code_des = json["errmsg"].ToString();
                        }
                    }
                }
                catch
                {
                }
            }
            return tokenRes;
        }
开发者ID:Bobom,项目名称:kuanmai,代码行数:56,代码来源:TokenRequest.cs

示例10: AccessToken

        public static AccessToken AccessToken(int? counter)
        {
            var rtValue = new AccessToken();
            rtValue.Reason = "Reason" + counter.Extra();
            rtValue.SetNewToken();
            rtValue.ContactEmail = "test" + counter.Extra() + "@testy.com";
            rtValue.Application = new Application(); //Need to replace...

            return rtValue;
        }
开发者ID:ucdavis,项目名称:Catbert,代码行数:10,代码来源:CreateValidEntities.cs

示例11: SinaWeiboService

        public SinaWeiboService(string accessToken, string accessTokenSecret)
        {
            if (accessToken.IsNullOrEmpty())
                throw new ArgumentException("accessToken不能为空", "accessToken");

            if (accessTokenSecret.IsNullOrEmpty())
                throw new ArgumentException("accessTokenSecret不能为空", "accessTokenSecret");

            var token = new AccessToken(ConsumerFactory.SinaConsumer, accessToken, accessTokenSecret);
            _weiboClient = new WeiboClient(token, ResultFormat.json);
        }
开发者ID:rench,项目名称:PCRemote,代码行数:11,代码来源:SinaWeiboService.cs

示例12: Login

        /// <summary>
        /// <para>Direct auth with login and password.</para>
        /// <para>See also: <seealso cref="http://vk.com/pages?oid=-1&p=Прямая_авторизация"/></para>
        /// </summary>
        /// <param name="login">Login</param>
        /// <param name="password">Password</param>
        /// <param name="scopeSettings">Scope settings</param>
        /// <param name="captchaSid">Captcha sid</param>
        /// <param name="captchaKey">Captcha key</param>
        /// <returns><see cref="AccessToken"/></returns>
        public async Task<AccessToken> Login(string login, string password, VkScopeSettings scopeSettings = VkScopeSettings.CanAccessFriends, 
            string captchaSid = null, string captchaKey = null)
        {
            if (string.IsNullOrEmpty(_vkontakte.AppId))
                throw new NullReferenceException("App id must be specified.");

            if (string.IsNullOrEmpty(_vkontakte.ClientSecret))
                throw new NullReferenceException("Client secret must be specified.");

            var parameters = new Dictionary<string, string>
            {
                {"username", login},
                {"password", password},
                {"grant_type", "password"},
                {"scope", ((int) scopeSettings).ToString(CultureInfo.InvariantCulture)}
            };

            if (!string.IsNullOrEmpty(captchaSid) && !string.IsNullOrEmpty(captchaKey))
            {
                parameters.Add("captcha_sid", captchaSid);
                parameters.Add("captcha_key", captchaKey);
            }

            parameters.Add("client_id", _vkontakte.AppId);
            parameters.Add("client_secret", _vkontakte.ClientSecret);

            var request = new VkRequest(new Uri(VkConst.DirectAuthUrl), parameters);
            var response = await request.Execute();

            if (response["error"] != null)
            {
                switch (response["error"].Value<string>())
                {
                    case "need_captcha":
                        throw new VkCaptchaNeededException(response["captcha_sid"].Value<string>(), response["captcha_img"].Value<string>());

                    case "invalid_client":
                        throw new VkInvalidClientException();

                    case "need_validation":
                        throw new VkNeedValidationException() { RedirectUri = new Uri(response["redirect_uri"].Value<string>()) };
                }

                return null;
            }

            var token = new AccessToken();
            token.Token = response["access_token"].Value<string>();
            token.UserId = response["user_id"].Value<long>();
            token.ExpiresIn = response["expires_in"].Value<long>() == 0 ? DateTime.MaxValue : DateTimeExtensions.UnixTimeStampToDateTime(response["expires_in"].Value<long>());
            _vkontakte.AccessToken = token;
            return token;
        }
开发者ID:justdude,项目名称:meridian,代码行数:63,代码来源:VkDirectAuthRequest.cs

示例13: DeserializeAccessToken

		/// <summary>
		/// Reads an access token to find out what data it authorizes access to.
		/// </summary>
		/// <param name="message">The message carrying the access token.</param>
		/// <param name="accessToken">The access token's serialized representation.</param>
		/// <returns>The deserialized, validated token.</returns>
		/// <exception cref="ProtocolException">Thrown if the access token is expired, invalid, or from an untrusted authorization server.</exception>
		public virtual AccessToken DeserializeAccessToken(IDirectedProtocolMessage message, string accessToken) {
			ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), ResourceServerStrings.MissingAccessToken);
			var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey);
			var token = new AccessToken();
			try {
				accessTokenFormatter.Deserialize(token, accessToken, message, Protocol.access_token);
			} catch (IOException ex) {
				throw new ProtocolException(ResourceServerStrings.InvalidAccessToken, ex);
			}

			return token;
		}
开发者ID:brivas,项目名称:DotNetOpenAuth,代码行数:19,代码来源:StandardAccessTokenAnalyzer.cs

示例14: SetLoginVk

 public static void SetLoginVk(AccessToken token)
 {
     if (token == null || token.Token == null)
     {
         throw new ArgumentException("AccessToken is empty");
     }
     else
     {
         _vkontakte.AccessToken = token;
         Settings.Instance.AccessToken = token;
         Settings.Instance.Save();
         Messenger.Default.Send(new LoginMessage() { Type = LoginType.LogIn, Service = "vk" });
     }
 }
开发者ID:justdude,项目名称:meridian,代码行数:14,代码来源:AccountManager.cs

示例15: IssueAccessTokenForResourceOwner

		public IToken IssueAccessTokenForResourceOwner(ITokenContext context)
		{

			AccessToken token = new AccessToken
			{
				ExpiresIn = 120,
				Token = Guid.NewGuid().ToString(),
				RefreshToken = Guid.NewGuid().ToString(),
				Scope = new string[] { "create", "delete", "view" },
			};
			TokenRepo.AddAccessToken(token);
			return token;

		}
开发者ID:ghorsey,项目名称:SharpOAuth2,代码行数:14,代码来源:TokenService.cs


注:本文中的AccessToken类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。