Getting error in Twitterizer (update status or tweet) in c# - c#

Actually i want to loop the twitterizer or update the tweet everytime when the loop iterate. When it starts the loop i=0 then everthing works fine.But when the loop iterate and i=1 then i am getting the below error in at enter image description here
An exception of type 'Twitterizer.TwitterizerException' occurred in Twitterizer2.dll but was not handled in user code
Additional information: The remote server returned an error: (401) Unauthorized.
string x;
var list2 = (List<string>)Session["title"];
if (list2 == null)
{
x = "No new Products Found";
}
else
{
x = string.Join(",", list2);
// x= list2[0];
}
//foreach (string x in list2)
//{
// Your code
for(int i=0;i<3;i++)
{
var oauth_consumer_key = "[REDACTED]";
var oauth_consumer_secret = "[REDACTED]";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
if(reqToken !=null)
{
Session["reqToken"] = reqToken;
}
string mx = Session["reqToken"].ToString();
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string fx = Session["reqToken"].ToString();
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
if(tokens!=null)
{
Session["tokens"] = tokens;
}
//var tokens = OAuthUtility.GetAccessToken(
//oauth_consumer_key,
//oauth_consumer_secret,
//requestToken,
//pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
//TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
// accesstoken,
// "Testing!! It works (hopefully).");
Twitterizer.TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken, x, new StatusUpdateOptions() { UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/" });
if (response.Result == RequestResult.Success)
{
// Response.Redirect("https://twitter.com/");
}
else
{
// Response.Redirect("https://twitter.com/");
}
}
}
}
Please help me i spent many hours on that but i do not know where is the error.

Related

How to authorize gmail to read my inbox using botframework web channel

I'm trying to use service of gmail to read inbox data and to show them in my chatbot. I want to authenticate using my account of gmail. When i test the chatbot in bot emulator works fine, the problem start when i deploy on web..i cannot authenticate on web.
string jsonPath2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "client_secret_webapp.json";
UserCredential credential;
string[] Scopes = { GmailService.Scope.GmailReadonly };
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
using (var stream = new FileStream(jsonPath2, FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for read-only access to the authenticated
// user's account, but not other types of account access.
new[] { GmailService.Scope.GmailReadonly,},
"xxxx#gmail.com",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var gmailService = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
log.Info("ApplicationName" + ApplicationName);
var emailListRequest = gmailService.Users.Messages.List("xxxxx#gmail.com");
emailListRequest.LabelIds = "INBOX";
emailListRequest.MaxResults = 1;
emailListRequest.Q = "is:unread";
emailListRequest.IncludeSpamTrash = false;
if (emailListResponse != null && emailListResponse.Messages != null)
{
//loop through each email and get what fields you want...
foreach (var email in emailListResponse.Messages)
{
var emailInfoRequest = gmailService.Users.Messages.Get("xxxxxx#gmail.com", email.Id);
var emailInfoResponse = emailInfoRequest.Execute();
if (emailInfoResponse != null)
{
String from = "";
String date = "";
String subject = "";
String body = "";
//loop through the headers to get from,date,subject, body
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
if (mParts.Name == "Date")
{
date = mParts.Value;
}
else if (mParts.Name == "From")
{
from = mParts.Value;
}
else if (mParts.Name == "Subject")
{
subject = mParts.Value;
}
if (date != "" && from != "")
{
if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null)
body = DecodeBase64String(emailInfoResponse.Payload.Body.Data);
else
body = GetNestedBodyParts(emailInfoResponse.Payload.Parts, "");
}
}
await context.PostAsync("Email list for: Date " + date + " ::::::::::: From: " + from + " :::::::::::: Subject " + subject + " : ::::::::::::: Body : " + body + " Email.id eshte " + email.Id);
}
}
}
}
static String DecodeBase64String(string s)
{
var ts = s.Replace("-", "+");
ts = ts.Replace("_", "/");
var bc = Convert.FromBase64String(ts);
var tts = Encoding.UTF8.GetString(bc);
return tts;
}
static String GetNestedBodyParts(IList<MessagePart> part, string curr)
{
string str = curr;
if (part == null)
{
return str;
}
else
{
foreach (var parts in part)
{
if (parts.Parts == null)
{
if (parts.Body != null && parts.Body.Data != null)
{
var ts = DecodeBase64String(parts.Body.Data);
str += ts;
}
}
else
{
return GetNestedBodyParts(parts.Parts, str);
}
}
return str;
}
}
private static byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
result.Append(String.Empty.PadRight(padChars, '='));
result.Replace('-', '+');
result.Replace('_', '/');
return Convert.FromBase64String(result.ToString());
}
client_id.json
{"installed":{"client_id":"xxxxxxx- yyyyyy.apps.googleusercontent.com","project_id":"reademailbot","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"yyyyyyyyyyy","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
Edited:
I try to add the code below :
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new
ClientSecrets
{
ClientId = "xx-
xxxxxxxxx.apps.googleusercontent.com",
ClientSecret = "xxxxxxxxxxxxxxxxxxxxx-lLO"
},
new[] {
GmailService.Scope.GmailReadonly,
GmailService.Scope.MailGoogleCom,
GmailService.Scope.GmailMetadata
},
"user",
CancellationToken.None,
new
FileDataStore("Drive.Auth.Store")).Result;
var gmailService = new Google.Apis.Gmail.v1.GmailService(new
BaseClientService.Initializer()
{
HttpClientInitializer = credential,
});
But when i try on web i have still problem :
Error: redirect_uri_mismatch
The redirect URI in the request, http://127.0.0.1:52158/authorize/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/673194113721-45u2pgl6m2l74ecf13c51fmmihrsu3jh.apps.googleusercontent.com?project=673194113721
Edit 2 :
string[] Scopes = { GmailService.Scope.GmailReadonly };
string ApplicationName = "IkanbiBot";
var secrets = new ClientSecrets
{
ClientId = ConfigurationSettings.AppSettings["GMailClientId"],
ClientSecret = ConfigurationSettings.AppSettings["GMailClientSecret"]
};
var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse { RefreshToken = ConfigurationSettings.AppSettings["GmailRefreshToken"] };
var credential = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}), "xxxx#gmail.com", token);
var gmailService = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
log4net.ILog log2 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
await context.PostAsync("Aplication name is ..." + ApplicationName);
await context.PostAsync("secret name is ..." + secrets.ClientId + "_____ and .... " + secrets.ClientSecret + " ++++ token is " + token.RefreshToken);
var emailListRequest = gmailService.Users.Messages.List("xxxxx#gmail.com");
emailListRequest.LabelIds = "INBOX";
emailListRequest.MaxResults = 1;
emailListRequest.Q = "is:unread";
emailListRequest.IncludeSpamTrash = false;
// Get our emails
// Get our emails
var emailListResponse = emailListRequest.Execute();
//get our emails
log2.Info(emailListResponse.Messages);
await context.PostAsync("emailListResponse is ..." + emailListResponse.Messages.Count);
if (emailListResponse != null && emailListResponse.Messages != null)
{
//loop through each email and get what fields you want...
foreach (var email in emailListResponse.Messages)
{
var emailInfoRequest = gmailService.Users.Messages.Get("botikanbi#gmail.com", email.Id);
var emailInfoResponse = emailInfoRequest.Execute();
if (emailInfoResponse != null)
{
String from = "";
String date = "";
String subject = "";
String body = "";
//loop through the headers to get from,date,subject, body
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
if (mParts.Name == "Date")
{
date = mParts.Value;
}
else if (mParts.Name == "From")
{
from = mParts.Value;
}
else if (mParts.Name == "Subject")
{
subject = mParts.Value;
}
if (date != "" && from != "")
{
if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null)
body = DecodeBase64String(emailInfoResponse.Payload.Body.Data);
else
body = GetNestedBodyParts(emailInfoResponse.Payload.Parts, "");
}
}
await context.PostAsync("Email list for: Date " + date + " ::::::::::: From: " + from + " :::::::::::: Subject " + subject + " : ::::::::::::: Body : " + body + " Email.id eshte " + email.Id);
}
}
}
}
static String DecodeBase64String(string s)
{
var ts = s.Replace("-", "+");
ts = ts.Replace("_", "/");
var bc = Convert.FromBase64String(ts);
var tts = Encoding.UTF8.GetString(bc);
return tts;
}
static String GetNestedBodyParts(IList<MessagePart> part, string curr)
{
string str = curr;
if (part == null)
{
return str;
}
else
{
foreach (var parts in part)
{
if (parts.Parts == null)
{
if (parts.Body != null && parts.Body.Data != null)
{
var ts = DecodeBase64String(parts.Body.Data);
str += ts;
}
}
else
{
return GetNestedBodyParts(parts.Parts, str);
}
}
return str;
}
}
private static byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
result.Append(String.Empty.PadRight(padChars, '='));
result.Replace('-', '+');
result.Replace('_', '/');
return Convert.FromBase64String(result.ToString());
}
}
}
Now i'm using this code . I get answer from the bot till :
"secret name is ..." + secrets.ClientId + "_____ and .... " + secrets.ClientSecret + " ++++ token is " + token.RefreshToken
But stop when try to read email :(
Can you help me please what is going on ?
There are sevral ways to authcate to google.
moble
web
sevice account
native applications.
The client you create for each of the above authentication types is different. The code to use them is also different.
GoogleWebAuthorizationBroker.AuthorizeAsync is used to authenticate installed applications. Its wont work with a web application.
For a web application you should be following Web applications (ASP.NET MVC) and using GoogleAuthorizationCodeFlow
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "PUT_CLIENT_ID_HERE",
ClientSecret = "PUT_CLIENT_SECRET_HERE"
},
Scopes = new[] { GmailService.Scope.GmailReadonly },
DataStore = new FileDataStore(this.GetType().ToString()
});
redirect_uri_mismatch
In order to use the api your client must be set up corectly. In google developer console you simply need to add the proper redirect uri in the settings on your client and it will work. It must match exactly http://127.0.0.1:52158/authorize/ make sure that visual studio isnt creating random port numbers on you.

Linkedin api post not work?

public ActionResult AuthorizeLinkedin(string code, string state, string error, string error_description)
{
//Linkedin
if (!string.IsNullOrEmpty(error) || !string.IsNullOrEmpty(error_description))
{
// handle error and error_description
}
else
{
objusermodel = new UserModel();
var host = ExtractHost();
var _redirectUrl = Url.Action("AuthorizeLinkedin", "Investments", null, Request.Url.Scheme, host);
var userToken = api.OAuth2.GetAccessToken(code, _redirectUrl);
// keep this token for your API requests
var user = new UserAuthorization(userToken.AccessToken);
var fields = FieldSelector.For().WithFirstName().WithFollowing();
if (Session["ShareResponse"] != null)
{
shareResponse = Session.GetObjectFromJson("ShareResponse");
}
//try
//{
var profile = api.Profiles.GetMyProfile(user, new string[] { "en-US" }, fields);
api.Social.Post(user, new PostShare()
{
Content = new PostShareContent()
{
Title = "FUNDING PORTAL",
Description = shareResponse.Message,
SubmittedUrl = shareResponse.ShareUrl,
SubmittedImageUrl = shareResponse.ImageUrl,
},
Visibility = new Visibility()
{
Code = "anyone"
},
});
shareResponse.Success = 1;
shareResponse.flag = true;
Session.SetObjectAsJson("ShareResponse", shareResponse);
TempData["PromoboxFN"] = shareResponse.ImageUrl;
TempData.Keep("PromoboxFN");
return Redirect(shareResponse.RedirectUrl);
//}
//catch (Exception ex)
//{
// throw;
// shareResponse.Success = 0;
// shareResponse.flag = true;
// Session.SetObjectAsJson("ShareResponse", shareResponse);
// return Redirect(shareResponse.RedirectUrl);
//}
}
return null;
}
Give the error:
"api.Social.Post(user, new PostShare()" to this point An exception of
type 'Sparkle.LinkedInNET.LinkedInApiException' occurred in
Sparkle.LinkedInNET.dll but was not handled in user code
Additional information: API error (500) Internal service error at https://api.linkedin.com/v1/people/~/shares

Remove the twitter authorization during program running in C#

I am doing the tweets automatically from getting data from json url. But during the program execution after some seconds twitter always require to press the authorization button and then the program will continue. But now i want to place more than 10 urls in my program and it will create the heavy problem to press the authorization button all the time. Please help me in this regard to remove the authorization process every time. Below is the coding of the twitter by twitterizer.
[enter image description here][1]
public void twitter_function()
{
string x;
var list2 = (List<string>)Session["title"];
if (list2 == null)
{
x = "No new Products Found";
}
else
{
x = string.Join(",", list2);
// x= list2[0];
}
//foreach (string x in list2)
//{
// Your code
var oauth_consumer_key = "[REDACTED]";
var oauth_consumer_secret = "[REDACTED]";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
//TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
// accesstoken,
// "Testing!! It works (hopefully).");
Twitterizer.TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken, x, new StatusUpdateOptions() { UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/" });
if (response.Result == RequestResult.Success)
{
Response.Redirect("https://twitter.com/");
}
else
{
Response.Redirect("https://twitter.com/");
}
}
}
It is the coding for tweets and it requires "Authorize app" button every time. I want to remove it from program and want to run my program without any interruption. Thanks

Postmark SendMessageAsync Message not sending Email c#

Here is my Code snippet to send email using postmark
public async Task<bool> SendEmail(CustomMailMessage mailMessage)
{
HeaderCollection headers = new HeaderCollection();
if (mailMessage.Headers != null)
{
var items = mailMessage.Headers.AllKeys.SelectMany(mailMessage.Headers.GetValues, (k, v) => new { key = k, value = v });
foreach (var item in items)
{
headers.Add(item.key, item.value);
}
}
var message = new PostmarkDotNet.PostmarkMessage()
{
To = mailMessage.To,
Cc = mailMessage.Cc,
Bcc = mailMessage.Bcc,
From = mailMessage.FromName + "<" + mailMessage.From + ">",
TrackOpens = true,
Subject = mailMessage.Subject,
TextBody = mailMessage.Body,
HtmlBody = mailMessage.HtmlBody,
Headers = headers,
};
if (mailMessage.AttachmentsPath != null)
{
foreach (string file in mailMessage.AttachmentsPath)
{
var imageContent = File.ReadAllBytes(file);
message.AddAttachment(imageContent, Path.GetFileName(file), MimeMapping.GetMimeMapping(file), null);
}
}
var client = new PostmarkClient(ConfigurationSettings.AppSettings["postmarkServerToken"].ToString(), "https://api.postmarkapp.com", 30);
var sendResult = await client.SendMessageAsync(message);
if (sendResult.Status== PostmarkStatus.Success)
{
return true;
}
else
{
return false;
}
}
When I try to send email "var sendResult = await client.SendMessageAsync(message);" didn't get any response when hitting this line, and when send mail again got message "The transaction has aborted."
Please Help

Controller is returning blank View in my website

public async Task<IActionResult> Contact1()
{
if (Convert.ToBoolean(HttpContext.Session.GetString("login")))
{
var pass = new ContactViewModel();
var username = HttpContext.Session.GetString("username");
Program.readname(HttpContext.Session.GetString("username"));
var names = HttpContext.Session.GetString("studentnames");
var obj1 = JsonConvert.DeserializeObject<Program.Data>(names);
if (Program.datecheck(username, DateTime.Today.Date))
{
try{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
}
catch(Exception ee)
{ ViewBag.m6 = ee.Message; ViewBag.attendance = "Attendace is not take yet";}
}
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
pass.studentname = obj1.studentname1;
pass.studentrollno = obj1.studentrollno1;
pass.date = DateTime.Today.Date;
HttpContext.Session.SetInt32("classselect", 1);
ViewData["Message"] = "Student Attendance of Class: " + HttpContext.Session.GetString("classname1");
ViewBag.Login = HttpContext.Session.GetString("login");
ViewBag.name = HttpContext.Session.GetString("name");
ViewBag.classname1 = HttpContext.Session.GetString("classname1");
ViewBag.classname2 = HttpContext.Session.GetString("classname2");
ViewBag.classname3 = HttpContext.Session.GetString("classname3");
ViewBag.classname4 = HttpContext.Session.GetString("classname4");
return View("/Views/Home/Contact.cshtml", pass);
}
else
{
ViewData["Message"] = "Please Login First!!";
return View("/Views/Home/Login.cshtml");
}
}
The above code is runnig well in my local ISS server but when i run this on bluemix then i am getting blank page. I tried to find out the problem and get to the conclusion that if the control does not enter in the if part of that code:
if (Program.datecheck(username, DateTime.Today.Date))
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
then it will run fine.I am unable to find what is wrong in that query.

Categories

Resources