protected void LinkButton1_Click(object sender, EventArgs e) { //Response.Write( GetBytesByImagePath("/img/bg1.jpg")); if (Session["Token"] == null) { //string cusCallbackUrl = CallbackUrl + "?point=1"; OAuth myoauth = new NetDimension.Weibo.OAuth(AppKey, AppSecret, CallbackUrl); String authUrl = myoauth.GetAuthorizeURL(ResponseType.Code, null, DisplayType.Default); Response.Redirect(authUrl); } else { Sina = new Client(new OAuth(AppKey, AppSecret, Session["Token"].ToString(), null)); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 UserID = Sina.API.Account.GetUID(); string weiboContent = "想让韩国国宝级彩妆大师朴泰轮教你如何打造少女肌肤吗?现在观看#人人都爱少女肌肤#教学视频就能从#innisfree#这里学到少女肌肤的底妆秘籍,还有机会赢取#悦诗风吟矿物质纯安动人粉底膏#哦!立刻猛击"; string jpgPath = Server.MapPath("") + "\\img\\bg1.jpg"; Sina.API.Statuses.Upload(weiboContent, GetBytesByImagePath(jpgPath)); //Sina.API.Statuses.Update(weiboContent); } }
//加载微博信息 private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e) { if (Authorize.oauth == null) { MessageBox.Show("请先登录!"); return; } if (e.KeyChar != 032) return; int count; if (int.TryParse(toolStripTextBox1.Text, out count)) { 工具ToolStripMenuItem.HideDropDown(); try { //实例化一个操作类,用刚才成功获得了AccessToken的OAuth实例 NetDimension.Weibo.Client Sina = new NetDimension.Weibo.Client(Authorize.oauth); //调用各种方法 var JsonText = Sina.API.Dynamic.Statuses.FriendsTimeline(null, null, count); //BasicFunc.JsonInfo(this, JsonText); BasicFunc.ShowStatus(this, JsonText); }//try catch (Exception ex) { lstMessage.Items.Insert(0, ex.Message); } } else MessageBox.Show("请输入一个整数!", "错误警告", MessageBoxButtons.OK, MessageBoxIcon.Error); }
/// <summary> /// 微博用户登录 /// </summary> private void login() { string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"]; string appSecret = System.Configuration.ConfigurationManager.AppSettings["appSecret"]; string userName = System.Configuration.ConfigurationManager.AppSettings["userName"]; string password = System.Configuration.ConfigurationManager.AppSettings["userPassword"]; OAuth oauth = new OAuth(appKey, appSecret); oauth.ClientLogin(userName, password); client = new Client(oauth); }
public Form1() { InitializeComponent(); appKey = Properties.Settings.Default.AppKey; appSecret = Properties.Settings.Default.AppSecret; accessToken = Properties.Settings.Default.AcessToken; serialReadFlag = false; OAuth oauth = null; sina = null; if (string.IsNullOrEmpty(accessToken))//如果本地未保存accessToken,这里没有做过期判断2012-10-5 { oauth = Authorize(); if (!string.IsNullOrEmpty(oauth.AccessToken)) { Properties.Settings.Default.AcessToken = oauth.AccessToken; Properties.Settings.Default.Save(); statTxt.Text = "授权成功,保存accesstoken"; sina = new Client(oauth); } else { statTxt.Text = "授权失败,未获取accesstoken"; } } else { oauth = new OAuth(appKey, appSecret, accessToken, "");//最后一个参数是refreshtoken这个是面向高级用户对的 TokenResult tokenResult = oauth.VerifierAccessToken(); if (tokenResult == TokenResult.Success) { statTxt.Text = "验证本地accesstoken有效"; sina = new Client(oauth); } else { Properties.Settings.Default.AcessToken = string.Empty; Properties.Settings.Default.Save(); statTxt.Text = "验证本地accesstoken无效,尝试重新授权"; oauth = Authorize(); if (!string.IsNullOrEmpty(oauth.AccessToken)) { Properties.Settings.Default.AcessToken = oauth.AccessToken; Properties.Settings.Default.Save(); statTxt.Text = "授权成功,重新保存accesstoken"; sina = new Client(oauth); } else { statTxt.Text = "授权失败,未获取accesstoken"; } } } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string cusCallbackUrl = CallbackUrl + "?point=1"; OAuth oauth = new NetDimension.Weibo.OAuth(AppKey, AppSecret, cusCallbackUrl); if (Session["Token"] != null) { string token = (string)Session["Token"]; OAuth newoauth = new OAuth(AppKey, AppSecret, token, ""); NetDimension.Weibo.Client Sina = new NetDimension.Weibo.Client(newoauth); String uid = Sina.API.Account.GetUID(); NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Users.Show(uid, null); //NetDimension.Weibo.Entities.user.Collection userFriends = new NetDimension.Weibo.Entities.user.Collection(); Session["wid"] = uid; Response.Redirect(CallbackUrl); } else { String mycode = Request.QueryString["code"]; if (mycode == String.Empty || mycode == null) { String authUrl = oauth.GetAuthorizeURL(ResponseType.Code, null, DisplayType.Default); Response.Redirect(authUrl); } else { AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(mycode); NetDimension.Weibo.Client Sina = new NetDimension.Weibo.Client(oauth); String uid = Sina.API.Account.GetUID(); //Response.Write(uid); Session["wid"] = Sina.API.Account.GetUID(); Response.Redirect(CallbackUrl); Session["Token"] = accessToken.Token; } } } }
public override void Post() { if (!String.IsNullOrEmpty(this.accessToken = Config.WeiboAccessToken)) { oauth = new OAuth(AppKey, AppSecret, accessToken, null); sinaClient = new Client(oauth); PostWeibo(); } else { AuthAndPost(); } }
private void btnSendToWeibo_Click(object sender, EventArgs e) { OAuth oauth = new OAuth(appKey, appSecrect, callbackUrl); string passport = this.txtName.Text.Trim(); string password = this.txtPwd.Text.Trim(); //string accessToken = string.Empty; bool result = oauth.ClientLogin(passport, password); if (!result) { MessageBoxHelper.Show("微博登陆失败!"); return; } //好吧,授权至此应该成功了。下一步调用接口吧。 Client Sina = new Client(oauth); try { //.Net其他版本 string uid = Sina.API.Account.GetUID(); //获取UID //这里用VS2010的var关键字和可选参数最惬意了。 //如果用VS2005什么的你得这样写: //NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Users.Show(uid,null); //如果用VS2008什么的也不方便,你得把参数写全: //var userInfo = Sina.API.Users.Show(uid,null); var userInfo = Sina.API.Users.Show(uid, null); Console.WriteLine("昵称:{0}", userInfo.ScreenName); Console.WriteLine("来自:{0}", userInfo.Location); //发条微博啥的 Image img = this.imageProcessPanel1.GetFinalImage(); //var statusInfo = Sina.API.Statuses.Update(string.Format("我是{0},我来自{1},我在{2}用《新浪微博开放平台API for .Net SDK》开发了一个小程序并发了这条微博,欢迎关注http://weibosdk.codeplex.com/", userInfo.ScreenName, userInfo.Location, DateTime.Now.ToShortTimeString()),0,0,""); var statusInfo = Sina.API.Statuses.Upload("测试内容"+System.DateTime.Now.ToLocalTime().ToString(), ImageHelper.GetBytesByImage(img), 0, 0, ""); //加个当前时间防止重复提交报错。 Console.WriteLine("微博已发送,发送时间:{0}", statusInfo.CreatedAt); MessageBoxHelper.Show("微博已发送"); } catch (WeiboException ex) { Console.WriteLine("出错啦!" + ex.Message); MessageBoxHelper.Show("出错啦!" + ex.Message); } Console.WriteLine("演示结束,按任意键继续..."); }
/// <summary> /// Share Kinect image to Sina Weibo /// </summary> /// <param name="imagePath">Image path</param> /// <param name="Content">Text description for Image</param> public void Share2Weibo(String imagePath="",String Content="") { if (oAuth != null) { Client Sina = new Client(oAuth); string uid = Sina.API.Entity.Account.GetUID(); var entity_userInfo = Sina.API.Entity.Users.Show(uid); if (string.IsNullOrEmpty(Content)) Content = string.Format("#Kinect for Windows 创新应用开发全国挑战赛# 我是{0},来自{1},我在{2}用KinectJoy发布分享了本条微博,欢迎关注\"2013码上Kinect\"~~ http://www.microsoft.com/zh-cn/kinectforwindows/campaign/trainning.aspx", entity_userInfo.ScreenName, entity_userInfo.Location, DateTime.Now.ToLongTimeString()); if (string.IsNullOrEmpty(imagePath)) { var StatusInfo = Sina.API.Entity.Statuses.Update(Content); } else { var StatusInfo = Sina.API.Entity.Statuses.Upload(Content, GetPictureData(imagePath)); } } }
void GetWeibo() { LogInWeibo();//登录验证 Sina = new Client(oauth); var json = Sina.API.Entity.Statuses.UserTimeline(count: 1); if (json.Statuses == null) { return; } foreach (var status in json.Statuses) { if (status.User == null) { continue; } Console.WriteLine(status.Text); } }
public Boolean checkIDByStatuses(Client client, string userID,string startStatusID, int sumNum = 50) { int statusNum = 0; try { string statusID = startStatusID; bool endFlag = false; int pageNum = 1; List<string> weibo_id_flag = new List<string>(); while (!endFlag && statusNum < sumNum) { var statusCollection = client.API.Entity.Statuses.UserTimeline(userID, "", "", statusID, 100, 1, false, 0, true); log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 分析用户" + userID + "第" + (pageNum++) + "页微博,总" + statusCollection.Statuses.Count() + "条微博"); endFlag = true; List<NetDimension.Weibo.Entities.status.Entity> statuslist = new List<NetDimension.Weibo.Entities.status.Entity>(); foreach (NetDimension.Weibo.Entities.status.Entity status in statusCollection.Statuses) { statusID = status.ID; if (!weibo_id_flag.Contains(statusID)) { weibo_id_flag.Add(statusID); endFlag = false; if (CommonLib.CompareDate.lStartTime(CommonLib.DataTranslate.SinaDateToString(status.CreatedAt))) { endFlag = true; break; } statusNum++; } } }//while log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 分析用户" + userID + "结束......"); } catch (WeiboException wex) { log.Info(wex.Message); } catch (Exception ex) { log.Info(ex.Message); } return statusNum >= sumNum ? true : false; }
/// <summary> /// 初始化Weibo /// </summary> /// <returns></returns> private string InitWeiboOAuth() { if (Session["AccessToken"] == null) { OAUTH = new OAuth(APPKEY, APPSECRET, RETURNURL); if (!OAUTH.ClientLogin(WEIBO_NAME, PASSWORD)) { return "授权登录失败,请重试。"; } else { Session["AccessToken"] = OAUTH.AccessToken; Sina = new Client(OAUTH); UserID = Sina.API.Entity.Account.GetUID(); return OAUTH.AccessToken; } } else { return (string)Session["AccessToken"]; } }
public List<string> operation(Client client, NetDimension.Weibo.Entities.user.Entity user,int depth,string tagname) { List<string> list = new List<string>(); string userID = user.ID; try { var SinaClient = client; var userCollection = SinaClient.API.Entity.Friendships.FollowersInActive(userID, 200); for (int i = 0; i < userCollection.Count(); i++) { var followeruser = userCollection.ElementAt(i); string sql = "select * FROM sinauser WHERE uid = '" + followeruser.ID + "'"; bool isexist = db_SQLServer.SQLServerUnit.getInstance().isExist(sql); if (!isexist) { var usertags = SinaClient.API.Entity.Tags.Tags(followeruser.ID); if (checkTags(usertags, tagname)) { list.Add(followeruser.ID + " " + (depth + 1)); sql = "INSERT INTO sinauser(uid,statuses,depth) VALUES('" + followeruser.ID + "','" + followeruser.StatusesCount + "','" + (depth + 1) + "')"; db_SQLServer.SQLServerUnit.getInstance().insert(sql); } } } } catch (WeiboException e) { log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 异常 {0} :\n[" + e.Message + "]"); } catch (Exception e) { log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 异常 {0} :\n[" + e.Message + "]"); } return list; }
public bool Login(string passport, string password) { accessToken = Properties.Settings.Default.AccessToken; if (string.IsNullOrEmpty(accessToken)) { try { oauth = Authorize(passport, password); online = true; sina = new Client(oauth); return true; } catch (Exception e) { return false; } } else { /* oauth = new OAuth(AppKey, AppSecret, accessToken, ""); TokenResult result = oauth.VerifierAccessToken(); if (result == TokenResult.Success) { //empty } else { return false; } */ return true; } return true; }
public SinaWeiboService(string sessionKey) { accessor=new PlatFormInfoAccessor(); this.sessionKey = sessionKey; sinaClient = InitializeSinaClient(); }
private TokenResult VerifyAccessToken(Client sinaClient) { TokenResult tokenResult; try { tokenResult = sinaClient.OAuth.VerifierAccessToken(); } catch (Exception ex) { throw new CustomException.TokenVerificationException() { Message = "验证SessionKey出现网络异常:" + ex.Message }; } return tokenResult; }
private Client InitializeSinaClient() { if (!string.IsNullOrEmpty(sessionKey))//检查是否存在SessionKey,后续可能还要从数据库去取 { OAuth2Base sinaAuth2 = new SinaWeiboOAuth2(); OAuth auth = new OAuth(sinaAuth2.AppKey, sinaAuth2.AppSecret, sessionKey, null); Client sinaClient = new Client(auth); return sinaClient; } else { throw new CustomException.NullWeiboSessionKeyException(); } }
public ActionResult SinaLogin(string type, string code) { try { ViewData["Code"] = code; ///如果code为空表示未登录成功 OAuth oauth = new OAuth("3780257084", "82231a680efedcd67b30c41c714ec85a", "http://www.csvfx.com/Home/SinaLogin?type=1"); var token = oauth.GetAccessTokenByAuthorizationCode(code); ViewData["accessToken"] = token.Token; Client Sina = new Client(new OAuth("3780257084", "82231a680efedcd67b30c41c714ec85a", token.Token, null)); string openID = Sina.API.Entity.Account.GetUID(); var user = Sina.API.Dynamic.Users.Show(ViewData["UID"].ToString()); string pic = user["profile_image_url"]; string nickName = user["screen_name"]; string email = ""; string password = ""; if (type == "0")//登录 { UMQuickLoginManager.Instance.SinaQuickLogin(openID, nickName, pic, ref email, ref password); ValidateUser(email, password, 2, "quicklogin"); return RedirectToAction("Dashboard", "Home"); } if (type == "1")//绑定 { ViewData["Message"] = UMQuickLoginManager.Instance.BindThirdParty(openID, nickName, pic, QuickLoginType.微博, SignInAccount.GID, ref email, ref password); ViewData["Email"] = email; ViewData["Password"] = password; return View(); } if (type == "2")//解除绑定 { UMQuickLoginManager.Instance.ReleseBind(openID, ref email, ref password); ViewData["Email"] = email; ViewData["Password"] = password; return View(); } } catch (Exception ex) { RedirectToAction("Error", "Error"); } return RedirectToAction("Error", "Error"); }
public JsonResult OAuthInit() { JsonResult jr = new JsonResult(); jr.ContentType = "text/json"; jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; try { Client Sina = null; OAuth oauth = new OAuth(CnfgConst.Sina_AppKey, CnfgConst.Sina_AppSecret, CnfgConst.Sina_CallbackUrl); Sina = new Client(oauth); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 //if (!string.IsNullOrEmpty(code))//暂时无法获取到传回的URL //{ // var token = oauth.GetAccessTokenByAuthorizationCode(code); // string accessToken = token.Token; // Response.Cookies["AccessToken"].Value = accessToken; // jr.Data = new { isSuccess = true }; // //Response.Redirect("Default.aspx"); //} //else { string url = oauth.GetAuthorizeURL(); jr.Data = new { isSuccess = false, url = url }; } return jr; } catch (Exception) { throw; } }
private void 调用ToolStripMenuItem_Click(object sender, EventArgs e) { if (Authorize.oauth == null) { MessageBox.Show("请先登录!"); return; } try { //实例化一个操作类,用刚才成功获得了AccessToken的OAuth实例 NetDimension.Weibo.Client Sina = new NetDimension.Weibo.Client(Authorize.oauth); //调用各种方法 var JsonText = Sina.API.Dynamic.Statuses.FriendsTimeline(null, null, 1) ; BasicFunc.ShowStatus(this, JsonText); foreach (var status in JsonText.statuses) { if (status.IsDefined("user")) //这里要判断下是不是有user这个项,一般微博被删除了就不会返回user,直接xxx.user要出错。 { lstMessage.Items.Insert(0, status);//打印用户名和他说的内容 } } }//try catch (Exception ex) { lstMessage.Items.Insert(0, ex.Message); } }
//由通过认证的新浪客户端,调取当前登录用户及其所关注用户的最新微博接口Friends_Timeline,n最大是一次100条 //获得最新的n条含有用户关键字的公共微博信息并存入数据库 public void getFriends_Timeline_sina(Client sinaClient, int n) { StringBuilder sql = new StringBuilder(); ArrayList lst_kw = new ArrayList(); Hashtable ht_evt = new Hashtable(); try { NetDimension.Weibo.Entities.status.Collection satColl = sinaClient.API.Entity.Statuses.FriendsTimeline("", "", n); foreach (NetDimension.Weibo.Entities.status.Entity entity in satColl.Statuses) { string text = entity.RetweetedStatus == null ? entity.Text : entity.Text + entity.RetweetedStatus.Text; if (!weibo_ids.Equals(entity.ID) || long.Parse(weibo_ids.Equals("") ? "0" : weibo_ids) > long.Parse(entity.ID)) { //把正文里包含的关键词都放入list for (int i = 0; i < dt_kw.Rows.Count; i++) { string[] _words = dt_kw.Rows[i][0].ToString().Split(new char[] { ' ' }); if (!lst_kw.Contains(dt_kw.Rows[i][0].ToString())) { lst_kw.Add(dt_kw.Rows[i][0].ToString()); foreach (string w in _words) { if (!text.Contains(w)) { lst_kw.Remove(dt_kw.Rows[i][0].ToString()); break; } } } } ht_evt = evtJudge(dt_event, lst_kw); if (ht_evt.Count > 0) { int part = partJudge(dt_partWord, text); weibo_ids = entity.ID; //string text = entity.RetweetedStatus == null ? entity.Text : entity.Text + entity.RetweetedStatus.Text; foreach (DictionaryEntry de in ht_evt) { int urlTherear = UrlThereare(entity.ID); if (urlTherear <= 0) { sql = sql.Append("insert into ReleaseInfoWB (title,contexts,releasedate,infosource," + "keywords,releasename,collectdate,snapshot,webname,pid,part,reposts,comments,kid) values ('"+entity.ID+"','" + text + "','" + string.Format(NetDimension.Weibo.Utility.ParseUTCDate(entity.CreatedAt).ToString("yyyy-MM-dd HH:mm:ss")) + "','" + "http://weibo.com/" + entity.User.ID + "','" + de.Key.ToString() + "','" + entity.User.Name + "','" + string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "','','" + "新浪微博" + "','" + "3" + "','" + part.ToString() + "','" + entity.RepostsCount + "','" + entity.CommentsCount + "'," + de.Value.ToString() + ");"); } } } lst_kw.Clear(); } } } catch (Exception err) { Console.Write(err.Message); } //插入数据库 if (sql.Length > 0) cmd.ExecuteNonQueryInt(sql.ToString()); }
public void getSinaClientAuto() { access_token = xmlutil.GetValue("AccessToken"); oauth = new OAuth(app_key, app_secret, access_token, ""); //用Token实例化OAuth无需再次进入验证流程 TokenResult result = oauth.VerifierAccessToken(); if (result == TokenResult.Success) { sina = new Client(oauth); } }
public void getSinaClient() { string code = ""; if (string.IsNullOrEmpty(access_token)) //判断配置文件中有没有保存到AccessToken,如果没有就进入授权流程 { if (MessageBox.Show("新浪微博未授权或授权已过期,请重新授权!", "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK) { Forms.SinaWBOauth sinaWbForm = new Forms.SinaWBOauth(); sinaWbForm.thread_in = "1"; if (sinaWbForm.ShowDialog() == DialogResult.OK) { if (sinaWbForm.retrun_url.Contains("code=")) { string[] url = sinaWbForm.retrun_url.Split('='); if (url.Length > 0) { code = url[1]; } oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url); at = oauth.GetAccessTokenByAuthorizationCode(code); xmlutil.SetValue("AccessToken", at.Token); sina = new Client(new OAuth(app_key, app_secret, at.Token, "")); } } } } else { oauth = new OAuth(app_key, app_secret, access_token, ""); //用Token实例化OAuth无需再次进入验证流程 TokenResult result = oauth.VerifierAccessToken(); if (result == TokenResult.Success) { sina = new Client(oauth); } } }
public eClient(Client client) { this._client = client; }
/// <summary> /// 初始化Weibo /// </summary> /// <returns></returns> private static void InitWeiboOAuth(string APPKEY, string APPSECRET, string ACCESSTOKEN) { OAUTH = new OAuth(APPKEY, APPSECRET, accessToken: ACCESSTOKEN); if (OAUTH.VerifierAccessToken() == TokenResult.Success)//验证AccessToken是否有效 { SINA = new NetDimension.Weibo.Client(OAUTH); Console.WriteLine(OAUTH.AccessToken); //还是来打印下AccessToken看看与前面方式获取的是不是一样的 //streamWriter.WriteLine(OAUTH.AccessToken); } }
private void webBrowserAg_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { string urlAdd = "https://rd.tencent.com/top/ptlogin/ptlogins/login?site="; string urlAdd2 = "https://tapd.tencent.com/ptlogin/ptlogins/login?"; if ((webBrowserWb.Url != null && webBrowserWb.Url.ToString().Contains(urlAdd)) || (webBrowserWb.Url != null && webBrowserWb.Url.ToString().Contains(urlAdd2))) { //判断是否已加载完网页 if (webBrowserWb.ReadyState == WebBrowserReadyState.Complete) { //获取网页文档对象,相当于获取网页的全部源码 HtmlDocument htmlDoc = this.webBrowserWb.Document; //设置帐号 HtmlElement id = htmlDoc.GetElementById("username"); id.SetAttribute("value", FrmSet.UserName); //设置密码 HtmlElement pwd = htmlDoc.GetElementById("password_input"); pwd.SetAttribute("value", FrmSet.PassWord); //登录 HtmlElement btn = htmlDoc.GetElementById("login_button"); if (btn != null) { btn.InvokeMember("click"); } } } // 根据id找到对应的元素 HtmlElement htmlEle = webBrowserWb.Document.GetElementById("checkin_btn"); if (htmlEle != null) { // 激活html元素的 click 成员 htmlEle.InvokeMember("click"); System.Threading.Thread submitT = new Thread(() => { Thread.Sleep(1000); bool search = true; try { while (search) { webBrowserWb.Invoke(new Action(() => { HtmlDocument cd = webBrowserWb.Document; HtmlElementCollection dhl = cd.GetElementsByTagName("BUTTON"); foreach (HtmlElement item in dhl) { if (item.InnerText == "提交" || item.InnerText == "Submit") { item.InvokeMember("click"); search = false; Share.wFiles.WriteString("WCO", "LastSignInTime", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now)); FrmSet.CheckInTime = DateTime.Now; if (WeiboOauth != null) { Sina = new Client(WeiboOauth); Sina.API.Entity.Statuses.Update(string.Format("{0} {1} {2}", Type, "成功签入", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now))); } webBrowserWb.Dispose(); } } })); Thread.Sleep(1000); } } catch (Exception ex) { LogUtil.WriteError(ex); } }); submitT.Start(); } }
/// <summary> /// 根据id调用Status/Show /// </summary> /// <param name="statusid"></param> private void LoadStatusShow(string statusid) { if (Sina == null) { Sina = new Client(OAUTH); } dynamic json = Sina.API.Dynamic.Statuses.Show(statusid); try { if (json != null) { var isInHarzardsDb = db.HarzardsDb.Find(json.id); if (isInHarzardsDb == null) { Hazards hazardsEntity = new Hazards(); hazardsEntity.CreatedAt = json.created_at; hazardsEntity.ID = json.id; hazardsEntity.Text = json.text; if (hazardsEntity.Text.IndexOf("此微博已被作者删除") <= -1 && hazardsEntity.Text.IndexOf("此微博已被删除") <= -1) { User userEntity = new User(); userEntity.ID = json.user.id; userEntity.IDStr = json.user.idstr; userEntity.Name = json.user.name; userEntity.Province = json.user.province; userEntity.City = json.user.city; userEntity.Location = json.user.location; userEntity.ProfileImageUrl = json.user.profile_image_url; userEntity.Gender = json.user.gender; userEntity.CreatedAt = json.user.created_at; var isInUserDb = db.UserDb.Find(json.user.id); if (isInUserDb == null) { db.UserDb.Add(userEntity); db.SaveChanges(); } hazardsEntity.Source = json.source; if (json.IsDefined("thumbnail_pic")) { hazardsEntity.ThumbnailPictureUrl = json.thumbnail_pic; hazardsEntity.MiddleSizePictureUrl = json.bmiddle_pic; hazardsEntity.OriginalPictureUrl = json.original_pic; } if (json.geo != null) { hazardsEntity.Long = (float)json.geo.coordinates[1]; hazardsEntity.Lat = (float)json.geo.coordinates[0]; } //else //{ // statusEntity.Long = 0f; // statusEntity.Lat = 0f; //} hazardsEntity.RepostsCount = int.Parse(json.reposts_count); hazardsEntity.CommentsCount = int.Parse(json.comments_count); hazardsEntity.AttitudeCount = int.Parse(json.attitudes_count); hazardsEntity.UserID = userEntity.ID; db.HarzardsDb.Add(hazardsEntity); db.SaveChanges(); } } } } finally { } }
protected void Page_Load(object sender, EventArgs e) { //string cusCallbackUrl = CallbackUrl + "?point=1"; //Response.Write(Server.MapPath("") + "\\images\\bg1.jpg"); OAuth oauth = new NetDimension.Weibo.OAuth(AppKey, AppSecret, CallbackUrl); if (Session["Token"] != null) { string token = (string)Session["Token"]; OAuth newoauth = new OAuth(AppKey, AppSecret, token, ""); Sina = new Client(newoauth); UserID = Sina.API.Account.GetUID(); NetDimension.Weibo.Entities.user.Entity userInfo = Sina.API.Users.Show(UserID, null); UserName = userInfo.ScreenName; Session["wid"] = UserID; } else { String mycode = Request.QueryString["code"]; if (mycode == String.Empty || mycode == null) { } else { AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(mycode); Sina = new NetDimension.Weibo.Client(oauth); String UserID = Sina.API.Account.GetUID(); Session["wid"] = UserID; Session["Token"] = accessToken.Token; } } }
public void operation(Client client, NetDimension.Weibo.Entities.user.Entity user) { string userID = user.ID; try { var SinaClient = client; /* //保存用户信息 string sql = "select * FROM dbo.Users WHERE uid = '" + userID + "'"; bool isexist = db_SQLServer.SQLServerUnit.getInstance().isExist(sql); if (!isexist) { userService.insertUser(user); log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 保存用户信息: " + userID); } //保存用户标签 var usertags = SinaClient.API.Entity.Tags.Tags(user.ID); saveUserTags(user, usertags); log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 保存用户标签: " + userID); */ string statusID = "-1"; if (user.Status != null) { statusID = user.Status.ID; } bool endFlag = false; int pageNum = 1; int statusNum = 0; List<string> weibo_id_flag = new List<string>(); while (!endFlag && !statusID.Equals("-1")) { var statusCollection = client.API.Entity.Statuses.UserTimeline(userID, "", "", statusID, 100, 1, false, 0, true); log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 保存用户" + userID + "第" + (pageNum++) + "页微博,总" + statusCollection.Statuses.Count() + "条微博"); endFlag = true; List<NetDimension.Weibo.Entities.status.Entity> statuslist = new List<NetDimension.Weibo.Entities.status.Entity>(); foreach (NetDimension.Weibo.Entities.status.Entity status in statusCollection.Statuses) { statusID = status.ID; if (!weibo_id_flag.Contains(statusID)) { weibo_id_flag.Add(statusID); endFlag = false; if (CommonLib.CompareDate.lStartTime(CommonLib.DataTranslate.SinaDateToString(status.CreatedAt))) { endFlag = true; log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 用户" + userID + "抓取不在时间范围内,正在退出......"); break; } /*if (CommonLib.CompareDate.gEndTime(CommonLib.DataTranslate.SinaDateToString(status.CreatedAt))) { continue; }*/ if (!saveUserBlog(user, status)) { endFlag = true; break; } statusNum++; log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 保存用户" + userID + "微博,微博ID: " + statusID); } } }//while log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 用户" + userID + "微博抓取结束,总" + statusNum + "条微博......"); //sql = "UPDATE sinauser SET iscrawler = '1' WHERE uid = '" + userID + "'"; //db_SQLServer.SQLServerUnit.getInstance().update(sql); } catch (WeiboException e) { log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 异常 {0} :\n[" + e.Message + "]"); } catch (Exception e) { log.Info("线程: " + threadNo.ToString() + "-" + subThreadNo.ToString() + " 异常 {0} :\n[" + e.Message + "]"); } }
void SaveAndPost() { Config.WeiboAccessToken = this.accessToken = oauth.AccessToken; sinaClient = new Client(oauth); PostWeibo(); }
public JsonResult OAuthLogin(string code) { JsonResult jr = new JsonResult(); jr.ContentType = "text/json"; jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; try { Client Sina = null; OAuth oauth = new OAuth(CnfgConst.Sina_AppKey, CnfgConst.Sina_AppSecret, CnfgConst.Sina_CallbackUrl); Sina = new Client(oauth); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 if (!string.IsNullOrEmpty(code))//暂时无法获取到传回的URL { var token = oauth.GetAccessTokenByAuthorizationCode(code); string accessToken = token.Token; Response.Cookies["AccessToken"].Value = accessToken; var userinfo = Sina.API.Dynamic.Users.Show(token.UID.ToString(), ""); jr.Data = new { isSuccess = true, Data = userinfo.ToString() }; //Response.Redirect("Default.aspx"); } else { jr.Data = new { isSuccess = false }; } return jr; } catch (Exception) { throw; } }
/// <summary> /// place/pois/users /// 米亚罗 B2094757D16FAAFA4392 530 31.657766465 102.80677515 /// 米亚罗自然保护区 B2094653DB64ABFD499C 193 31.65477 102.810272 /// 古尔沟温泉山庄 B2094653DB64A1FB469C 31.49766 102.97848 /// 毕棚沟旅游景区 B2094653DB64A0FA459E 31.40819 102.98744 /// 毕棚沟 B2094751D569AAFA409E 103.071091 31.402451 /// 娜姆湖 B2094653DB64A0FA4899 102.95245 31.31969 /// 桃坪羌寨 B2094757D16CAAF4469C 103.45722781 31.554634941 /// 桃坪寨 B2094653DB64A1F8489D 103.46205 31.57092 /// 白空寺 B2094653DB64ABFE459D 103.45392 31.60256 /// 甘堡藏家 B2094653DB64A1F4409D 103.19954 31.48252 /// </summary> private void LoadPoiUesr(string poiid,float lon,float lat) { int times = 0; if (Sina == null) { Sina = new Client(OAUTH); } dynamic json = Sina.API.Dynamic.Place.POIUsers(poiid, 50, 1, false); //IEnumerable<NetDimension.Weibo.Entities.user.Entity> users = json; if (json.IsDefined("total_number")) { int totalNumber = int.Parse(json.total_number); times = totalNumber / 50 + 1; } LoadPoiUserReadJson(json,lon,lat); for (int i = 2; i <= times; i++) { dynamic newjson = Sina.API.Dynamic.Place.POIUsers(poiid, 50, i, false); LoadPoiUserReadJson(newjson,lon,lat); } //return users; }
public frmChat(NetDimension.Weibo.OAuth oauth) { InitializeComponent(); this.oauth = oauth; Sina = new NetDimension.Weibo.Client(oauth); }