I am building an application in asp.net using C# where people have their own profiles, and if they want to see others profile they can, but they only have read permission; how to set all these read write permissions in Ms Sql?
here is one way you can hide/show the controls based the user id on asp.net side.
Then there is no need to actually do the work on DB level since user does not have any ability to do that via UI.
pseudo code:
public void Page_Load(object sender,Eventargs e)
if(!Page.IsPostBack){
string userid= //get the id of the user whose profile you want to see
string loggeduserid=//get the id of the logged in user
bool visible = userid==loggeduserid
ShowHideControls(visible)
}
}
private void(bool visible){
btnEdit.Visible=visible;
btnDelete.Visible = visible;
//set other controls' visibility.
}
This is one way. You can refine the code above as per the need.
I will suggest you do it on your code level itself instead of DB because essentially you will be doing the same check if it were in a storedproc.
Related
Saw so many articles and links related to the same concept.
Counting online users using asp.net
Is there any ASP.NET application to monitor online user and page view log report?
Mine is little different. My application is MVC4 and using SimpleMembershipProvider. I am not sure why GetNumberOfUsersOnline is not working.
https://msdn.microsoft.com/en-us/library/system.web.security.membership.getnumberofusersonline(v=vs.110).aspx
Any Ideas ? How to do this in a easy and efficient way. I am just using this in only one place in my website.
I found this online it it looks like it will work for you. Just add this code to your Global.asax.cs file:
protected void Application_Start(Object sender, EventArgs e)
{
Application.Lock();
Application["UserCount"] = 0;
}
protected void Session_Start(Object sender, EventArgs e)
{
Application.Lock();
Application["UserCount"] = (int)Application["UserCount"] + 1;
Application.UnLock();
}
protected void Session_End(Object sender, EventArgs e)
{
Application.Lock();
Application["UserCount"] = (int)Application["UserCount"] - 1;
Application.UnLock();
}
Then when you need to access the user count you can use:
var count = (int)Application["UserCount"];
You can use signalR to track connected users. Using this you can get count online efficiently & Real Time and also track connected users information. You can put condition to track logged in users also. So, Go with latest technology. You can implement with existing MVC application.
You can refer this official tutorial for the same.
http://www.asp.net/signalr
Another nice solution that is pleasantly orthogonal to your code is Google Analytics. http://www.google.com/analytics/ Using GA, you can see a real-time display of active users on your website. It also helps that you have a history over time and can see peaks and valleys of user activity.
From Microsoft documentation:
GetNumberOfUsersOnline returns the number of users for the current ApplicationName where the last-activity date is greater than the current time less the UserIsOnlineTimeWindow. The last-activity date/time stamp is updated to the current date and time when user credentials are validated by way of the ValidateUser or UpdateUser method or when a call to a GetUser overload that takes no parameters or one that uses the userIsOnline parameter to specify that the date/time stamp should be updated.
You can see that GetNumberOfUsersOnline depends on multiple parameters and isn't efective.
As a workaround I suggest that you could nherits SqlMembershipProvider and override the GetNumberOfUsersOnline(), so you cam implement your logic here.
public class MyMembershipProvider : SqlMembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (base.ValidateUser(username, password))
{
// successfully logged in. add logic to increment online user count.
return true;
}
return false;
}
public override int GetNumberOfUsersOnline()
{
// add logic to get online user count and return it.
}
}
Just decrement online user count logic in user log out
If you want track visitors and pages visited, here some idea:
track with httpmodule
Visitor Real-time Session
You may try to read the performance counters listed here :
Current Anonymous Users is the number of anonymous IIS users
Current Non-Anonymous Users is the number of authorized IIS users
In my application, I have a form that users fill out, then gets approved by a manager. I have various types of forms that all use the same process, so the approval buttons are all done via a user control (which includes the functionality to update the data in the database and call the postback).
However, once I click on the "Approve" button (which is in the user control), the form information doesn't update (it still says "unapproved"). A postback is definitely happening, but not sure why the page isn't updating properly.
I can confirm that the change are being made - when I manually reload the page, it gets updated - but not on the post back.
What am I missing here?
My page:
protected void Page_Load(object sender, EventArgs e)
{
int ID;
// ensure that there's an ID set in the query string
if (Int32.TryParse(Request.QueryString["ID"], out ID))
PopulatePage(ID);
else
Response.Redirect("~/Default.aspx");
}
}
protected void PopulatePage(int ID)
{
using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
{
lblStatus.Text = wo.Workorder.status;
....
}
}
I think that the Page_Load happens before the code in the submit button. To check this just use a couple of breakpoints. So the page loads the old data since the new data are not saved yet.
You should call a method to load the data inside the OnClick method of the Approve button.
After you've submitted the changes to the database, try running db.Refresh(RefreshMode.OverwriteCurrentValues) to force the changes to be reloaded into the data context.
I have a site with multiple pages, not necessarily heirarchical. I want to query the user's identity (using AD...) whenever the user first enters the site, and create session state variables for the convenience of other pages as needed. A user could possibly enter the site without going through the default.aspx page, so I thought I'd put the code in the Master Page's code-behind.
On the assumption this is a good idea, versus some sort of static class that maintains this information, I started setting it up, but found the Master Page code-behind doesn't always seem to get fired when I enter the site. Is this a debugging phenomenon, or am I right, and the Master Page is the wrong place to put this code...?
I would recommend using the Global.asax class. You'll need to add it to your web app if it's not already there. Once you have it, you can then use the various events (session start and end, app start and end and error) to implement business logic particular to what you need exactly.
I tend to monkey around with the logged in user in the Application_PreRequestHandlerExecute event of the global.asax. This will allow you to look at the User Principle (eg - User.Identity.Name) to see who is logged in (or if they're not logged in) and do what you need to (such as set Session information for the user, etc.).
Here's a tidbit of code I've got on one .NET web app that uses the Global.asax for storing user data in the Session.
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e) {
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState) {
SetUserItem();
}
}
private void SetUserItem() {
if (Session["UserItem"] == null)
Server.Execute("~/SetSessionUserObj.aspx", true);
}
... and then the SetSessionUserObj.aspx.cs
protected void Page_Load(object sender, EventArgs e) {
string ID = User.Identity.Name;
MyUser myUser = new MyUser();
UserItem userItem = myUser.GetUserItemByID(ID);
if (userItem != null) {
Session["UserItem"] = userItem;
}
}
This is just one manner that you can go about accessing a user's identity in the global.asax. You don't necessarily have to go about doing a Server.Execute to set user data (I just did it for other reasons that fall outside the scope of this question).
Good luck.
in my project i need to upload files so i decided to use the uploader provided by asp.net ajax controls AsyncFileUPloader control.
there are four blocks. every block contains two such uploaders
so i decided to utilize the power of asp.net web user controls.
i wrapped the required form fields in my user control called DesignUploader.ascx
now i have to put the four instances of this control on my aspx page
please refer the snap below
my problem starts here i have to insert the fileurl to the database and each of the block generates unique id and id value changes after uploading the file to the server. i noticed that viewstate does not work for me in case of asyncfileuploader it clears the viewstate because it does the secret postback to the server behind the scenes. now only option left for me is to use session but when user uploads the files in two blocks one after another then filepath from second/third consecutive blocks overwrite my session. i don't know how many blocks user can use to upload the designs he may use 1 only or he may use all four.
There would be a final submit button in the bottom of the page on click of which i have to insert data to database.
so when i tried to save the data to database the session stores the value of the recently uploaded file path for all the records my problem lies here
i don't know if i was able to describe my problem in correct manner or not please excuse me if it is not clear and post comment if required.
Note: I can not change the UI because client insists for this only :(
any quick work around would be appreciated much
Thanks
Devjosh
I believe you saving file path to session in a wrong way and it's impossible to recognize where is an error without code.
All the way, in my opinion better don't persist file path in session but use client side for that purpose instead. You can add two hidden fields to DesignUploader.ascx control and set their values in UploadedComplete event handler.
public partial class DesignUploader : System.Web.UI.UserControl
{
private static readonly string AppDataPath = HttpContext.Current.Server.MapPath("~/App_Data/");
public string FirstFilePath
{
get
{
return Server.UrlDecode( FirstFilePathHiddenField.Value);
}
}
public string SecondFilePath
{
get
{
return Server.UrlDecode(SecondFilePathHiddenField.Value);
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
FirstFileUpload.UploadedComplete += FirstFileUpload_UploadedComplete;
SecondileUpload.UploadedComplete += SecondileUpload_UploadedComplete;
}
void FirstFileUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
var fullPath = Path.Combine(AppDataPath, Path.GetFileName(e.FileName));
FirstFileUpload.SaveAs(fullPath);
SaveFilePathToHiddenField(FirstFilePathHiddenField.ClientID, fullPath);
}
void SecondileUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
var fullPath = Path.Combine(AppDataPath, Path.GetFileName(e.FileName));
SecondileUpload.SaveAs(fullPath);
SaveFilePathToHiddenField(SecondFilePathHiddenField.ClientID, fullPath);
}
private void SaveFilePathToHiddenField(string fieldId, string pathValue)
{
var script = string.Format("top.$get('{0}').value = '{1}';", fieldId, Server.UrlEncode(pathValue));
ScriptManager.RegisterStartupScript(this, this.GetType(), "setPath", script, true);
}
}
Per Microsoft's ProfileInfo definition http://msdn.microsoft.com/en-us/library/system.web.profile.profileinfo.aspx, an unauthenticated profileinfo object has a username; naturally this must be keyed off of to persist/ reference profile information in a given session (I am assuming it is session-based). I'm guessing this is some guid or something, but I don't see where this is defined, created, tracked, etc. Can someone point me in the right direction?
Well... The question interested me so I've decided to do some research.
A bit of digging in documentation lead me first to Implementing a Profile Provider MSDN article, where I've found the following:
GetPropertyValues method
Takes as input a SettingsContext and a SettingsPropertyCollection
object.
The SettingsContext provides information about the user. You can use
the information as a primary key to retrieve profile property
information for the user. Use the SettingsContext object to get the
user name and whether the user is authenticated or anonymous.
...
So, the determination of whether user is authenticated or not is generally done on higher level. Anyway, I took a look at code of Microsoft's default SqlProfileProvider implementation (namely, GetPropertyValues method implementation) and found out that it calls method private void GetPropertyValuesFromDatabase(string userName, SettingsPropertyValueCollection svc) which actually has the following code:
HttpContext context = HttpContext.Current;
...
string sName = null;
if (context != null)
sName = (context.Request.IsAuthenticated ? context.User.Identity.Name : context.Request.AnonymousID);
So, if we have a non-authenticated request then a user id is taken from HttpContext.Current.Request.AnonymousID property. Searching through MSDN for this property has revealed the following page: HttpRequest.AnonymousID property (System.Web). Although it still does not describe exact algorithm of generating this ID, but it provides information on how you can override this default algorithm if you want. All you need is to overload public void AnonymousIdentification_Creating(Object sender, AnonymousIdentificationEventArgs e) method in your web application. Also this page provides some information on how AnonymousID is persisted between calls (by default it's stored in .ASPXANONYMOUS cookie).
Example code:
void Application_Start(Object sender, EventArgs e)
{
// Initialize user count property
Application["UserCount"] = 0;
}
public void AnonymousIdentification_Creating(Object sender, AnonymousIdentificationEventArgs e)
{
// Change the anonymous id
e.AnonymousID = "mysite.com_Anonymous_User_" + DateTime.Now.Ticks;
// Increment count of unique anonymous users
Application["UserCount"] = Int32.Parse(Application["UserCount"].ToString()) + 1;
}
Summary: I have not been able to answer your original question on HOW this ID is created by default but I think that last code snippet will be enough for you to override this with any algorithm you want.