Creating Facebook Application in asp.net - c#

I want to create a Facebook IFRAME applicaton with asp.net. I just want to know should I need to host the application some where over internet? If yes, how could I test my application on localhost?
Update:
I just want a simple app for displaying a user name with "Hello." Can anyone show me the code for that with the complete web.config configuration?
I'm trying this code
using facebook.web;
namespace TestFbApplication
{
public partial class _Default:facebook.web.CanvasFBMLBasePage
{
facebook.Components.FacebookService _fbService = new facebook.Components.FacebookService();
private const string FACEBOOK_APPKEY = "66a8278bb94d969247a80815bab686e5"; // From the Facebook application page
private const string FACEBOOK_SECRET = "de76280e4ddaef72ac2166afe7ffb9d5"; // From the Facebook application page
protected void Page_PreInit(object sender, EventArgs e)
{
base.RequireLogin = false;
_fbService.IsDesktopApplication = false;
_fbService.ApplicationKey = FACEBOOK_APPKEY;
_fbService.Secret = FACEBOOK_SECRET;
_fbService.IsDesktopApplication = false;
_fbService.ConnectToFacebook();
abc.InnerText = _fbService.users.getInfo().ToString();
}
and it is throwing and Exception in the last line that that the object reference is not set.

You will need to host your production application somewhere, but you can test locally. If you set your Canvas URL to http://localhost:81 in Facebook, this should work. It did for me a couple of months ago, but they may have changed it since then.

this might be an interesting for you:
http://www.stevetrefethen.com/blog/DevelopingFacebookapplicationsinCwithASPNET.aspx

Related

C# Method - Publish Entire Sitecore Site

I have an odd request. I am wondering if it is possible to have your C# solution file publish the entire Site from the master database to the web database. I am in my development environment and the amount of items in Sitecore is changing daily as I am working with multiple people. This is not something that is going to be used to Production Content Management or Content Delivery. Purely development.
Is it possible to trigger a full Site publish in C# just like pressing the publish button in the content editor? And what would the code look like?
/sitecore/shell/Applications/Publish.aspx
I assume this C# method would work with Sitecore.Publishing.PublishManager?
Thanks!
We also use that on our projects...
We have that placed in a regular .aspx page. I hope that helps:
protected void Page_Load(object sender, EventArgs e)
{
PublishMode publishMode = PublishMode.Full;
using (new Sitecore.SecurityModel.SecurityDisabler())
{
var webDb = Sitecore.Configuration.Factory.GetDatabase("web");
var masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
try
{
foreach (Language language in masterDb.Languages)
{
//loops on the languages and do a full republish on the whole sitecore content tree
var options = new PublishOptions(masterDb, webDb, publishMode, language, DateTime.Now) { RootItem = masterDb.Items["/sitecore"], RepublishAll = true, Deep = true };
var myPublisher = new Publisher(options);
myPublisher.Publish();
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("Could not publish", ex);
}
}
}

Open ID with Google and dotnetopenauth - Passing query string

I have some code that uses Google Apps as an Open ID provider to authenticate to my web application that is based on the example https://developers.google.com/google-apps/marketplace/tutorial_dotnet.
It all works as expected. However, when redirected to the Google Login screen, the 'Stay Signed In' checkbox is selected by default. I have found that if I manually add &rm=false to then end of the URL, the checkbox is unselected, which I believe is a more secure default option.
My question is, how can I pass &rm=false in my code. I've looked at AddCallbackArguments but this doesn't seem to be the way to do it.
Code is
private static readonly HostMetaDiscoveryService GoogleAppsDiscovery = new HostMetaDiscoveryService
{
UseGoogleHostedHostMeta = true,
};
private static readonly OpenIdRelyingParty relyingParty;
static login()
{
relyingParty = new OpenIdRelyingParty();
relyingParty.DiscoveryServices.Clear();
relyingParty.DiscoveryServices.Insert(0, GoogleAppsDiscovery);
}
protected void buLogin_Click(object sender, EventArgs e)
{
IAuthenticationRequest request = relyingParty.CreateRequest("mydomain");
request.RedirectToProvider();
}

Problems using captured access token to retrieve user's facebook information

I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx

Web Application Project - how to use ProfileCommon

I am porting a site I had developed on an old box across to a new dev env. I have not just copied all the files as I didn't have a great file structure and some parts of the code needed to be removed as I went along.
Originally I had created a website (File -> New -> Web Site). I wanted a file structure something like:
Popular folder structure for build
So I created a new blank solution so the sln file was on its own, then added projects (various DLL projects) and am ASP.NET Web Application.
This last part seems to have caused me a few issues, I am now getting the following error:
"The type or namespace name ' ProfileCommon' could not be found".
I found the following page:
http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx
It seems a bit long winded and I was hoping someone might know of a better solution.
I am trying to use the ProfileCommon with the CreateUser Wizard as I add a little extra information into it.
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
// Create an empty Profile for the newly created user
ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties off of the create user wizard
p.CurrentLevel = Int32.Parse(((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("clevel")).SelectedValue);
// Save profile - must be done since we explicitly created it
p.Save();
}
Web.config:
<profile enabled="true">
<properties>
<add name="CurrentLevel" type="Int32"/>
</properties>
</profile>
If there is another way to add this extra information into the creation wizard, or just a better way of setting extra info to a new user then I am all ears and would be very grateful.
Thanks for the help and advice.
This is a very late post, but I just ran into this same problem when porting a VB.NET Visual Studio 2008 (.NET 3.5) website over to C# Visual Studio 2010 (.NET 4.0) website.
I found references to ProfileCommon in MSDN's ProfileBase documentation, but nothing on how to get that object.
From your helpful MSDN link, I noticed that ProfileCommon would only ever be just a wrapper for the HttpContext.
In short, I used the var keyword to extract the ProfileCommon information from the HttpContext, as in:
var profile = HttpContext.Current.Profile;
Using this one bit of information, I was able to create the entire class for reading and writing the information for my website visitors.
Like you, I hope this code might help someone else:
using System.Web;
using System.Web.Security;
namespace WebApplication17 {
public partial class ManageProfile : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
if (User.Identity.IsAuthenticated) {
loadProfile();
} else {
goHome();
}
}
}
private void changePassword(string pwdOld, string pwdNew) {
MembershipUser user = Membership.GetUser(User.Identity.Name);
user.ChangePassword(pwdOld, pwdNew);
Membership.UpdateUser(user);
}
private void goHome() {
Server.Transfer("Default.aspx");
}
private void loadProfile() {
MembershipUser user = Membership.GetUser(User.Identity.Name);
txtEmail.Text = user.Email;
TextBox3.Text = user.GetPassword();
var profile = HttpContext.Current.Profile;
txtTitle.Text = profile.GetPropertyValue("Title").ToString();
txtName.Text = profile.GetPropertyValue("Name").ToString();
txtAddress.Text = profile.GetPropertyValue("Address").ToString();
txtCity.Text = profile.GetPropertyValue("City").ToString();
txtSt.Text = profile.GetPropertyValue("St").ToString();
txtZip.Text = profile.GetPropertyValue("Zip").ToString();
txtPhone.Text = profile.GetPropertyValue("Phone").ToString();
txtFax.Text = profile.GetPropertyValue("Fax").ToString();
txtCompany.Text = profile.GetPropertyValue("Company").ToString();
}
private void setProfile() {
MembershipUser user = Membership.GetUser(User.Identity.Name);
user.Email = txtEmail.Text;
Membership.UpdateUser(user);
var profile = HttpContext.Current.Profile;
profile.SetPropertyValue("Title", txtTitle.Text);
profile.SetPropertyValue("Name", txtName.Text);
profile.SetPropertyValue("Address", txtAddress.Text);
profile.SetPropertyValue("City", txtCity.Text);
profile.SetPropertyValue("St", txtSt.Text);
profile.SetPropertyValue("Zip", txtZip.Text);
profile.SetPropertyValue("Phone", txtPhone.Text);
profile.SetPropertyValue("Fax", txtFax.Text);
profile.SetPropertyValue("Company", txtCompany.Text);
profile.Save();
}
protected void Button6_Click(object sender, EventArgs e) {
changePassword(TextBox3.Text, TextBox4.Text);
goHome();
}
protected void Button11_Click(object sender, EventArgs e) {
setProfile();
goHome();
}
}
}
I found "a" solution to this one. Not sure if it is the best one or not but it worked for my situation. Minimal code changes required.
http://msdn.microsoft.com/en-us/library/aa983476.aspx
Hope it might help someone else, (or me when I forget it again).

When user hit's the site the custom error page is shown. Why? This is to few users and sporadic

Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.

Categories