Profile.GetProfile() on Base Class - c#

I have a base page (inherited from System.Web.UI.Page and all my pages inherit from this base page) in my .Net web application and at the moment if I put the following methods:
protected int GetProfileTenant()
{
try
{
ProfileCommon p = Profile.GetProfile(Profile.UserName);
return Convert.ToInt32(p.TenantID);
}
catch
{
return -1;
}
}
the error come up saying that "the Name Profile does not existin the current context".
This methods if I put this into the page (inherited from the base page clas) works well (no issue).
Any ideas?
Thanks
Thanks

Add System.web namespace in the class.
and try this
HttpContext.Current.Profile.UserName

I don't have a clear-cut answer for you, but there is some "magic" happening in the way profiles work (a class matching your profile properties gets generated). Apparently the Profile property gets injected into the top level page class. Have you tried using HttpContext.Current.Profile instead?

Related

How can i define gloabal C# code classes in ASP.NET Blazor which functions can be called from each partial class of the related razor pages?

I have a Blazor application where I program the code of each razor page in the related xxx.razor.cs Class in C#. I have the case that I use common functions in this C# codes. So instead of repeating the common functions in each class, I want to define a common class, and then call the function from each class. How can I do that? I have tried it like in a C# desktop application but it didn't work.
Commonclass test = new Commonclass();
test.CommonFunction();
I don't know why but after trying for hours I see my error always just when I have posted my question. I had copied the common class from another directory. I forgot to correct the namespace. After correcting it worked.
I think the accepted way to do this is dependency injection. Either a scoped or singleton service.
Program.cs
builder.Services.AddSingleton<Commonclass>();
Razor Page
[Inject] Commonclass test { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
test.CommonFunction();
}

Asp.net 4.5 Custom Attribute Webform

Using a Asp.Net old project, to access webforms I need to create a custom class Attribute that reads users rights like 'Rights.ViewDashboard' or 'Rights.CanEdit' an so. The class code is:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AuthorizationAttribute : Attribute
{
public AuthorizationAttribute(Rights permission)
{
if (Security.IsAuthorizedTo(permission))
return;
HttpContext.Current.Server.TransferRequest("~", false);
}
}
In the aspx webform I have:
[Authorization(Rights.ViewDashboard)]
public partial class DashboardRisorse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
When the user calls the webform if he haven't specific right the page is not loaded and site is redirected to the default page. But if he make a refresh of the page the code isn't execute, attribute is ignored and the page is loaded. When debugging I see that this attribute is executed only once.
Where is my fault?
I don't need Net Core solution because the project has old assemblies.
Thanks.
Ingd
I am assuming here that you are trying to define custom attribute similar to ActionFilter Attributes in MVC. Unfortunately ASP.Net does not work in the same way.
You have two options
Create an HttpModule and use one of the events available to build your logic
Write the logic you want to execute in Page Load. Use Page.IsPostBack to identify if it is initial load of the page or if the page is being posted back. Write the logic you need within the if.. else if conditions
In case my assumption was incorrect then please provide more details on your query specifically what is it that you are trying to achieve using the Attribute.

Moving data from one web form to another ASP.NET C#

I am trying to move the content of a textbox on the from StudentRegistration to the form MyProfile by following a tutorial on YouTube. However when I try to reference the StudentRegitration Page in my code, I get the error that the type or namespace cannot be found.
In the tutorial I can see that in their code they have a namespace, however my website does not. Could anyone tell me what to do in order to be able to reference StudentRegistration without getting an error?
I should have stated that I have a website not a web app. I have found that websites do not have a default namespace. How would I go about accessing the StudentRegistration without referencing a namespace?
public partial class MyProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
lblEmail.Text = StudentRegistration.STextBoxEm;
}
}
}
Rather than answer your question directly, I'd like to point out another issue with your code that will probably prevent it from working. You should refer to the documentation on the PreviousPage property at: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage%28v=vs.110%29.aspx
It does NOT work like this:
user visits /StudentRegistration.aspx
user does stuff
user submits the form on /StudentRegistration.aspx
server redirects the user to /MyProfile.aspx
MyProfile class knows that PreviousPage = the class from /StudentRegistration.aspx
Instead, the description from the msdn reference page linked above stipulates that the PreviousPage property only works on this scenario:
user visits /StudentRegistration.aspx
user does some stuff
user submits form on /StudentRegistration.aspx
server transfers request to the MyProfile class
this does not mean that the url has changed to /MyProfile.aspx for the user, this means that the server is going to treat the current request to /StudentRegistration.aspx as if it were actually a request to /MyProfile.aspx
the user ends up seeing the result of what would normally be /MyProfile.aspx on /StudentRegistration.aspx
Now, your code may actually want that, but the fact that you have:
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
// this should be
// StudentRegistration LastPage = (StudentRegistration)PreviousPage;
}
makes me think that you have misinterpreted the somewhat misleadingly named PreviousPage property. For a sample of how to persist state across multiple page loads in .NET, I would recommend reading up on SessionState. It has a somewhat complicated name, but does more of what you would want in this scenario:
http://msdn.microsoft.com/en-us/library/ms178581%28v=vs.100%29.aspx
An added bonus is that you do not need to reference one class from another, so you fix your current bug later on. Additionally, even if you did resolve your potential namespace error, the issue that I outlined earlier will cause the value of the text field to be blank if your code is working as I suspect.
You are sending data from a source to a target - e.g. StudentRegistration -> MyProfile
You have options because at the end of the day, it is HTTP. Aside from "persistence" (Session), and the tutorial you are following, a "simpler" way is to use ButtonPostBackUrl.
All it means is that you are POSTing data to the target page. The target page (MyProfile) will have to validate and parse the posted data (Request.Form). This way you don't have to manage things like Session state.

Get Page's Type from URL in C#

Given a URL, I have to be able to know what the page's Type is that resides at that URL. For example, lets say I have a couple pages.
//first.aspx
public partial class FirstPage : System.Web.UI.Page { }
//second.aspx
public partial class SecondPage : MyCustomPageType { }
I would like to be able to call a method in the following manner with the following results:
GetPageTypeByURL("first.aspx"); //"FirstPage"
GetPageTypeByURL("second.aspx"); //"SecondPage"
Is this possible? How can I do this?
From this answer, it appears that you can get the class of a specific page. You may then be able to use reflection to determine its base type. (Note: I haven't attempted this, it's just a suggestion.)
System.Web.Compilation.BuildManager.GetCompiledType(Me.Request.Url.AbsolutePath)
What about this?
public Type GetPageTypeByURL(string url)
{
object page = BuildManager.CreateInstanceFromVirtualPath(url, typeof(object));
return page.GetType().BaseType.BaseType;
}
Usage:
Type pageType = GetPageTypeByURL("~/default.aspx");
Just a thought:
I assume that you calling the page from some other program.
Get the HTML, search for your distinguishing HTML / hidden element that tells you what the page is.
If you are on the server just load up the page as a text file and read it.
Page page = (Page)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(url, typeof(Page));
CustomerPage page = (CustomerPage) SomeMagicalPageCreater.CreatePage("CustomerPage.aspx");
https://forums.asp.net/t/1315395.aspx
This is what I found.

After creating separate Models and Controllers projects, I get "no suitable method found to override" on my Initialize method declaration

This is driving me insane... I am reorganizing my MVC app into a Models project and a Controllers project, and then the main application as a project. So, everything is working good so far except...
Whenever I go to "Rebuild" my controllers project, I get this error:
Controllers.AccountController.Initialize(System.Web.Routing.RequestContext)': no suitable method found to override.
Keep in mind that AccountController.cs was automatically placed in my application by Visual Studio, and this was all working fine when the Controllers were within my main project. I think it might have to do with the ASPNETDB.MDF file that this AccountController.cs file references to authenticate users as they log in, since this database stayed within my main project and didn't follow the Controllers project. Thoughts on that??
Here's the Initialize method on my AccountController:
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
PLEASE HELP!!! Thanks in advance!!
this error message suggests that your AccountController class isn't being derived from MVC's Controller base class.
It turns out what I was missing was a reference to System.Web.Routing. I had using System.Web.Routing, and it wasn't marked "red" (meaning, it couldn't find it), so I just assumed it was there. So this fixed the problem.

Categories

Resources