How can i get Equivalent method of HttpwebRequest in javascript - c#

As we all know HttpwebRequest loads another page behind the scenes without redirecting the client to the other page.
How can I get this functionality using Javascript/Jquery?
$(document).ready(function () {
debugger;
var ip = '<%= Request.UserHostAddress%>';
var location = window.location.href;
var Browser = BrowserDetect.browser;
var Version = BrowserDetect.version;
var Os = BrowserDetect.OS;
var SendItems = 'Ip=' + ip + '&location=' + location + '&Browser=' + Browser + '&Version=' + Version + '&Os=' + Os;
var HttpWebReq = ?
I want to pass these values as a query string to the other page :S

A cross domain example by using yql,
var url = 'xyz.com'; // website you want to scrape
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=json&callback=?';
$.getJSON(yql,function(data){
if (data.results[0]){
console.log(data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')); // The scraped data (the whole webpage)
}
});

As Corbin commented - you are looking for AJAX tutorial.
Since you've tagged with JQuery starting from JQuery.ajax is a good idea.
Also check out other related questions like - How to get page content using Javascript or JQuery

Related

SharePointContextFilter attribute fails to rebuild SharePoint context

I have developed a SharePoint add-in (SharePoint Online) and it is hosted in Azure. The add-in is an ASP.NET MVC application.
Here's the situation:
/Home/Index: The user starts on the landing page of the application and goes to the section Actions.
Actions/Index: On this page, the user has to select a few parameters and select an action to edit
Actions/Edit/123: The edit page opens, a form is shown with all controls filled in with the information about the action.
POST: After changing some fields, or none, the user clicks the Save button.
I didn't show it in the list but all the URLs have the SPHostUrl, SPAppWebUrl, SPLanguage, SPClientTag & SPProductNumber parameters.
This all works fine, except when the user doesn't interact with the application/page for a number of minutes and then presses the Save button. When the button is pressed, the application fails to pass the SharePointContextFilter attribute. The SharePointContext doesn't "exist" anymore. Following line returns null:
SharePointContext spContext = LoadSharePointContext(httpContext);
Normally, if it doesn't exist or isn't valid, the code will try and create it based based on the request. In the CreateSharePointContext method, the contextTokenString is always null:
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
This is the code of the method:
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
So, if this fails, the creation and saving of the context fails and the app returns the default error page.
This is the jQuery code that makes the call to the controller:
var request = $.ajax({
url: '#Url.Action("Edit", "Actions")' + window.buildSpAppParameters(),
data: $("#updateForm").serialize(),
cache: false,
type: "POST"
});
Here's the code of the buildSpAppParameters function:
function buildSpAppParameters() {
var spHostUrl = getQueryStringParameter("SPHostUrl");
var appWebUrl = getQueryStringParameter("SPAppWebUrl");
var spLanguage = getQueryStringParameter("SPLanguage");
var spClientTag = getQueryStringParameter("SPClientTag");
var spProductNr = getQueryStringParameter("SPProductNumber");
return "?SPHostUrl=" + spHostUrl +
"&SPAppWebUrl=" + appWebUrl +
"&SPLanguage=" + spLanguage +
"&SPClientTag=" + spClientTag +
"&SPProductNumber=" + spProductNr;
}
Why does this initially work, but if the user waits a period of time, the code is unable to get/create the context again? Is there something I am missing and how can solve this?
Note: I am aware of following question: Sharepoint 2013 MVC 5 provider-hosted app. Fails to authenticate on HttpPost using [SharePointContextFilter] and while there is useful information to read, it didn't help me further.
This all works fine, except when the user doesn't interact with the application/page for a number of minutes
The session is expired and the SharePointContext is lost. So we need to regenerate the context.
According to the GetContextTokenFromRequest method, the context token should be passed in query string or forms. But from the buildSpAppParameters method, we can't found the context token is passed from the query string. The query string parameter should be named AppContext or AppContextToken or AccessToken or SPAppToken.
To solve this issue, you could check whether your current URL in your brower contains a query parameter named AppContext or AppContextToken or AccessToken or SPAppToken. If yes, you could read the value this parameter out from URL and pass it server in your buildSpAppParameters method. For example, if your URL contains a query parameter named AppContextToken, you could modify your code as following.
function buildSpAppParameters() {
var spHostUrl = getQueryStringParameter("SPHostUrl");
var appWebUrl = getQueryStringParameter("SPAppWebUrl");
var spLanguage = getQueryStringParameter("SPLanguage");
var spClientTag = getQueryStringParameter("SPClientTag");
var spProductNr = getQueryStringParameter("SPProductNumber");
var appContextToken = getQueryStringParameter("AppContextToken");
return "?SPHostUrl=" + spHostUrl +
"&SPAppWebUrl=" + appWebUrl +
"&SPLanguage=" + spLanguage +
"&SPClientTag=" + spClientTag +
"&SPProductNumber=" + spProductNr +
"&AppContextToken=" + appContextToken;
}
If your URL doesn't contain such query parameters, you need to modify your code to store the context token in cookie when the context token was got at the first time.
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (!string.IsNullOrEmpty(contextTokenString))
{
HttpCookie cookie = new HttpCookie("AppContextToken", contextTokenString);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
After that, the context token can be got from the cookie if the token haven't been passed through query string.
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
if (request.Cookies["AppContextToken"] != null)
{
return request.Cookies["AppContextToken"].Value;
}
return null;
}

facebook application redirects to redirect_uri location

Let me put my code first
string strSigned = Request.Params["signed_request"];
// JSONObject obj = JSONObject.CreateFromString(strSigned);
Facebook.FacebookSignedRequest fb = FacebookSignedRequest.Parse(AppSecret, strSigned);
JsonObject jsonObj = fb.Data as JsonObject;
if (!jsonObj.ContainsKey("user_id"))
{
string appId = App_Id;
string redirectUrl = "http://127.0.0.1/Default.aspx"
string redirectstr = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + redirectUrl + "&scope=email,read_stream";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect", "<script>top.location.href='" +redirectstr +"'</script>");
Response.Clear();
}
else
{
Response.Write(jsonObj["user_id"].ToString());
}
Above code runs perfectly untill user press allow permissions.the application is actually redirecting to the mentioned redirect_uri http:... and not staying within facebook.
i am really bugged with this.let me know the solution.
It is made this way so that it can be used by external sites which accept facebook login.
The redirect_uri can be set to:
apps.facebook.com/myapp/
or
www.facebook.com/pageurl?sk=app_YOUR_APP_ID
along with external site url.

how to solve 403 error in google analytics api call

I'm using the code in the following post:
Google Analytics API - Programmatically fetch page views in server side
but getting a 403 forbidden error on the highlighted line below. I don't think it's a credential issue, becuase my credentials are correct, as I have checked and double checked, and also I log in to the analytics account with these credentials. So maybe it is somekind of folder permissions issue ?
//-------------- Get Auth Token -------------------
WebClient webClient = new WebClient();
NameValueCollection data = new NameValueCollection();
data.Add("accountType", "GOOGLE");
data.Add("Email", "xxxx#gmail.com");
data.Add("Passwd", "xxxx");//Passwd, not a misspell.
data.Add("service", "analytics");
data.Add("source", "xxxx-xxxx-xx");//Could be anything.
byte[] bytes = webClient.UploadValues("https://www.google.com/accounts/ClientLogin", "POST", data);
string tokens = Encoding.UTF8.GetString(bytes);
string authToken = extractAuthToken(tokens);
//-------------- Get page views -------------------
string feed = "https://www.google.com/analytics/feeds/data";
//Required:
string ids = "ga:xxxx";
string metrics = "ga:pageviews";
string startDate = "2011-06-25";
string endDate = "2011-07-25";
//Optional:
string dimensions = "ga:pagePath";
string sort = "-ga:pageviews";
string feedUrl = string.Format("{0}?ids={1}&dimensions={2}&metrics={3}&sort={4}&start-date={5}&end-date={6}",
feed, ids, dimensions, metrics, sort, startDate, endDate);
webClient.Headers.Add("Authorization", "GoogleLogin " + authToken);
// This is the line I get the 403 error on:
**string result = webClient.DownloadString(feedUrl);**
//-------------- Extract data from xml -------------------
XDocument xml = XDocument.Parse(result);
var ns1 = "{http://www.w3.org/2005/Atom}";
var ns2 = "{http://schemas.google.com/analytics/2009}";
var q = from entry in xml.Descendants()
where entry.Name == ns1 + "entry"
select new
{
PagePath = entry.Element(ns2 + "dimension").Attribute("value").Value,
Views = entry.Element(ns2 + "metric").Attribute("value").Value
};
//-------------- Do something with data -------------------
foreach (var page in q)
{
Debug.WriteLine(page.PagePath + " " + page.Views);
}
//-------------- Help Method -------------------
private string extractAuthToken(string data)
{
var tokens = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
return tokens.Where(token => token.StartsWith("Auth=")).Single();
}
If you call the Google Analytics API too frequently, you could get 403 Forbidden errors. From that link:
General Analytics API quotas. These apply to both the Analytics APIs, i.e., Management API and Core Reporting API:
- 50,000 requests per project per day
- 10 queries per second (QPS) per IP
I've seen 403 errors returned from the AdWords API when my applications have made too many consecutive calls, so that potentially could be the cause of your problem.
EDIT
If you're not able to make any calls at all, then review the steps listed here under "Before You Begin". According to the documentation, you'll need to register your application through the Google API console before you can use the API.

Google Analytics API - Programmatically fetch page views in server side

We have a web application that consists of several pages. We registered our web app domain to Google Analytics and page views tracking works as expected (In the Analytics panel we can see page views for each page). Now we want this page views info to be stored in the back-end inside our DB. So we want to create a back-end process that will run once each day, and fetch the page views from Analytics API.
This is of course need to be done in code. From initial research it seems that in order to access Analytics API an authentication process must take place, meaning a human user must type in an id and password.
The question is, can it be done with code only ?
//-------------- Get Auth Token -------------------
WebClient webClient = new WebClient();
NameValueCollection data = new NameValueCollection();
data.Add("accountType", "GOOGLE");
data.Add("Email", "xxxx#gmail.com");
data.Add("Passwd", "xxxx");//Passwd, not a misspell.
data.Add("service", "analytics");
data.Add("source", "xxxx-xxxx-xx");//Could be anything.
byte[] bytes = webClient.UploadValues("https://www.google.com/accounts/ClientLogin", "POST", data);
string tokens = Encoding.UTF8.GetString(bytes);
string authToken = extractAuthToken(tokens);
//-------------- Get page views -------------------
string feed = "https://www.google.com/analytics/feeds/data";
//Required:
string ids = "ga:xxxx";
string metrics = "ga:pageviews";
string startDate = "2011-06-25";
string endDate = "2011-07-25";
//Optional:
string dimensions = "ga:pagePath";
string sort = "-ga:pageviews";
string feedUrl = string.Format("{0}?ids={1}&dimensions={2}&metrics={3}&sort={4}&start-date={5}&end-date={6}",
feed, ids, dimensions, metrics, sort, startDate, endDate);
webClient.Headers.Add("Authorization", "GoogleLogin " + authToken);
string result = webClient.DownloadString(feedUrl);
//-------------- Extract data from xml -------------------
XDocument xml = XDocument.Parse(result);
var ns1 = "{http://www.w3.org/2005/Atom}";
var ns2 = "{http://schemas.google.com/analytics/2009}";
var q = from entry in xml.Descendants()
where entry.Name == ns1 + "entry"
select new
{
PagePath = entry.Element(ns2 + "dimension").Attribute("value").Value,
Views = entry.Element(ns2 + "metric").Attribute("value").Value
};
//-------------- Do something with data -------------------
foreach (var page in q)
{
Debug.WriteLine(page.PagePath + " " + page.Views);
}
//-------------- Help Method -------------------
private string extractAuthToken(string data)
{
var tokens = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
return tokens.Where(token => token.StartsWith("Auth=")).Single();
}

Fans-only content in facebook with asp.net C# sdk

Hi i'm developing an application in facebook with c# sdk and i want that the user whom liked my page can only use my application. (Like woobox)
I found some solutions in php in this link but there isn't any source about .net how can i get the liked info in ASP.NET
I find another examples in php in this link again but i can't find c# answer :\
Thanks
You get signed request when your web page is loaded within facebook canvas app; you should be able to parse signed request something similar to following:
if (Request.Params["signed_request"] != null)
{
string payload = Request.Params["signed_request"].Split('.')[1];
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var o = JObject.Parse(json);
var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");
var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");
var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");
}
You need to add reference to json libraries in order to parse signed requestin C#, download from http://json.codeplex.com/
Also refere to How to decode OAuth 2.0 for Canvas signed_request in C#? if you are worndering about signed request.
This is only possible with the legacy APIs, or with the user_likes permission. As you want a solution without specific permissions I'll show you 2 methods. Use them in combination with AJAX to refresh the page when a user presses like.
Option 1) REST API
Using the legacy API, it's possible to use Pages.IsFan
https://api.facebook.com/method/pages.isFan?
page_id=...&
uid=...&
access_token=...
Do this in C# as follows.
var appID = "....";
var appSecret = "....";
var uid = "....";
var pageId = "....";
WebClient client = new WebClient();
var appAuthUri = string.Concat("https://graph.facebook.com/oauth/access_token?",
"client_id=", appID,
"&client_secret=", appSecret,
"&grant_type=", "client_credentials"
);
var response = client.DownloadString(appAuthUri);
var access_token = response.Split('=')[1];
var isFanUri = string.Concat("https://api.facebook.com/method/pages.isFan?",
"format=", "json",
"&page_id=", pageId,
"&uid=", uid,
"&access_token=", access_token
);
response = client.DownloadString(isFanUri);
bool isFan;
bool.TryParse(response, out isFan);
Option 2) Client side
The FBXML method. This is done with Javascript on the client, by subscribing to an event when the user clicks the like button. It's documented here.
How do I know when a user clicks a Like button?
If you are using the XFBML version of the button, you can subscribe to
the 'edge.create' event through FB.Event.subscribe.
Generate an FBXML like button here.
<div id="fb-root"></div>
<script>(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js#appId=132240610207590&xfbml=1";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));</script>
<div class="fb-like" data-href="http://www.thecodeking.co.uk" data-send="true" data-width="450" data-show-faces="false"></div>
Then subscribe to the edge.create event using the Javascript SDK. Place this code in the document BODY preferably just before the end.
<script type="text/javascript">
<!--
window.fbAsyncInit = function () {
FB.init({ appId: '245693305442004', status: true, cookie: true, xfbml: true });
FB.Event.subscribe('edge.create',
function (href, widget) {
// Do something here
alert('User just liked '+href);
});
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
};
//-->
</script>
this.canvasAuthorizer = new CanvasAuthorizer {
Permissions = new[] { "user_about_me", "publish_stream", "offline_access", "user_likes", "friends_about_me" }
};
this.canvasAuthorizer.Authorize();
if (FacebookWebContext.Current.IsAuthorized())
{
this.facebookWebClient = new FacebookWebClient(FacebookWebContext.Current);
string requested_Data = HttpContext.Current.Request.Form["signed_request"];
dynamic decodedSignedRequest = FacebookSignedRequest.Parse(this.facebookApplication, requested_Data);
if (decodedSignedRequest.Data.page != null)
{
// Funs Page
this.IsLike = decodedSignedRequest.Data.page.liked;
}
else
{
// Application Page
dynamic likes = this.facebookWebClient.Get("/me/likes");
foreach (dynamic like in likes.data)
{
if (like.id == this.FacebookFanPageID)
{
this.IsLike = true;
}
}
}
}
If your app is a canvas app, you could (should?) use the signed_request parameter to check if the user likes the page it's on:
# pseudocode
signed_request = decode_signed_request()
if signed_request['page']['liked']:
# user liked page, do something cool
else:
# user doesn't like page. redirect somewhere to tell them why they should
The signed_request is passed to your page as a POST variable; just as if there was a form field named signed_request and the form was submitted on the page previous to yours (in fact this is basically how facebook "runs" your app; the form is auto-submitted instead of waiting for a user to submit it). So in ASP.net you should be able to get it through the Request object:
Request["signed_request"]
This approach is useful if you're creating a "tab app" for a page; you can detect whether the user liked the page without them granting you extra permissions.
This can be done in PHP with the help of an SQL Query
`$result = $facebook->api(array( "method" => "fql.query",
"query" => "SELECT uid FROM page_fan WHERE uid=$uid AND page_id=$page_id"
));
Here $result variable can be used for segregating the Fan and non-Fan content

Categories