I've my ASP.Net HTML 5 Application, Which have the image byte array in Session,
I'm using the Latest 5.X C# facebook SDK from CodePlex.
But when user is authorized and Coming back to my canvas page at that time I can't access my ASP.Net Session, its give me a null value.
Here is my Code.
CanvasAuthorizer _authorizer = new CanvasAuthorizer { Perms = "publish_stream,offline_access,manage_pages" };
if (!_authorizer.IsAuthorized())
{
_authorizer.HttpContext.Session["ImageByte"] = Session["ImageByte"];
// Go for Login,
_authorizer.HandleUnauthorizedRequest();
}
else
{
//After Login
//Here its give me a null instead of Byte Array(My Image Byte Array).
byte[] imageByte = (byte[])(_authorizer.HttpContext.Session["ImageByte"]);
var mediaObject = new FacebookMediaObject
{
FileName = "sample.png",
ContentType = "image/png"
};
mediaObject.SetValue(imageByte);
dynamic parameters = new ExpandoObject();
parameters.source = mediaObject;
parameters.uid = _authorizer.Session.UserId;
var fb = new FacebookClient(Facebook.FacebookContext.Current.AppId, Facebook.FacebookContext.Current.AppSecret);
parameters.access_token = _authorizer.Session.AccessToken;
string path = "/me/photos";
dynamic param = new ExpandoObject();
param.access_token = _authorizer.Session.AccessToken;
param.uid = _authorizer.Session.UserId;
param.source = mediaObject;
dynamic result = fb.Post(path, param);
Now pls give me some suggestion, Where I'm missing, How can I access my Application Session.
Thanks,
Jigar Shah
Try this:
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("P3P", "CP=\"CAO PSA OUR\"");
if (!Page.IsPostBack)
{
}
}
I recently found that the following hidden field is required for proper functioning.
Please make shore u have it.
<input type="hidden" name="signed_request" value="<%: Request.Params["signed_request"]%>"/>
Link to my Question
Related
I have telerik REST web API(ASP.NET ) which is working fine. Now I need to localize the reports (report are in .trdx extension).
From documentation of telerik I found the code which have place in my BaseTelerikReportsController but this also not working, and even not show any error.
Telerik Localization Documentation
public class BaseTelerikReportsController : ReportsControllerBase
{
static readonly Telerik.Reporting.Services.ReportServiceConfiguration ConfigurationInstance;
static BaseTelerikReportsController()
{
var resolver = new CustomReportResolver();
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("aa-iq"); //<-- Line 1
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; //<-- Line 2
var reportsPath = HttpContext.Current.Server.MapPath("~/Reports");
ConfigurationInstance = new Telerik.Reporting.Services.ReportServiceConfiguration
{
HostAppId = "TBReportApp",
ReportResolver = resolver,
// ReportResolver = new ReportFileResolver(reportsPath),
Storage = new Telerik.Reporting.Cache.File.FileStorage(),
};
}
public BaseTelerikReportsController()
{
ReportServiceConfiguration = ConfigurationInstance;
}
}
Note
There is a similar question but don't guide me to any right direction Here
Update 1
I have added below function in Global.asax.cs.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("ar");
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
// Set the language for dynamic text (i.e. date, time, money)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
}
After above line (see image) data under red mark is localize but i need to localize yellow one(i.e heading)
I figure out how to localize the report header. Following are the some summarized steps.
Add App_GlobalResources folder and .resx accordingly your languages (See the figure 1-1).
Send language attribute from 'HTML5 Viewer'.
var viewer = $("#report-viewer").data("telerik_ReportViewer");
var model = {
//other attributes
Language: this.selectedLanguage //Here value may be ,en Or ar
};
viewer.reportSource({
report: reportSettings,
parameters: model
});
On server side based on that attribute change label accordingly.
private static void Localization(ref Report reportInstance)
{
ResourceManager currentResource = null;
switch (_language)
{
case "en":
currentResource = new ResourceManager("Resources.en", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
case "ar":
currentResource = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
}
// var MyResourceClass = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = currentResource.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string key = entry.Key.ToString();
string value = entry.Value.ToString();
var items = reportInstance.Items.Find(key,true);
foreach (var singleItem in items)
{
var singleItemType = singleItem.GetType();
//if (singleItem.GetType().FullName == "") ;
if (singleItemType.FullName == "Telerik.Reporting.TextBox")
{
var castItem = (Telerik.Reporting.TextBox) singleItem;
castItem.Value = value;
}
}
}
}
On Telerik Standalone Report Designer
Change your report(.trdx) Textbox value which matches your .resxname value pair.
Resource file values
This is the ReportViewer control:
<form id="reportForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="360000">
</asp:ScriptManager>
<div>
<rsweb:ReportViewer ID="mainReportViewer" runat="server" Width="100%"
Height="100%" SizeToReportContent="True" >
</rsweb:ReportViewer>
</div>
</form>
This is the code behind page:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] == null)
{
Response.Redirect("~/account/login", true);
}
string ReportPath = "";
try
{
if (mainReportViewer.Page.IsPostBack) return;
mainReportViewer.ProcessingMode = ProcessingMode.Remote;
mainReportViewer.ServerReport.ReportServerUrl = new Uri(
#"" + ConfigurationManager.AppSettings["ReportServer"].ToString()
);
ReportPath = Convert.ToString(ConfigurationManager.AppSettings["ReportPath"]);
if (!string.IsNullOrEmpty(ReportPath))
{
if (ReportPath.Substring(0, 1) == "/")
{
ReportPath = ReportPath.Substring(1, ReportPath.Length - 1);
}
if (ReportPath.Substring(ReportPath.Length - 1, 1) != "/")
{
ReportPath = ReportPath + '/';
}
}
else
{
ReportPath = "";
}
ReportPath = ReportPath + Request["Report"].ToString().Split(".".ToCharArray())[0].ToString();
mainReportViewer.ServerReport.ReportPath = #"/" + ReportPath;
ReportParameterCollection parmCol = new ReportParameterCollection();
string sFrom = "";
string sTo = "";
string dateRange = Request["dateRange"].ToString();
string[] obj = dateRange.Split("-".ToCharArray());
if (obj.Length > 1)
{
sFrom = obj[0].ToString();
sTo = obj[1].ToString();
}
else
sFrom = obj[0].ToString();
else if (Request["Report"].ToString().ToUpper() == "SOURCEWISEREPORT_AR.RDL")
{
string[] frommonthyear = sFrom.Split(',');
string[] tomonthyear = sTo.Split(',');
parmCol.Add(new ReportParameter("FromYear", frommonthyear[1]));
parmCol.Add(new ReportParameter("FromMonth", frommonthyear[0]));
parmCol.Add(new ReportParameter("ToYear", tomonthyear[1]));
parmCol.Add(new ReportParameter("ToMonth", tomonthyear[0]));
parmCol.Add(new ReportParameter("lang", Convert.ToString(Session["Culture"])));
}
mainReportViewer.PromptAreaCollapsed = true;
mainReportViewer.AsyncRendering = true;
mainReportViewer.ServerReport.Timeout = System.Threading.Timeout.Infinite;
mainReportViewer.ServerReport.SetParameters(parmCol);
mainReportViewer.ShowParameterPrompts = true;
mainReportViewer.LocalReport.EnableHyperlinks = true;
mainReportViewer.ServerReport.Refresh();
}
catch (Exception ex)
{
CommonFunctions.createLog("Reports : " + ex.Message);
}
}
When I try to view report(which is a view in asp.net mvc) it opens in a new tab to view the report (which is aspx page with codefile) and mean while if I try to open any link from the previous tab the page doesn't get loaded until the report in the new tab is completely loaded. I tried doing everything but no solution found yet. Need help
mean while if i try to open any link from the previous tab the page doesn't get loaded until the report in the new tab is completely loaded
You need to profile your application. Most likely your request has been queued trying to get a write lock for the user's session state.
You can read more about the problem here:
To prevent two pages from modifying in-process Session variables at the same time, the ASP.NET runtime uses a lock. When a request arrives for a page that reads and writes Session variables, the runtime acquires a writer lock. The writer lock will block other pages in the same Session who might write to the same session variables.
Emphasis mine.
To mitigate this, you can enable or disable session state for individual pages, or declare your usage of session state as "read only".
Pay attention not to accidentally choose the wrong type of session state, however (enabled, disabled, read only). It needs to be set correctly for your application to work correctly.
Since the ReportViewer user's session state continously, it uses a lock that blocks page loading.The method which i followed to solve my problem is :
Create a Class and implement IReportServerConnection2 interface
add key="ReportViewerServerConnection" value="MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken= 00000000000000000 "/> to web.config file in <appsettings>
Set EnableSessionState = "Readonly" at the ReportViewer.aspx page
This thread helped me in solving my issue :
The attempt to connect to the report server failed - Setting URL and Path in ASP.NET?
Can you try ?
System.Threading.Thread thLoadReport = new System.Threading.Thread(new System.Threading.ThreadStart(LoadReport));
thLoadReport.Start();
private void LoadReport()
{
// Invoke necessary controls here for eg.
mainReportViewer.Invoke((MethodInvoker)delegate {
// your report loading here
});
}
Let me know if you need more help with this.
I got error ProfileCommon could be not found , in my code. I don't know how to fix the error. I put namespace using system.Web.Profile, but error still does here. Could someone help how to do that? Please help me if you know. Thank you
public partial class UserProfile : System.Web.UI.UserControl
{
private string _userName = "";
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
this.Page.RegisterRequiresControlState(this);
}
protected override void LoadControlState(object savedState)
{
object[] ctlState = (object[])savedState;
base.LoadControlState(ctlState[0]);
_userName = (string)ctlState[1];
}
protected override object SaveControlState()
{
object[] ctlState = new object[2];
ctlState[0] = base.SaveControlState();
ctlState[1] = _userName;
return ctlState;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// if the UserName property contains an emtpy string, retrieve the profile
// for the current user, otherwise for the specified user
ProfileCommon profile = this.Profile;
if (this.UserName.Length > 0)
profile = this.Profile.GetProfile(this.UserName);
txtFirstName.Text = profile.FirstName;
txtLastName.Text = profile.LastName;
ddlGenders.SelectedValue = profile.Gender;
if (profile.BirthDate != DateTime.MinValue)
txtBirthDate.Text = profile.BirthDate.ToShortDateString();
ddlOccupations.SelectedValue = profile.Occupation;
txtWebsite.Text = profile.Website;
txtStreet.Text = profile.Address.Street;
txtCity.Text = profile.Address.City;
txtPostalCode.Text = profile.Address.PostalCode;
txtState.Text = profile.Address.State;
txtPhone.Text = profile.Contacts.Phone;
txtFax.Text = profile.Contacts.Fax;
}
}
public void Save()
{
// if the UserName property contains an emtpy string, save the current user's
// profile, othwerwise save the profile for the specified user
ProfileCommon profile = this.Profile;
if (this.UserName.Length > 0)
profile = this.Profile.GetProfile(this.UserName);
profile.FirstName = txtFirstName.Text;
profile.LastName = txtLastName.Text;
profile.Gender = ddlGenders.SelectedValue;
if (txtBirthDate.Text.Trim().Length > 0)
profile.BirthDate = DateTime.Parse(txtBirthDate.Text);
profile.Occupation = ddlOccupations.SelectedValue;
profile.Website = txtWebsite.Text;
profile.Address.Street = txtStreet.Text;
profile.Address.City = txtCity.Text;
profile.Address.PostalCode = txtPostalCode.Text;
profile.Address.State = txtState.Text;
profile.Contacts.Phone = txtPhone.Text;
profile.Contacts.Fax = txtFax.Text;
profile.Save();
}
}
As Mark pointed out, profiles only work out-of-the-box with the website template and I have blogged instructions on how to use the plug-in to facilitate the use of profiles for the Web Application project:
http://www.codersbarn.com/post/2008/07/10/ASPNET-PayPal-Subscriptions-IPN.aspx
It is possible to do it yourself, and here's a fully working implementation that you can download:
http://leedumond.com/blog/asp-net-profiles-in-web-application-projects/
According to these links(link1, link2)
Web Applications don't support the auto generation of the ProfileCommon object
The first link then give's a link to a VS Addin and instructions on how to incorporate it into the build process in order to work around the problem
There is a very simple work-around for this, for all coders who just want to hack on with things. You can get the ProfileBase type and load the profile into that, but you lose strong typing. If you are in control of the data in the profile, or you are sure that the data in the profile is of a certain type, you are good to go.
string user = "Steve"; // The username you are trying to get the profile for.
bool isAuthenticated = false;
MembershipUser mu = Membership.GetUser(user);
if (mu != null)
{
// User exists - Try to load profile
ProfileBase pb = ProfileBase.Create(user, isAuthenticated);
if (pb != null)
{
// Profile loaded - Try to access profile data element.
// ProfileBase stores data as objects in (I assume) a Dictionary
// so you have to cast and check that the cast succeeds.
string myData = (string)pb["MyKey"];
if (!string.IsNullOrWhiteSpace(myData))
{
// Woo-hoo - We're in data city, baby!
Console.WriteLine("Is this your card? " + myData + " - Ta Dah!");
}
}
}
I'm trying to create a Facebook Mobile Application using asp.net and MVC3 and integrate Facebook Credits as a payment method. First of all, taking the recent annoucements into consideration, is it now possible to have a mobile web application that accepts Facebook Credits?
If so, I've taken the example provided in the following post
http://www.m-webs.com/blog_facebookcredits.html
And implemented the following Controller action:
public JsonResult CallBack()
{
string fborder_info = Request.Form["order_info"];
string fborder_id = Request.Form["order_id"];
string fbmethod = Request.Form["method"];
if (fbmethod == "payments_get_items")
{
fborder_info = fborder_info.Substring(1, (fborder_info.Length - 2)); // remove the quotes
ulong credscost = 2; // Price of purchase in facebook credits
var theItem = new FacebookBuyItem()
{
item_id = 123456789,
description = "Own yours today!",
price = credscost,
title = "Digital Unicorn",
product_url = "http://www.facebook.com/images/gifts/21.png",
image_url = "http://www.facebook.com/images/gifts/21.png"
};
var res = new Dictionary<string, object>();
res["method"] = fbmethod;
res["order_id"] = fborder_id;
res["content"] = new object[] { theItem };
var jss = new JavaScriptSerializer();
var ob = jss.Serialize(res);
ob = ob.Replace("#$", #"\/".Replace("//", #"\/"));
return Json(ob, JsonRequestBehavior.AllowGet);
}
return null;
}
I've verified that the callback is being requested by facebook, and I've also captured the response being sent back, which appears to contain all of the required information to display the purchase dialog, but I'm still getting the following error message:
API Error Code: 1151
API Error Description: Sorry, but this app may not be eligible to accept Facebook Credits. If this app has accepted credits before, please try again.
Error Message: Invalid Application
and when tested from a mobile browser:
Sorry, but we're having trouble processing your payment. You have not been charged for this transaction. Please try again.
I've also noticed that my callback is being requested twice which doesn't seem right either.
Any insight into how to get my integration up and running would be greatly appreciated. My Facebook AppId is 177876855621874
Thanks.
Update: So I played around with the examples given and reverted back to webforms in order to test the example given at http://www.m-webs.com/blog_facebookcredits.html. In order to get this solution working in an asp.net MVC3 application I had to change the action type to HttpResponse instead of JsonResult which makes sense as the JsonResult leaves elements out that would normally be included in a HttpResponse.
So the Controller Action ended up looking like this:
[HttpPost]
public HttpResponse CallBack()
{
if (Request.Form["signed_request"] != null)
{
var decodeFbSignedRequest = FacebookSignedRequest.Parse(FacebookApplication.Current.AppSecret,
Request.Form["signed_request"]);
LogHelper.MicroLogMsg("SIGNED REQUEST DECODE:: " + decodeFbSignedRequest.Data);
}
string fborder_id = Request.Form["order_id"];
string fbmethod = Request.Form["method"];
string fborder_info = Request.Form["order_info"]; // Use this to look up a product on the database..
if (fbmethod == "payments_get_items")
{
int credscost = 2; // Price of purchase in facebook credits
var theItem = new FacebookBuyItem()
{
item_id = "123456AA",
description = "[Test Mode] Own yours today!",
price = credscost,
title = "[Test Mode] Digital Unicorn",
product_url = #"http:\/\/www.facebook.com\/images\/gifts\/21.png",
image_url = #"http:\/\/www.facebook.com\/images\/gifts\/21.png"
};
// Return the initial response to FB
//------------------------------------------
var res = new Dictionary<string, object>();
res["method"] = fbmethod;
res["content"] = new object[] { theItem };
var jss = new JavaScriptSerializer();
string ob = jss.Serialize(res);
LogHelper.MicroLogMsg(ob);
Response.ContentType = "application/json";
Response.Write(ob);
Response.End();
}
return null;
}
I hope this helps out anyone doing an MVC3 implementation for Facebook Credits.
I have an application in Asp.Net and at a click of a button it is supposed to launch another mapping application. In that application the credentials of the user like user name and Email are required. So, I was trying to set a cookie and fix the domain of the cookie to that application but I am not able to see the cookie in that application. I am not really sure what is going wrong or if I have made some mistake in the cookie.
MembershipUser usr = Membership.GetUser();
Guid newUserId = (Guid)usr.ProviderUserKey;
HttpCookie SampleCookie = new HttpCookie("UserInfo");
Response.Cookies["UserInfo"]["UserName"] = usr.UserName;
Response.Cookies["UserInfo"]["Email"] = usr.Email;
SampleCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(SampleCookie);
SampleCookie.Domain = "http://157.182.212.204/MAP";
Thank you once again for the help.
Code for MAP application:
function Get_Cookie( check_name ) {
// first we'll split this cookie up into name/value pairs
// note: document.cookie only returns name=value, not the other components
var a_all_cookies = document.cookie.split( ';' );
var a_temp_cookie = '';
var cookie_name = '';
var cookie_value = '';
var b_cookie_found = false; // set boolean t/f default f
for ( i = 0; i < a_all_cookies.length; i++ )
{
// now we'll split apart each name=value pair
a_temp_cookie = a_all_cookies[i].split( '=' );
// and trim left/right whitespace while we're at it
cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
// if the extracted name matches passed check_name
if ( cookie_name == check_name )
{
b_cookie_found = true;
// we need to handle case where cookie has no value but exists (no = sign, that is):
if ( a_temp_cookie.length > 1 )
{
cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
}
// note that in cases where cookie is initialized but no value, null is returned
return cookie_value;
break;
}
a_temp_cookie = null;
cookie_name = '';
}
if ( !b_cookie_found )
{
return null;
}
}
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
alert(Get_Cookie("UserName"));
The code for the WVWRAPICt page RESET.aspx.cs is given below...This is where the cookie is being set
using System;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class RESET_RESET : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Menu Nav = Master.FindControl("NavigationMenu1") as Menu;
MenuItemCollection Menu = Nav.Items;
foreach (MenuItem item in Menu)
{
string name = item.Text.ToString();
if (name == "ADMIN")
{
item.Enabled = User.IsInRole("Administrator");
}
if (name == "ICT")
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser();
Guid newUserId = (Guid)usr.ProviderUserKey;
HttpCookie SampleCookie = new HttpCookie("UserInfo");
SampleCookie["UserName"] = usr.UserName;
SampleCookie["Email"] = usr.Email;
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string checkSiteEventIDSQL = "Select * from UserProfiles WHERE UserId='" + newUserId + "'";
using (SqlConnection myConnection1 = new SqlConnection(connectionString))
{
try
{
myConnection1.Open();
SqlCommand myCommand1 = new SqlCommand(checkSiteEventIDSQL, myConnection1);
SqlDataReader myReader = myCommand1.ExecuteReader();
if (myReader.HasRows)
{
while (myReader.Read())
{
string Agency = (myReader.GetValue(2)).ToString();
SampleCookie["Agency"] = Agency;
}
}
}
catch (Exception ex)
{
}
finally
{
myConnection1.Close();
}
}
SampleCookie.Expires = DateTime.Now.AddDays(1);
SampleCookie.Domain = "157.182.212.204/MAP";
// SampleCookie.Path = "/MAP";
Response.Cookies.Add(SampleCookie);
Response.Redirect("http://157.182.212.204/MAP/index.html");
}
}
Regarding trouble with the way you are setting your cookie... you're not going to find the cookie in the response unless you've added it to the response. (And if you ARE finding it, you're just over-writing that cookie a couple lines later). Just edit the cookie directly then add to the cookie jar. Also I believe the MAP should be in the path property of the cookie (not sure how big of a difference it makes). As far as I know you don't want the http in the domain (again, not sure if the browser is smart enough to handle).
MembershipUser usr = Membership.GetUser();
Guid newUserId = (Guid)usr.ProviderUserKey;
HttpCookie sampleCookie = new HttpCookie("UserInfo");
sampleCookie["UserName"] = usr.UserName;
sampleCookie["Email"] = usr.Email;
sampleCookie.Expires = DateTime.Now.AddDays(1);
sampleCookie.Domain = "157.182.212.204";
sampleCookie.Path = "/MAP";
Response.Cookies.Add(sampleCookie);
Cookies can only be set to a domain which is a 'tail' of the current FQDN. So if your current FQDN is not 157.182.212.204, the cookie will not set in the browser. By tail, for example, I mean http://overflow.acme.com could set a cookie for overflow.acme.com or acme.com, but not for fubar.acme.com or fubar.com.
My guess is if your application is on a different FQDN than the MAP application, you're going to need to figure a different way to pass the user name and e-mail to the map application (maybe post to a page on the map application which can set the cookie and then redirect to the appropriate page?
Update after you've posted some more code:
Try this:
SampleCookie.Domain = "157.182.212.204";
SampleCookie.Path = "/MAP";
Response.Cookies.Add(SampleCookie);
Response.Redirect("http://157.182.212.204/MAP/index.html", false);
Setting false on the response.redirect should cause the set cookie headers to come through. You might need to short circuit other logic in your page if you have anything in the render events
Or just pass the stuff in a query string. You're not using HttpOnly cookies (so a user could inject the cookies).