C# Session doesn't exist in current content - c#

I want to save the userid in the session to use in the application. I gave the following code.
But getting compilation error saying The name Session doesn't exist in the current context. is there any library that I need to use?. Please advise.
private void button1_Click(object sender, EventArgs e)
{
Session["Username"] = user.Text;
}

if it is a web application it should have worked.
anyways try adding
HttpContext.Current.Session["Username"] = user.Text;

I went ahead and solved this for myself, was having the same problem until I read the MS documentation: https://msdn.microsoft.com/en-us/library/system.web.httpcontext.session%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396. Basically, outside of the WebForms class, you need to grab a reference to the context. Example follows for getting and setting the sessionStorage.
using System.Web;
HttpContext context = HttpContext.Current;
Setting:
context.Session["FirstName"] = firstName;
Getting:
firstName = (string)(context.Session["FirstName"]);

Related

Updating a lookup field from a Silverlight app - CRM 2011

I'm using the following code to try and update a lookup field value in my CRM 2011 system from a silverlight app:
try
{
ma.my_ActionDetails = details;
Guid userId = new Guid();
foreach (SystemUser s in SystemUsers)
{
if (s.FullName.Equals(comboBox1.SelectedItem))
{
userId = s.SystemUserId;
}
}
// Define eval statements for setting lookup to a value and null
string setLookupJscript = #"Xrm.Page.getAttribute(""{0}"").setValue([ {{ id: ""{1:B}"", typename: ""{2}"", name: ""{3}"" }}])";
string evalStatement = null;
// Set the statement to be evaluated based upon the value of the id argument
// Setting the lookup to a value
evalStatement = string.Format(setLookupJscript, "my_salesperson", userId, "my_memberaction", ma.my_SalesPerson.Name);
HtmlPage.Window.Eval(evalStatement);
_context.UpdateObject(ma);
_context.BeginSaveChanges(OnUpdateAccountComplete, ma);
}
catch (SystemException se)
{
_syncContext.Send(new SendOrPostCallback(showErrorDetails), se);
}
However when I run this code it generates the following errors:
In the browser:
'Xrm' is undefined
From the code:
System.InvalidOperationException: [Common_MethodFailed]
Can anyone explain whats going on here?
Thanks,
Jack
You need to be within the context of a CRM form for the Xrm namespace to be available. Are you running from within a form?
From the CRM SDK:
If your Silverlight web resource is designed to be viewed in an entity form, the form has an Xrm.Page.context object you can use to access contextual information.
If you need your Silverlight application to appear outside the context of the form you must configure an HTML web resource to provide this context information by adding a reference to the ClientGlobalContext.js.aspx page. After this reference is added, your Silverlight application can access contextual information in the same way it can in an entity form. The following sample shows how to call the getServerUrl function from the Xrm.Page.context object.
private string serverUrl = "";
ScriptObject xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
ScriptObject page = (ScriptObject)xrm.GetProperty("Page");
ScriptObject pageContext = (ScriptObject)page.GetProperty("context");
serverUrl = (string)pageContext.Invoke("getServerUrl");

How to add a module on my page in DNN programatically

So far, I have tried below code to add a module through code on my page in DNN.
protected void Page_Load(object sender, EventArgs e)
{
ModuleController MC = new ModuleController();
ModuleInfo MInfo = new ModuleInfo();
MInfo = MC.GetModule(507, 116,false);//Just Hard coded for testing
MInfo.TabID = PortalSettings.ActiveTab.TabID;
MInfo.PaneName = "ContentPane";
MInfo.Alignment = "left";
MC.AddModule(MInfo);//Line throwing error :-
}
I am trying to add a module which is present on tabid=116 and having moduleId=507 on my current tab or page in pageLoad Event.But the last line throwing a error saying
"Violation of UNIQUE KEY constraint 'IX_TabModules_UniqueId'. Cannot insert duplicate key in object 'dbo.TabModules'. The duplicate key value is (555ba77a-be19-40a0-bb72-559672230345)."
Please tell me where i am doing wrong ? and is this the correct way to add a module ?
The first thing that I notice is that you're effectively trying to add the same instance of the module to the database. You've changed the TabID, but otherwise all of the other IDs within the ModuleInfo instance are still there.
Looking at how DNN adds an existing module (look in the DoAddExistingModule method), they start by calling Clone() on the ModuleInfo instance, and then reset the UniqueId (which is the constraint you're hitting):
newModule.UniqueId = Guid.NewGuid();

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

Creating Facebook Application in asp.net

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

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).

Categories