ProfileCommon could be not found - asp.net

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!");
}
}
}

Related

user.Roles.FirstOrDefault() returns DynamicProxy

OK...
I was finally making some headway with creating a User Management page using Identity 2 in Web Forms.
It was mostly moving along just fine. When suddenly I run into this issue, and it makes no sense to me.
I have an AS form with a dropdown list of Roles. That list is populated using
roleMgr.Roles.ToList();
Works Great
I use the user being edited Role to set the current selected value.
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
This WAS working like dynamite
Last week...
Now all of a sudden user.Roles.FirstOrDefault().ToString(); is returning
"System.Data.Entity.DynamicProxies.IdentityUserRole_FDDE5D267CF62D86904A3BC925D70DC410F12D5BE8313308EC89AC8537DC6375"
What he heck, man?
So I tried user.Roles.Take(1).ToString();
That returns
"System.Linq.Enumerable+d__24`1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole]"
I have to presume I Broke, Something...
But What?
Nothing in this code page changed at all between when it worked and then didn't.
The only thing I did related to Identity at all was Migrate a couple of fields into AspNetUsers (another whole ballgame, migrations...) which also worked like dynamite BTW.
I even went to the extreme of wiping out my Migrations and AspNet user tables entirely, and re-initializing it all.
Any suggestions ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Sperry_Parts.Models;
using Sperry_Parts.Logic;
using Microsoft.AspNet.Identity.Owin;
using Owin;
namespace Parts.Admin
{
public partial class CreateEditUser : System.Web.UI.Page
{
private bool NewUser
{
get { return ViewState["NewUser"] != null ? (bool)ViewState["NewUser"] : false; }
set { ViewState["NewUser"] = value; }
}
private string EditUser
{
get { return (string)ViewState["EditUser"]; }
set { ViewState["EditUser"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EditUser = Session["Edit_User"].ToString();
// Access the application context and create result variables.
Models.ApplicationDbContext context = new ApplicationDbContext();
RoleActions roleAction = new RoleActions();
// Create a RoleStore object by using the ApplicationDbContext object.
var roleStore = new RoleStore<IdentityRole>(context);
// Create a RoleManager object that is only allowed to contain IdentityRole objects.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
// Load the DDL of Roles
var roles = roleMgr.Roles.ToList();
ddlUserType.DataTextField = "Name";
ddlUserType.DataValueField = "Id";
ddlUserType.DataSource = roles;
ddlUserType.DataBind();
if (EditUser == "")
{
txtUserName.Enabled = true;
txtUserName.Focus();
NewUser = true;
} // End New User
else
{
// User part
var userMgr = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
txtUserName.Enabled = false;
txtFullName.Focus();
var user = userMgr.FindByName(EditUser);
if (user != null)
{
txtUserName.Text = user.UserName;
txtUserEmail.Text = user.Email;
txtFullName.Text = user.FullName;
var hisroles = user.Roles.ToList(); // properly returns 1 item
// this is where it went off the rails - these 4 lines are debugging code
string xrole = user.Roles.FirstOrDefault().ToString();
string role2 = user.Roles.Take(1).ToString();
string trythis = xrole.ToString();
string trythis2 = role2.ToString();
// I swear, this worked last week...
ddlUserType.SelectedValue = user.Roles.FirstOrDefault().ToString();
}
} // End Editing User
} // End if (!IsPostBack)
} // End Page Load
protected void CreateUser()
{
// removed as non-relevant to question
} // End CreateUser
protected void UpdateUser()
{
// removed as non-relevant to question
} // End UpdateUser
protected void btnSave_Click(object sender, EventArgs e)
{
// removed as non-relevant to question
} // End btnSave
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/ManageUsers");
} // End btnCancel
} // End Class CreateEditUser
}
I ran into the same problem trying to set the value of a "Roles" DropDownList inside a GridView Control. I solved it by using:
user.Roles.First().RoleId
It just happens that my RoleId is also my role name.

Login users at the same time problems in signalr

I'm working on a social network with ASP.NET and signalr. I have a simple login page, if it finds the user in the database it creates an Application variable and redirect the user to the profile page and in this page i invoke my Connect method declared in my hub class, this method takes the userid in the session and it give the friend list of this user. That works great when two or many users logged in at different time. The thing is, when two or several users logged in at the same time, the connect method declared in my hub takes the last user id stored in the Application variable and it give the friend list of this last user id and it send it to all user connected.
I can't find the correct approach.
Loggin Page code:
protected void btn_login_Click(object sender, EventArgs e)
{
Tbl_User user = new Tbl_User();
user = FonctionCommun.Login(txt_UserName.Text , txt_PassWord.Text);
if (user != null)
{
Application["UserID"] = user.UserID.ToString();
Response.Redirect("Profile.aspx");
}
else {
Label1.Visible = true;
}
}
My connect method code:
public void connect()
{
UserID = Guid.Parse(HttpContext.Current.Application["UserID"].ToString());
string OutPut = "";
if (ListOnlineUser.Count(x => x.UserID == UserID) == 0)
{
ListOnlineUser.Add(new OnlineUsers { UserID = UserID, ConnetionID = Guid.Parse(Context.ConnectionId) });
objchat.SetOnline(UserID);
ListFriends = objchat.GetFriendLoginStatus(UserID);
}
foreach (Tbl_User item in ListFriends)
{
if (item.Status == "1")
{
OnlineUsers onlineFriend = ListOnlineUser.FirstOrDefault(x => x.UserID == Guid.Parse(item.UserID.ToString()));
if (onlineFriend != null)
{
using (FIESTA_ADVISOREntities BD = new FIESTA_ADVISOREntities())
{
Tbl_User Obj_User = BD.Tbl_User.Where(o => o.UserID == UserID).FirstOrDefault();
if (Obj_User.ProfileImage != null)
{
string ext = BD.Assets.Where(o => o.url == Obj_User.ProfileImage).Select(o => o.MimeType).FirstOrDefault();
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = Obj_User.ProfileImage.ToString(), Ext = ext };
OutPut = JsonConvert.SerializeObject(res);
}
else {
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = "111", Ext = "png" };
OutPut = JsonConvert.SerializeObject(res); }
Clients.Client(onlineFriend.ConnetionID.ToString()).OnNewUserConnect(OutPut);
}
}
}
}
Clients.Caller.ShowFriends(ListFriends);
}
Try session variable instead of application variable. Application variable shared through out application working. So Whenever new user this is override. But if you use session variable that will never override by any other user
Also you can use query string in signalr in which you can pass userid as query string so in each request userid will be in query string
$.connection.hub.qs = 'userid=' + "UserId";

Functionality of not working user control not working on Sharepoint 2007 List Edit.aspx

I have deployed a user control on sharepoint 2007 list Edit.aspx page. It is working fine on my test server but on production only the UI of the user control is loaded. No textbox or combo box on page load are getting filled. Please see the screen shot of default values of user control instead of the filled up data. Also find the code below which takes the ID from querystring and loads the required data on page load. I have used createdby value to check who is assigning the list item. If the user is accessing the data which is not created by him then its redirected to other page.Please guide me. What shall I do or check to make it work.
public partial class Class1 : System.Web.UI.UserControl
{
static string name, lname, Number;
protected void Page_Load(object sender, EventArgs e)
{
try
{
string c1,c2,c3,c4,c5, Created;
if (!Page.IsPostBack)
{
EditID = Convert.ToInt32(Request.QueryString["ID"]);
name = SPContext.Current.Web.CurrentUser.Name;
lname = SPContext.Current.Web.CurrentUser.LoginName;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("site name"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["list1"];
SPList UserSkill = web.Lists["list2"];
ItemForEdit = UserSkill.GetItemById(EditID);
c1 = ItemForEdit["col1"].ToString();
c2 = ItemForEdit["col2"].ToString();
c3 = ItemForEdit["col3"].ToString();
c4 = ItemForEdit["col4"].ToString();
c5 = ItemForEdit["col5"].ToString();
Created = ItemForEdit["Author"].ToString();
Number = ItemForEdit["col6"].ToString();
string[] extract;
extract = Created.Split('#');
if (name == extract[1])
{
WholeData = web.Lists["list1"].Items.GetDataTable();
Roles = WholeData.DefaultView.ToTable(true, "Title");
txtnumber.Text = Number;
ddlRole.DataSource = Roles;
ddlRole.DataTextField = "Title";
ddlRole.DataValueField = "Title";
ddlRole.DataBind();
ddlRole.SelectedValue = c1;
//more code
}
else
{
Response.Redirect("/IM/pages/Intrusion.aspx", false);
}
}
}
});
}
}
catch (Exception exc)
{
HttpContext.Current.Response.Write("<script>alert('Exception on page load: " + exc.Message + "')</script>");
}
}
}
It looks at first cut to be a data issue.
To debug on your production box you can use a remote debugger, or you could add a call that checks if 0 items are returned and either product an error or log the result.

How to implement Generics in business object class definition with DAL to create a proper user control dropdown

I am woefully new to generics, being tied to the support of a corporate intranet web application whose upgrade process is bound to red tape and slowwwly-changing standards. Consequently, today (thankfully!) I finally find myself scrambling during our upgrade to .Net 3.5 and transitioning all the code I can to a properly tiered model.
I have been reading all morning about generics trying to digest how to transition dropdown user controls into a proper business object that gets its data from a class in the data access layer.
There is a perfectly succinct question here that details exactly what I am interested in exploring: Set selected index in a Dropdownlist in usercontrol.
What I would love to see, however, is what Travel_CarSizes.GetCarSizes() actually looks like inside and how the class Travel_CarSizes is defined. (I am having a hard time with <T> and knowing where it should occur.)
For my own specific circumstance at the moment I need a dropdown user control to contain location directionals (N, S, W, C/O, NW, SE, etc) that are stored in a SQL table in the DB and whose selected index needs to be able to be set by whichever page it happens to be in, when form data exists.
I have begun to implement the model in the example from the link above but right now without using Generics because I can't figure it out:
The dropdown user control:
public partial class DropDownStreetPrefix : System.Web.UI.UserControl
{
public string StreetPrefixValue
{
get { return ddlStreetPrefix.SelectedValue.ToString(); }
set
{
Bind();
ddlStreetPrefix.SelectedIndex = ddlStreetPrefix.Items.IndexOf(ddlStreetPrefix.Items.FindByValue(value));
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Bind();
}
}
private void Bind()
{
if (ddlStreetPrefix.Items.Count == 0)
{
SqlDataReader rdr = StreetDirectionals.GetDirectionals();
ddlStreetPrefix.DataSource = rdr;
ddlStreetPrefix.DataBind();
ddlStreetPrefix.DataValueField = "StreetSuffixPrefixAbbr";
ddlStreetPrefix.DataTextField = "StreetSuffixPrefixAbbr";
ListItem li = new ListItem("", "");
ddlStreetPrefix.Items.Insert(0, li);
ddlStreetPrefix.SelectedIndex = 0;
}
}
}
The StreetDirectionals class:
public class StreetDirectionals
{
private StreetDirectionals () { }
public static SqlDataReader GetDirectionals ()
{
string sqlText = "SELECT StreetSuffixPrefixAbbr FROM common..tblStreetSuffixPrefix " +
"ORDER BY StreetSuffixPrefixAbbr";
SqlDataReader rdr = SqlClient.ExecuteFetchReturnDataReader( theConnectionString, CommandType.Text, sqlText);
return rdr;
}
}
I will separate out the database interaction inside the StreetDirectionals class as soon as I can figure out how to change its code if I were to transform the Bind() method from my dropdown user control into this:
private void Bind()
{
if (!IsPostBack)
{
**List<StreetDirectionals> sd = StreetDirectionals.GetDirectionals();**
ddlStreetPrefix.DataSource = sd;
ddlStreetPrefix.DataTextField = "StreetSuffixPrefixAbbr";
ddlStreetPrefix.DataValueField = "StreetSuffixPrefixAbbr";
ddlStreetPrefix.DataBind();
}
}
Any assistance would be sooo much appreciated!
public class StreetDirectional
{
public string StreetSuffixPrefixAbbr { get; set; }
public static IEnumerable<StreetDirectional> GetDirectionals ()
{
string sqlText = "SELECT StreetSuffixPrefixAbbr FROM common..tblStreetSuffixPrefix "
+ "ORDER BY StreetSuffixPrefixAbbr";
SqlDataReader rdr = SqlClient.ExecuteFetchReturnDataReader( theConnectionString, CommandType.Text, sqlText);
var list = new List<StreetDirectional>();
while (rdr.Read())
{
var item = new StreetDirectional() { StreetSuffixPrefixAbbr = (string)rdr["StreetSuffixPrefixAbbr"] };
list.Add(item);
}
return list;
}
}
then you can do this
ddlStreetPrefix.DataSource = StreetDirectional.GetDirectionals();

access ASP.Net Session variable in Facebook C# SDK

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

Resources