Creating a Web Page in Google Sites through the GData API and the AtomEntry is always null - gdata

I'm using the same GDAta API code from https://code.google.com/p/gdata-samples/source/browse/trunk/sites/dotnet/SitesAPIDemo.cs to programatically create web pages in Google Sites in C#.
The problem I'm getting is when I create a Web Page the page is created successfully in the site but the returned object (newEntry) is always null so I can't create any child pages with the returned information.
SiteEntry entry = new SiteEntry();
AtomCategory category = new AtomCategory(SitesService.WEBPAGE_TERM, SitesService.KIND_SCHEME);
category.Label = "webpage";
entry.Categories.Add(category);
entry.Title.Text = title;
entry.Content.Type = "xhtml";
entry.Content.Content = html;
entry.ExtensionElements.Add(makePageNameExtension(pageName));
AtomEntry newEntry = null;
try
{
//the newEntry below is always returned as null
newEntry = service.Insert(new Uri(makeFeedUri("content")), entry);
}
catch (GDataRequestException e)
{
Console.WriteLine(e.ResponseString);
}
return newEntry;
Has anybody seen this problem before?
Thanks
Ryan

I've had to get into the source code of the SDK to fix this temporarily. This method seems to be the problem:
public TEntry Insert<TEntry>(Uri feedUri, TEntry entry) where TEntry : AtomEntry
{
return this.Insert(feedUri, entry, null) as TEntry;
}
I have changed this to return an AtomEntry rather than a TEntry and the object is no longer null:
public AtomEntry Insert<TEntry>(Uri feedUri, TEntry entry) where TEntry : AtomEntry
{
return this.Insert(feedUri, entry, null);
}

Related

How do I get Access Token for Facebook Graph API in C#?

I am trying to develop a demo Facebook App in C#. But I could not get Access Token (for both Application & User).
Please help me, How could I get this for both Application & User (Diff examples are welcome).
My Code is:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckIfFacebookAppIsSetupCorrectly();
var fbWebContext = FacebookWebContext.Current;
if (fbWebContext.IsAuthorized())
{
var fb = new FacebookWebClient(fbWebContext);
dynamic result = fb.Get("/me");
lblName.Text = "Hi " + result.name;
}
}
private void CheckIfFacebookAppIsSetupCorrectly()
{
bool isSetup = false;
var settings = ConfigurationManager.GetSection("facebookSettings");
if (settings != null)
{
var current = settings as IFacebookApplication;
if (current.AppId != "{app id}" &&
current.AppSecret != "{app secret}")
{
isSetup = true;
}
}
if (!isSetup)
{
System.Web.HttpContext.Current.Response.Redirect("~/GettingStarted.aspx");
}
}
}
Well When I check the code by putting the break points, I found that if (fbWebContext.IsAuthorized()) is always returns false, If I try to comment the Authorization I get the following Exception:
(OAuthException) An active access token must be used to query information about the current user.
Than I searched for this, I got following Link: Another Question Link
But When I got the Access Token for the App, I could not assign to the object as that is readonly.
What should I Do in this case, Also How do I get Access Token for Users?
Thanks
you need to create a new app and account at facebookDeveloperSite
you will get access token from there
Regards

Facebook profile picture doesnt show up, it shows an icon of a question mark

Do you have any idea? I am developing an app using Unity IDE and C#. Also, I'm using the social networking prime31 for my plugin with Facebook. I was able to get all the graphs and display it in my screen app, but since last week it didn't show the profile picture and my friend's picture, it just shows a plain question mark. Do you have any idea with regard to that?
But I was able to show the username and my friend's username. My app token is working, and I am using JSON data to get the data from the Facebook URL.
void Start()
{
getFB_ID();
}
void getFB_ID()
{
Facebook.instance.graphRequest( "me/", HTTPVerb.GET, ( error, obj ) =>
{
var ht = obj as Hashtable;
userId = ht["id"].ToString();
Debug.Log( "USER ID: " + userId);
string url = "http://graph.facebook.com/"+userId+"?fields=id,name,picture";
StartCoroutine(getURL(url));
});
}
IEnumerator getURL(string url)
{
WWW www = new WWW(url);
yield return www;
Debug.Log ("Heres the URL you are accessing: " + url);
ProfilePicDisplay(www.text);
public void ProfilePicDisplay(string jsonString)
{
JsonData jsonProfilePic = JsonMapper.ToObject(jsonString);
ConverterScript fbprofilepic;
MyPicture = new ArrayList();
{
fbprofilepic = new ConverterScript();
fbprofilepic.name = jsonProfilePic["name"].ToString();
fbprofilepic.picture = jsonProfilePic["picture"].ToString();
LoadProfilePic(fbprofilepic);
MyPicture.Add(fbprofilepic.name);
}
}
private void LoadProfilePic(ConverterScript profile)
{
string ProfilePic = "userAvatar";
GameObject profile_pic_holder = GameObject.Find(ProfilePic);
profile_pic_holder.SendMessage("LoadImage", profile);
}
was able to get the data in my logs, but the problem is it didnt load the image, it says:
You are trying to load data from a www stream which had the following error when downloading.
Could not resolve host: JsonData object (Domain name not found)
As of last week, October 3rd and detailed here: https://developers.facebook.com/blog/post/2012/10/03/platform-updates--operation-developer-love/
The picture endpoint no longer returns the picture URL in the string. It returns a dictionary and you have to change your parsing to get to it. So the data returned will look more like this:
{
"id": "1234567",
"name": "Your Name",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn1/your_picture.jpg",
"is_silhouette": false
}
}
}
In the latest LeanLoader, there is an automatic fix for the newly implimented Facebook endpoint abernathy mentioned, which allows you to load the image directly (with all the parsing of the json and other data handled by the engine). You can easily load profile images like this:
function Start () {
LeanLoader.load("https://graph.facebook.com/DentedPixel/picture?type=large&redirect=false", LLOptions().setOnLoad(onImageLoaded));
}
private function onImageLoaded( tex:Texture2D ){
Debug.Log("Your image texture ready to use! :"+tex);
}
There is also many other features that I think people will find helpful with LeanLoader (including caching of images/text/sound and a built-in JSON parser).
try this- fb sdk version-9.1.0
FB.API ("/me/picture?type=large", HttpMethod.GET, DisplayProfilePic);// API call
void DisplayProfilePic(IGraphResult result)
{
Image profilePic;
if (result.Texture != null)
{
profilePic = image1; // diplaying image
profilePic.sprite = Sprite.Create(result.Texture, new Rect(0, 0, result.Texture.width, result.Texture.height), new Vector2());
}
}

Logic behind linkage of ExpandoObject() members and FB Graph API

Just started today some dev using Facebook SDK and i can't figure out the logic followed to link the members of the expando object to the fields in the Graph API objects in the example bellow that was taken from facebook C# SDK docs:
public ActionResult RestFacebookPage()
{
FacebookApp app = new FacebookApp();
dynamic parameters = new ExpandoObject();
parameters.page_ids = "85158793417";
parameters.method = "pages.getInfo";
parameters.fields = "name";
dynamic result = app.Api(parameters);
return View("FacebookPage", result);
}
I do understand the page_ids and fields, but not pages.getInfo. It would be great if someone could enlighten me here and tell me where in the documentation i can find a reference that leads me to this....
Thanks a lot!
Not sure I understand what you are asking but there is a pretty decent example about translating php to facebook-c#-sdk over on their project page. Then you can just look up the official facebook developer documentation directly.
If you were asking more off a "how is this implemented" type of question, the best way to do this in my opinion is to break at the line containing app.Api and from there just step through the code. In the Api method there is a check to see if the parameters dictionary contains a key "method". If there is, the sdk figures the call is bound for the old rest api, not the graph api. A few stack frames lower we find the code that makes the url:
protected virtual Uri GetUrl(string name, string path, IDictionary parameters)
{
Contract.Requires(!String.IsNullOrEmpty(name));
Contract.Ensures(Contract.Result() != default(Uri));
if (_domainMaps[name] == null)
{
throw new ArgumentException("Invalid url name.");
}
UriBuilder uri = new UriBuilder(_domainMaps[name]);
if (!String.IsNullOrEmpty(path))
{
if (path[0] == '/')
{
if (path.Length > 1)
{
path = path.Substring(1);
}
else
{
path = string.Empty;
}
}
if (!String.IsNullOrEmpty(path))
{
uri.Path = UriEncoder.EscapeDataString(path);
}
}
if (parameters != null)
{
uri.Query = parameters.ToJsonQueryString();
}
return uri.Uri;
}
You should probably step into this method yourself to see what the variables hold and it should make sense to you. The source is always the best documentation. Hope this helps.

How to get the complete request that calls my MVC2 controller?

Newbie question … sorry ;-)
I have to write and to integrate a new website in a complex web application.
My new (MVC2) website will be hosted on a separate server and only called when the user clicks on a link in the already existing, complex website.
Means I(!) define the URL which calls my(!) new website.
But “they” (the calling, already existing, complex web application/website) will add an attribute to the url. This attribute is the sessionID.
Ok, I think I understand already that this calls my (MVC2) controller.
But how can I get in my (MVC2) controller the “calling URL” (which include the added sessionID)?
Hopefully that someone understand what I ask ;-)
Thanks in advance!
I want just share my little parser - hopefully it helps someone. ;-)
Also requests like
(Request.Url.Query =) "?sessionID=12345678901234567890123456789012&argumentWithoutValue&x=1&y&z=3"
will be well parsed.
Here my code:
Hashtable attributes = new Hashtable();
string query = Request.Url.Query;
string[] arrPairs = query.Split('&'); // ...?x=1&y=2
if (arrPairs != null)
{
foreach(string s in arrPairs)
{
if (!String.IsNullOrEmpty(s))
{
string onePair = s.Replace("?", "").Replace("&", "");
if (onePair.Contains("="))
{
string[] arr = onePair.Split('=');
if (arr != null)
{
if (arr.Count() == 2)
{
attributes.Add(arr[0], arr[1]);
}
}
}
else
{
// onePair does not contain a pair!
attributes.Add(onePair, "");
}
}
}
You really should set your URL and Route to be more MVC-Like. The URL you are calling should be:
newapp/controller/action/sessionId
Then set your route up:
routes.MapRoute(
"sessionId",
"{controller}/{action}/{sessionId}",
new { controller = "controller", action = "action", sessionId = 0 });
Then in your controller:
public ActionResult Action(int sessionId)
{
}
In your controller you still have direct access to the Request object, so you can use Request.Url, etc.
Does that answer your question, or is it something else that you need?

ASP.NET MVC2 - Redirect to Url in overriden controller

I've created a ControllerBase class that overrides the Execute method of the default Controller class. I'm doing this to check the url and pull an associated page from our database. If the page isn't found, I want to redirect to a specific url ("invalid-page"). All is working except the redirect. I've tried to use Response.Redirect("invalid-page"), but it gives me a null reference error. Also tried requestContext.HttpContext.Response.Redirect("invalid-page"), but same error. I'm guessing it doesn't want to let you bypass the MVC process by using a response redirect. And since the override doesn't actually return an ActionResult, I can't just return a Redirect action. Anyone know how I could do a redirect here?
Here's my ControllerBase class:
public class ControllerBase : Controller
{
protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
ViewData.Model = new DynamicPage{ LeftColumnCss = "bg5"};
var friendlyUrl = (string)requestContext.RouteData.Values["friendlyUrl"];
if (friendlyUrl != null && !friendlyUrl.Equals("invalid-page"))
{
var page = PageService.FetchByFriendlyUrl(null, (int?)PageCategoryType.MomMavens, friendlyUrl);
if (page == null)
{
var archivedPage = PageArchiveService.FetchByFriendlyUrl(friendlyUrl);
if (archivedPage != null)
{
page = PageService.FetchById(archivedPage.PageID);
if (page != null)
{
requestContext.HttpContext.Response.Redirect(PageService.GetPageAbsoluteUrl(page));
}
}
}
if (page == null)
{
//This is where I need to figure out how to do a redirect //requestContext.HttpContext.Response.Redirect("invalid-page");
//base.Redirect("invalid-page");
Response.Redirect("contact-us");
return;
}
((DynamicPage)ViewData.Model).CurrentPage = page;
// Allow the page to override the left column class
if (!string.IsNullOrEmpty(page.LeftColumnCssClasses))
{
var classes = page.LeftColumnCssClasses.Split(';');
var index = SubSonic.Sugar.Numbers.Random(0, classes.Length);
if (index == classes.Length)
index--;
((DynamicPage)ViewData.Model).LeftColumnCss = classes[index];
}
}
base.Execute(requestContext);
}
}
EDIT:
Somehow I managed to fix it by changing the line:
if (friendlyUrl != null && !friendlyUrl.Equals("invalid-page"))
to...
if (!friendlyUrl.Equals("invalid-page"))
and then using requestContext.HttpContext.Response.Redirect("invalid-page"), even though that gave me an error before. Not sure why that made a difference. Somehow having pages with blank urls bypass all those checks caused a problem.
Have you tried a Server.Transfer()?
It seems like you could make a change to the RouteValueDictionary and it would work, but I can't remember if it's an readonly collection.
Managed to fix it by changing the if statement slightly. See edit in original post. Still not completely sure what was wrong.