Session State MVC3 - c#

I am having a problem I can not find a tutorial or some code where I am able to do some session state. For example I would like to create a application where when a user logs in, he or she can only view there information for example a student viewing his grades an no other student can see that information. I have achieved this in VB 2008 last year but need help in MVC3 as it is not the same as the language as i am using C#. In vb 2008 i achieved this connecting a table from the ASP.net database (users) and joined to my employee table by a foreign key. And added the following code:
Session("ID") = objUser
Dim db As New DataClassesDataContext
Dim info = From a In db.tblCourses _
Where a.CourseTitle = ddlCourseName.SelectedItem.Value _
Select a.CourseId Order By CourseId Descending
crseID = info.FirstOrDefault()
Session("Course") = crseID
sdsAddStudent.Insert()
FName.Text = ""
LName.Text = ""
Address.Text = ""
ddlCourseName.SelectedIndex = 0
Session("UserID2") = objUser
Session("RoleID2") = "f13b9bf3-593d-4170-bfaa-bc43655773e2"
sdsRoleStudent.Insert()
I know VB is different to C# MVC3 as this is 2008 and not MVC3 am just showing this code so people know that I am not after free code and have tried to make an effort which has not succeed.
Thank You For Your Kind Help People

I'm not clear what exactly are you trying to achieve.
If you want to limit users access exclusively to the data that belongs to them, you need to have this data related their IDs in Users table. There is very little that you have told about table structure, but I think it is safe to assume that you have Courses table and something like UsersInCourses that would map many users to a single Course. All you would have to do is to select courses have User's Id assigned to them. To get currently logged in user you just have refer to
User.Identity.Name
in your application's code.
So let's assume your class is cooking reciepe :
public class Recipe
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string PreparationInstructions { get; set; }
public DateTime CreationDate { get; set; }
}
and you want to have an Action that returns recipes for currently logged in user
public ActionResult ShowMyRecipes()
{
var myRecipes = dbContext.Recipes.Where(recipe => recipe.Author.Equals(User.Identity.Name)).ToList();
return View(myRecipes);
}
public ActionResult CreateRecipe(Recipe recipe)
{
// set Author to curently logged in user's key
recipe.Author = Membership.GetUser().ProviderUserKey;
// save changes
dbContext.Recipes.Add(recipe);
}

Related

Android Firebase - add authenticated user into database

Ok, so I am building xamarin.android applicationon in Visual Studio and there is quite a lot of questions of this type, but I really didn't find anything regarding xamarin.android, everything is Java based. I tried following those tutorials and answers but there was always something missing or not working on Xamarin android.
I have made authentication and it works great, no problems there. And i tried storing user information (info that user types in while registering) into database. It kind of worked, but with one problem. Here is code:
public void OnComplete(Task task)
{
if (task.IsSuccessful)
{
Toast.MakeText(this, "Successful", ToastLength.Long).Show();
FirebaseUser user = FirebaseAuth.GetInstance(app).CurrentUser;
id = user.Uid;
CreateUser();
buttonSignIn.PerformClick();
progressBar.Visibility = ViewStates.Invisible;
}
else
{
//something
}
}
And here is CreateUser() method:
private void CreateUser ()
{
Account user = new Account();
user.uid = id;
user.name = signup_inputName;
user.lastName = signup_inputLastName;
user.email = signup_inputEmail;
user.phone = signup_inputPhoneNumber;
var firebase = new FirebaseClient(FirebaseURL);
var item = firebase.Child("users").PostAsync<Account>(user);
}
Here is Account class code:
public class Account
{
public string uid { get; set; }
public string name { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
This code stores user information under "users" node in database. But there is one more node under "user" with some random value and below are information about user (including uid). Here is output:
- Users
-LBGFtYFTfD3l1hmwHVn
email: "testuser#test.com"
lastName:"peric"
name: "pero"
phone: "12321"
uid: "18puc5CzSZfzbdflzekzNCHGHR62"
So, my question is, shouldn't this random value below "users" node be uid? If yes, how to set it that way?
I tried with this:
Account user = new Account();
user.uid = id;
user.name = signup_inputName;
user.lastName = signup_inputLastName;
user.email = signup_inputEmail;
user.phone = signup_inputPhoneNumber;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users").Child(uid).SetValue(user)
But that didn't work, I was getting this error:
Firebase No properties to serialize found on class
Even though I have set public getters and setters in users class.
I need to get that user info and show it on some places in my app, but I just can't get it to work. This is my first time using Firebase and I am used to SQL database so this is really confusing to me. Also, there is very little information online about xamarin.android and firebase, plus I am actually new to programming in general. Any help would be appreciate. This is my last try before switching to SQL online database.
When you call PostAsync the client creates a new child node under the location that you call it on. This is similar to the HTTP POST verb, and the push() method in most other Firebase SDKs.
To write data to a location that you exactly specify, use PutAsync:
var item = firebase.Child("users").Child(uid).PutAsync<Account>(user);
See the example from the Readme of Firebase.Xamarin.

c# filter database results using EF similar to SQL WHERE Clause

I've connected to my database using Entity Framework and am building my first MVC app for use in a web page.
I can get the controller to populate public strings in my models with no problem... the issue I'm having is that I can't figure out how to filter responses from my database.
I expect to have only one item returned which I will display in the view with #Model.BusinessUnit
Here's my Model Class for the database table:
public partial class TBL_Wholesale_UWS_BusinessUnits
{
public int PrimaryID { get; set; }
public string BusinessUnit { get; set; }
public string Status { get; set; }
}
Here's what I have in my controller:
public ActionResult test(int PrimaryID)
{
var testing = new TBL_Wholesale_UWS_BusinessUnits();
// maybe putting new is the wrong thing to do as that would be wiping the class? IDK
return View(testing);
}
As you can see, the PrimaryID is passed to the controller via the querystring and this is recognised without issue, but I'm at a loss as to where to add the filter, I assumed it would be something like...
var testing = TBL_Wholesale_UWS_BusinessUnits.Where(TBL_Wholesale_UWS_BusinessUnits.PrimaryID = PrimaryID);`
but Visual Studio is telling me in no uncertain terms that this this wrong.
Had this been classic asp I would have just made a record set and used the where clause in SQL, but as this is built with the Entity Framework to do my connecting I don't really know where to start.
Any help would be greatly appreciated.
If you are only trying to return that one specific object to the view.. then you need to find that int PrimaryID in the database and retrieve that specific record.
What you are doing is simply creating a new instance of the TBL_Wholesale_UWS_BusinessUnits class which is empty.
Try this:
public ActionResult test(int PrimaryID)
{
var testing = db.TableName.Find(PrimaryID);
// db = Whatever the variable holding your connection string is.. maybe DbContext
// TableName = Whatever table in your database that holds the record you want
// This will return the specific object that you are looking for
return View(testing);
}
I hope this helps!

Accessing a list of objects & how to claim a object for the fatest request

I'm developing an Asp.net mvc project:
There is a List store all the online Pupils
There are few methods:
- Login(Pupil p): if login ok, p will be added to Pupils list
- Logout(Pupil p): if logout ok, p will be removed out of Pupil list
-> 2 methods have a same potential issue is "cannot modify list while modifying" because there are a lot of Pupil login to system and logout at the same time. While adding a pupil the other are being removed from Pupils list -> exception throws
I tried to use lock to lock a list while modifying (insert/remove) but is it a good way to do? Do you have some better idea?
The last method is Claim(Book b)
Administrator put some books in the GUI and all the logged Pupils can see these books. They can claim any book they want. The fastest Pupil claimed is will own that book. So how can we know the fastest claimer? While updating a data row. At the same time there are many books are claimed by many pupils. But only one fastest pupil can own a particular book after claiming successfully
Do you have a solution for this? This solution just like you put a command to buy stocks. The fastest guy will own the stocks
Remember that there are many pupils will do the same thing at the same time. So we have to make sure that system works properly and exactly
Thanks you in advance,
Best regards
The issue I see here is that your design assumes that the application is always on, and that the lists are the absolute truth about who has what book. What happens when the server is reset? What if your library gets big enough to need a second server to the application?
You need to preserve your lists in a database or some other sort of persistent medium. Holding the lists in memory will give you a read/write buffer, but the lists must be populated from the persistence layer of your library database.
using System;
using System.Collections.Concurrent;
namespace TestArea
{
public class Pupil
{
public Guid Id { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
}
public class Book
{
//Supports having more than one ISBN in the library... We may have more than one To Kill a Mockingbird in our school library
public Guid Id { get; set; }
public string ISBN { get; set; }
}
public class SchoolLibrary
{
private ConcurrentDictionary<Guid, Pupil> Pupils { get; set; }
private ConcurrentDictionary<Guid, Book> Books{ get; set; }
private ConcurrentDictionary<Guid, Guid> CheckOuts { get; set; }
public Pupil Login(string userName, string password)
{
//Call repository to authenticate pupil into library system
//Mocked return assuming password check success
var id = Guid.NewGuid();
return Pupils.GetOrAdd(id, (i) =>
{
//Replace with function to get student info
return new Pupil
{
Id = i,
Name = "Bac Clunky",
UserName = userName
};
});
}
public bool CheckOut(Guid pupilId, Guid bookId)
{
//If book exists
if (Books.ContainsKey(bookId))
{
Guid currentOwner;
//...is not currently checked out by anyone
if (CheckOuts.TryAdd(bookId, pupilId))
{
return true; //book is now checked out
}
if (CheckOuts.TryGetValue(bookId, out currentOwner))
{
return currentOwner == pupilId; //returns true if pupil already has the book, false if another student has it
}
}
return false; //all other cases fail to check out book
}
}
}

How to only display 4 most recently added database records?

I have run through the MVC3 Razor tutorial on ASP.Net, and and have started trying adapt it a bit to work with a small web project of my own.
What I have done so far is create a section that will add two fields to a new database record. A "News_Item" and a "News_Date" field.
Then when displaying this data on a separate page I only want to display the 4 most recently added records.
My View code (below) displays all entries in the database no problem, but I'd like to amend as stated above so it only displays the 4 most recent records. How would I go about doing this please? I am a beginner, and have no real prior experience with development.
In my Controller I have the following code for "Get":
public ViewResult Index()
{
return View(db.News_Entries.ToList());
}
and just in case it is needed, here is the Model code:
namespace dale_harrison.Models
{
public class News
{
public int ID { get; set; }
public string News_Entry { get; set; }
public DateTime News_Date { get; set; }
}
public class NewsDBContext : DbContext
{
public DbSet<News> News_Entries { get; set; }
}
}
Many thanks for any help.
Change your Actions code
public ViewResult Index()
{
return View(db.News_Entries.OrderByDescending(n => n.News_Date).Take(4).ToList());
}
you should read linq to entity tutorials
The following LINQ query:
var latest4 = db.News_Entries.OrderByDescending(n => n.News_Date).Take(4);
should be converted to the following SQL query:
select top 4 *
from news
order by date desc

get list from based on another list

I asked this question earlier, but I over simplified it, and I still don't know how to do it in a better way than I'm doing (for).
I got two lists.
One, a list of facebook friends, a simple object, consider facebook.id the only property.
Second, a list of users, it's a more complex object, because each user gets a lists of providers inside (facebook, twitter, etc), but the providers list can be null, and if not null, not necessarily the provider is a facebook one. So:
public class EFacebook
{
public long Id { get; set; }
}
public class EUser
{
public long Id { get; set; }
/// <summary>
/// Nullable
/// </summary>
public List<EProvider> EProviders { get; set; }
}
public class EProvider
{
public enum EnumProviderType
{
Facebook = 2,
Twitter = 3
}
public EnumProviderType ProviderType { get; set; }
public string Id { get; set; }
}
What I need is to filter the facebook list to get all the facebook friends that are users and get all the facebook friends that are not users.
Suppose that List<EFacebook> fbList is the first list and List<EUser> usersList is the second list.
You can do something like this:
fbList.Where(x=>usersList.Select(x=>x.Id).Contains(x.Id)) ==> this will return the list of facebook entities that are users.
The second list is the difference between this fbList and this one.
Let me know if I understood the question correctly!
Tamash
Assuming this:
List<EFacebook> listEFacebookFriends = new List<EFacebook>();
List<EUser> listEUsers = new List<EUser>();
Then you can get a list of all Facebook friends that are users here:
var listEUsersOnFacebook = from user in listEUsers
let fbProviders =
from provider in user.EProviders
where provider.ProviderType == EProvider.EnumProviderType.Facebook
select provider.Id
where fbProviders.Count() > 0
select user.Id;
// this next call will get facebook friends that are users
var friendsOnFacebook = listEFacebookFriends.Where(x =>
listEUsersOnFacebook.Contains(x.Id));
And here you can get your Facebook friends that are NOT users:
var listEUsersNotOnFacebook = from user in listEUsers
let fbProviders =
from provider in user.EProviders
where provider.ProviderType == EProvider.EnumProviderType.Facebook
select provider.Id
where fbProviders.Count() == 0
select user.Id;
// this call will get facebook friends that are not users
var friendsNotOnFacebook = listEFacebookFriends.Where(x =>
listEUsersNotOnFacebook.Contains(x.Id));

Categories