ASP.NET Why is this shortening url code redirecting to page - asp.net

Hey I have the following method
public static string GetShortenedURL(String inURL)
{
String shortURL = "";
String queryURL = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" + inURL + "&login=&apiKey=";
HttpWebRequest request = WebRequest.Create(queryURL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string jsonResults = reader.ReadToEnd();
int indexOfBefore = jsonResults.IndexOf("shortUrl\": \"") + 12;
int indexOfAfter = jsonResults.IndexOf("\"", indexOfBefore);
shortURL = jsonResults.Substring(indexOfBefore, indexOfAfter - indexOfBefore);
}
return shortURL;
}
Which worked fine on my development machine, but on live server for some reason whenever I call this method I actually seems to visit the URL aswell. The reason why this is a problem is because that URL updates a status of a record. But I only want to do this when the user clicks on the link in the mail but for some very weird reason when Im creating the email on my confirmation page of registration and call this shortened URL method so I can add the short URL in my mail to send out,
it seems to visit it by itself. Hence updating my status when it shouldnt yet.
Any Ideas ?
EDIT : This is how i call it
emailBody.Append(M1Utils.GetShortenedURL(ConfigurationSettings.AppSettings["strSite_FEURL"].ToString() + "login/verify.aspx?" + strEncrypted)).Append("\r\n\r\n");

Related

OneDrive for Business :"invalid_request","error_description":"AADSTS90014: The request body must contain the following parameter: 'grant_type

I'm trying to integrate the OneDrive for Busines to a Web Form App.
For this I use the documentation given at this url
In web Form App I have two Pages:
First one is Login page which have a button for login
On login button click I create a GET Request to OneDrive for Business API using the following code:
HttpClient client = new HttpClient();
Redirecturi = Uri.EscapeDataString(Redirecturi);
string url = string.Format("https://login.windows.net/common/oauth2/authorize?response_type=code&client_id={0}&redirect_uri={1}", ClienId, Redirecturi);
var response = client.GetAsync(url);
var json = response.Result.Content.ReadAsStringAsync();
Label2.Text = json.Result;
When I click the login button it takes me to micorosoft login service and sends me back to callback.aspx page with access code (Redirect URI configured on azure)
I got the access code.
On the second page I redeem the access code and make a POST request to get the Authentication token.
Here is the code for the second page:
private string BaseUri="https://login.windows.net/common/oauth2/token";
public string Redirecturi = "http://localhost:51642/CallBack.aspx";
public string ResourcesId = "https://api.office.com/discovery/";
private string ClienId = "180c6ac4-5829-468e-.....-822405804862"; ///truncated//azure
private string ClientSecert = "G4TAQzD8d7C4...OE6m366afv8XKbTCcyXr4=";//truncated
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString[OAuthConstants.AccessToken]))
{
// There is a token available already. It should be the token flow. Ignore it.
return;
}
if (!string.IsNullOrEmpty(Request.QueryString[OAuthConstants.Code]))
{
string _accessCode = Request.QueryString[OAuthConstants.Code];
HttpClient client = new HttpClient();
// BaseUri = Uri.EscapeDataString(BaseUri);
Redirecturi = Uri.EscapeDataString(Redirecturi);
ResourcesId = Uri.EscapeDataString(ResourcesId);
string url = string.Format("{0}?client_id={1}&redirect_uri={2}&grant_type=authorization_code&client_secret={3}&code={4}&grant_type=authorization_code&resource={5}", BaseUri, ClienId, Redirecturi, ClientSecert, _accessCode, ResourcesId);
var response = client.PostAsync(url, null);
var json = response.Result.Content.ReadAsStringAsync();
Response.Write(json);
}
}
But instead of Response I am get the following error. Which say include the grant_type in url. I have already added (you can check in code).
I get same error the same error without including it.
Here is the error
{"error":"invalid_request","error_description":"AADSTS90014: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 2adb3a7f-ceb1-4978-97c4-3dc2d3cc3ad4\r\nCorrelation ID: 29fb11a0-c602-4891-9299-b0b538d75b5f\r\nTimestamp: 2015-07-15 09:58:42Z","error_codes":[90014],"timestamp":"2015-07-15 09:58:42Z","trace_id":"2adb3a7f-ceb1-4978-97c4-3dc2d3cc3ad4","correlation_id":"29fb11a0-c602-4891-9299-b0b538d75b5f","submit_url":null,"context":null}
Please help to know where or what is getting wrong.
Any kind of help will be appreciable
You're adding the parameters to the request querystring. You have to post the data in the request body.
var content = new StringContent(
"grant_type=authorization_code" +
"&client_id=" + ClienId +
"&redirect_uri=" + Redirecturi +
"&client_secret=" + ClientSecert +
"&code=" + _accessCode +
"&resource=" + ResourcesId,
Encoding.UTF8,
"application/x-www-form-urlencoded");
var response = httpClient.PostAsync(BaseUri, content);
var result = response.Result.Content.ReadAsStringAsync();
use FormUrlEncodedContent instead of StringContent (form data post)
var formContent = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "code", authCode },
{ "redirect_uri", redirectUri },
{ "grant_type", "authorization_code" }
});
var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/token", formContent);
Sharing for future readers because this error is not specific to OneDrive only but can arise in other Microsoft tools
I was getting this error when working with Microsoft Bot Framework's Skype bot. In my case the bot file the appId and appSecret was wrongly set to clientId and clientSecret
Changing the same to appId and appSecret fixed the issue.

Facebook notification post data asp.net

I created a facebook app. A small game in asp.net mvc. It is a real time turn based game and i want the first player to choose his opponent, send him a facebook notification and go to the page of tthe game.
The second player then clicks on this notification and also go the the page of the game.
My problem is about the href parameter of the post data.
In asp.net i create a webhttprequest object. But my data i have to post is like that :
But when second player click on notification the last two parameters are lost. I think it is because symbol & is used with facebook graph address and with my address. How can i write the correct postdata with all the parameters ??
Here is my code :
public string sendnotificationtoplay(string monid, string prenomMoi, string codetokenjeu)
{
try
{
// variables to store parameter values
string url = "https://graph.facebook.com/" + monid + "/notifications";
string autrePrenom = "#[" + monid + "]";
string texte = "#[" + monid + "] ! " + prenomMoi + " wants to play with you ! \n Click here !";
// creates the post data for the POST request
string postData = ("access_token=MYACCESSTOKEN&template=" + texte + "&href=mywebsite.org/Index?ordredemandejeugame=2&codejeuadeux=ds&prenom1=dfdf&prenom2=fdgdfg");
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// POST the data
using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter2.Write(postData);
}
// This actually does the request and gets the response back
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// dumps the HTML from the response into a string variable
responseData = responseReader.ReadToEnd();
}
return responseData;`
please help me :)
Thank you in advance !

Getting Facebook Page Feed ( using graph api ) in asp.net, receiving error "Unsupported Browser"

I am trying to get facebook page feed ( public posts) which does not require any access token.
here's the url
https://www.facebook.com/feeds/page.php?format=json&id=1393547494231876
when i run this in browser where id= any facebook page id. it returns first 25 public posts in json format.
but when i run this in my code to get json result facebook return a page saying "unsupported browser"
this is my method . i pass it facebook page id to get posts..
public static String GetPosts(string PageId)
{
string id = PageId;
string apilink = "https://www.facebook.com/feeds/page.php?format=json&id=";
HttpWebRequest request = WebRequest.Create(apilink + id) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
String result = reader.ReadToEnd();
return result;
}
}
Here's the result that i get in return string
Result Image String
and so on remaining page returned.
Can somebody help me how to get it working??
Update
Found Answer...
I Have To Set User agent to make Facebook think i am a browser..
so just added
request.UserAgent = ".NET Framework";
and i worked.
Thanks to All.
Found Answer... I Have To Set User agent to make Facebook think i am a browser.. so just added request.UserAgent = ".NET Framework"; and i worked. Thanks to All.

Post comment to facebook wall using asp.net

I have a website that I have registered as a facebook app - I now have an app ID.
My website is ASP.net C#. When the user clicks a button I'd like it to post a pre-defined message to their wall. I'm expecting Facebook to present a login dialog to the user - they login and grant publish permission to for my website app.
Does anyone have any sample code that would do this? I think I need to use the graph API but all the examples I've seen use PHP - which I know nothing about. I'm looking for an example that would use Java Script (of which I know almost nothing) or C# (beautiful!).
* Update *
I have managed to get the access_token. Now I make a call through the Facebook C# API to post to the wall. I get the error message:
(#803) Some of the aliases you requested do not exist: profile_id
I've stepped through the api code and found that it is trying to post to the following address: {https://graph.facebook.com/PROFILE_ID/feed}, the post data is: message=Sample+message+from+c%23+sdk&access_token=199209316768200|2.1avFTZuDGR4HJ7jPFeaO3Q__.3600.1302897600.1-100000242760733|R4DkNDf4JCb6B2F64n5TSQwBqvM
I'm pretty sure my token should be valid. Prior to requesting access token I requested publish_stream on the app authorization request as follows:
Response.Redirect ("https://www.facebook.com/dialog/oauth?client_id=" + myAppId + "&redirect_uri=" + myURL + "&scope=publish_stream");
The sdk code that actually makes the request is as follows:
private string MakeRequest(Uri url, HttpVerb httpVerb,
Dictionary<string, string> args)
{
if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
{
url = new Uri(url.ToString() + EncodeDictionary(args, true));
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = httpVerb.ToString();
if (httpVerb == HttpVerb.POST)
{
string postData = EncodeDictionary(args, false);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
}
try
{
using (HttpWebResponse response
= request.GetResponse() as HttpWebResponse)
{
StreamReader reader
= new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Can anyone see what I'm doing wrong?
Many thanks,
Rob.
First of all, you need to take care of Authentication. You need to create an Application, and use OAuth to get hold of the access token. It's all described in the Authentication guide.
To post something to the user's wall, take a look at the Graph API under Publishing.
As a start, you could use Facebook's C# SDK
You could look to use a .NET library like http://facebooknet.codeplex.com/ to do this. There are a couple out there, I just remembered this one...
HTH.
I created a video showing how to do this using OG: http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
In case you don't have time to watch the video, here is the full code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace FBO
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "374961455917802";
string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
string scope = "publish_stream,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
}
}
}
}
I am using this http://facebooksdk.codeplex.com/ . I am using the latest stable release, easy to use. To comment, just post with /OBJECT_ID/comments for more, refer http://developers.facebook.com/docs/reference/api/#publishing and http://developers.facebook.com/docs/reference/api/post/
How about trying this API tha I recently developed to make integrating with Facebook easier.
Here is a code sample for you there's more documentation on the site.
Authenticating Users
Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[application_id]","applicaiton_secret")
'Redirects user to facebooks
SI.AuthenticateUser("http://[my url]", New SessionInfo.PermissionsEnum(){SessionInfo.PermissionsEnum.email, SessionInfo.PermissionsEnum.read_stream}))
'Called when the user is returned to your page
Dim FSR = FS.ReadFacebooAuthResponse
Response.Write(FSR.Access_Token)
Response.Write(FSR.UserID)
Making Posts
Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[access_token]"))
Dim Posts = New Functions.Posts(SI)
Dim P As New Post
P.name = "name of post"
P.message = "message"
P.link = "www.cnn.com"
P.caption = "my caption"
Posts.PublishCreate("[object ID to post to]", P)
Dim PostID = P.id
Getting stuff from the graph.
Dim SI As New SessionInfo("[access_token]"))
Dim Req New Functions.Requests(SI)
Dim User = Req.GetUserInfo("[optional user ID]")
Response.Write(U.name)

How to submit a form automatically using HttpWebResponse

I am looking for an application that can do the following
a) Programmatically auto login to a page(login.asxp) using HttpWebResponse by using already specified username and password.
b) Detect the redirect URL if the login is successful.
c) Submit another form (settings.aspx) to update certain fields in the database.
The required coding needs to be using asp.net
The application needs to complete this entire process in the same session cookie.
string sUrl = "login.aspx";
HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(sUrl);
CookieContainer oMyCookies = new CookieContainer();
oRequest.CookieContainer = oMyCookies;
// encode postdata into byte array. the postdata string format will most likely be different and you'll have to examine the postdata going back and forth using some firefox addon like LiveHTTPHeaders
byte[] oPostData = System.Encoding.UTF8.GetBytes("username=" + HttpUtility.UrlEncode(sUser) + "&pass=" HttpUtility.UrlEncode(sPass));
using (Stream oStream = oRequest.GetRequestStream())
{
oStream.Write(oPostData, 0, oPostData.Length);
}
HttpWebResponse oResponse = oRequest.GetResponse();
// save response cookies in our cookie object for future sessions!
foreach (Cookie oCookie in oResponse.Cookies)
{
oMyCookies.SetCookies(sUrl, oCookie.ToString());
}
// maybe check response headers for location
string sResponseContents = null;
using (StreamReader oReader = new StreamReader(oResponse.GetResponseStream())
{
// store server response into string
sResponseContents = oReader.ReadToEnd();
}
...this is the basic code required for what you want to do.

Resources