how to save value in prperties in place of session? - asp.net

I an using Session for storing UserName for whole project.
But it always time out before 20 min.
I want set value in properties and want to use in project but when my page is loading again its showing null value.
How can i save this value in this?
Code what i am using.
public string UserName {get; set; }
public string Password {get; set;}

Properties are a language construct (not an ASP.NET feature) and won't survive either.
You should persist the information in a database or up the session timeout.

With a public string UserName {get; set;} you don't set anything in the Session.
Use this instead:
public string UserName
{
get { return Session["UserName"] as string; }
set { Session["UserName"] = value; }
}

Related

Using Backlink feature of realm-dotnet in Xamarin.Forms App

My current employer is developing a mobile app using Xamarin.Forms and Asp.net mvc on the backend. I suggested to use realm in the mobile app. My manager want to see a POC(Proof of concept) app using realm with backlink feature before allowing it to be used in the app. I am working on the POC on GitHub . The documentation is very limiting and the GitHub repo of realm-dotnet don’t have good sample.
I completed the project. But unable to implement backlink. The sample app I have developed allow user to create assignees(employees) in the first page. The user can delete or edit the employees using context menu. When the user clicks on the employee name the app navigates to the ToDoListPage of that particular employee. Here the user can create ToDoItems. On this ToDoList page I want to show the ToDoItems that where assigned to that employee only.
The models were as follows:
public class Assignee : RealmObject
{
public Assignee()
{
ToDoItems = Enumerable.Empty<ToDoItem>().AsQueryable();
}
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; }
public string Role { get; set; }
[Backlink(nameof(ToDoItem.Employee))]
public IQueryable<ToDoItem> ToDoItems { get; }
}
public class ToDoItem : RealmObject
{
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; }
public string Description { get; set; }
public bool Done { get; set; }
public Assignee Employee { get; set; }
}
I am adding employee to each ToDo Item:
Item.Employee = Employee;
_realm.Add(Item);
Now I want to access the ToDoItems for the Employee:
Items = _realm.All<Assignee>().Where(x => x.Id == EmployeeId).FirstOrDefault().ToDoItems;
But this does not work. I will be grateful if someone can help me out by preferably writing code in my sample app or write the correct code in the reply.
Thank you
Firstly, Realm .NET doesn't currently support traversing properties (x.Employee.Id). Due to this, when I start the app and try to go to the ToDoListPage, the app crashes with the exception:
The left-hand side of the Equal operator must be a direct access to a persisted property in Realm
Realm supports object comparison, so we can fix this like so:
var employee = _realm.Find<Assignee>(EmployeeId);
Items = _realm.All<ToDoItem>().Where(x => x.Employee == employee);
Secondly, everything seemed fine in your code, so I dug a bit deeper and saw why it isn't working. The issue is that when we try to get all items with the code above, the EmployeeId parameter is null. Since the EmployeeId is being populated after the load logic has been triggered, we don't need to load the data in the ctor. So you can remove this code.
Finally, since you won't be loading the data in the ctor, and instead in the SetValues method, the UI needs to know, when the data has been updated, what exactly to redraw. Thus, you need to mark the collection to be Reactive too:
[Reactive]
public IEnumerable<ToDoItem> Items { get; set; }
Then, you need to change the SetValues method to use object comparison, instead of traversing:
async Task SetValues()
{
Employee = _realm.Find<Assignee>(EmployeeId);
Title = Employee.Name;
Items = _realm.All<ToDoItem>().Where(x => x.Employee == Employee);
}
To sum up - you don't need to try and load the data in the ctor, since you don't know when the EmployeeId will be set. You are already tracking when the property will change and inside the SetValues command you simply need to change the expression predicate.

its possible to retrieve data from one session? asp.net

Is this possible to retrieve data from mysql table from one session?
For example I have the Session["username"] that show me the name of the user.
but If I want to know the gender of the user, I can know it through only one session?
For example Session["username"].gender ??
instead of opening another Session for gender?
someone told me to open a class in app_code:
public class user
{
public string username { get; set; }
public string gender { get; set; }
}
But I dont know how to use it with only one session.
If its possible, show me how pls!

MonoTouch Adding Encryption in the getter/setter

I am using Sqlite database in my app with RijndaelManaged Encryption. Encryption works fine. The problem is how do i add encryption/decryption to my object class. Below is a class
public class MTBL_USER
{
[PrimaryKey, AutoIncrement]
public int UserID { get; set; }
public string LoginID { get; set; }
public string Password { get; set; }
}
I would like to add encryption/decryption logic for LoginID and Password in getter and setter. something like
public string LoginID
{
get {
EncryptDecryptController decrypt = new EncryptDecryptController ();
return decrypt.Decrypt(LoginID);
}
set {
EncryptDecryptController encrypt = new EncryptDecryptController ();
LoginID = encrypt.Encrypt (value);
}
}
This won't work. What is the best way to achieve this.
Your code has StackOverflow in it, it happens if you set LoginID from LoginID's set method.
Try adding a private field that stores the data.
private string _encryptedLoginID = null;
public string LoginID{
get{ return (new EncruptDecryptController()).Decrypt(_encryptedLoginID);}
set{ _encryptedLoginID = (new EncruptDecryptController()).Encrypt(value);}
}
Notice that a database/json/xml serializer will still see the decrypted value when they ask for it, so this is probably not going to do the trick for you.
Continue with this code and mark the LoginID property as ignored for your method of serialization; mark it internal if you can. For example:
[DataMemberIgnore]
[JsonIgnore]
[XmlIgnore]
public string LoginID{...}
Then add another property that communicates _encryptedLoginID directly
public string EncryptedLoginID {
get {return _encryptedLoginID;}
set {_encryptedLoginID=value;}
}
You can also rename LoginID to CleartextLoginID and EncryptedLoginID to LoginID if you want to keep things with less attributes.
Keep in mind that "encryption" is a term lightly tossed around without ever mentioning a very important part of crypto-security: key management. If your key is easy to recover from your code or config files this entire exercise is pointless. You'd be surprised how easy it is some times to get through such defenses. If you're only slowing your attacker down by a few hours you might as well just B64-encode :). Make sure that's not the case and that your key is properly protected by whatever the OS has to offer - don't store it in config files or code.

Edit model with virtual field

I have a Shop model which contains several fields. One of which is a virtual User one. Whenever I try to edit one entry I get an error saying that User field is required.
public class Shop
{
//..
public virtual ApplicationUser User { get; set; }
//..
}
My workaround is this:
shop.User = shop.User; //re-set the value
shop.Active = true;
db.Entry(restaurant).State = EntityState.Modified;
db.SaveChanges();
And I have to do this for all the fields. Is this the standard approach for this or is there a better way?
Change your model to this:
public class Shop
{
//..
public int UserId {get; set; }
public virtual ApplicationUser User { get; set; }
//..
}
Entity Framework will automatically detect that UserId is the foreign key for object User. You had this problem because User is virtual (lazy loaded). When changing the model without accessing or setting this property EF thinks it's empty (I assume). The foreign key UserId is not virtual, and will be fetched together with the other properties of model Shop, so you don't have to re-set the value when saving the model.
To set a new user, you now have to do for example:
myShop.UserId = 1; // instead of setting myShop.User
For more information, see this article: http://msdn.microsoft.com/en-us/data/jj713564.aspx

ASP.NET: Is it possible to keep complex object such as list<> is the session?

ASP.NET: Is it possible to keep complex object such as List<object> is the session? If yes, how to do so? I'm trying to keep a list in the session, but I'm being told that I cannot convert that List to a string.
EDIT
[Serializable]
public class Client
{
public string ClientType { get; set; }
public string ClientName { get; set; }
public string SubClientName { get; set; }
public string Project { get; set; }
public string Service { get; set; }
public string Activity { get; set; }
}
List<Client> ListOfClients;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListOfClients = new List<Client> { new Client()};
Session["ListOfClients"] = ListOfClients;//This is where the error occurs
//Cannot convert List<Client> to string...
}
}
There are many operations to execute, but the idea is to keep whatever is in the list of clients in the session.
Thanks for helping.
Yes, you can store any serializable object into a session variable. For example:
List<string> list;
Session["list"] = list;
Then to return the value:
List<string> list = (List<string>)Session["list"];
You can store anything in the session object as long as session state is in InProc mode.
Otherwise what you store has to be serialisable.
Note that the type of what you store is object, so you cast the reference that you get back:
ListOfClients = Session["ListOfClients"] as List<Client>;
Since you wrote in a comment that the error happens when compiling as opposed to at runtime, I suspect that you have some other object called Session that masks the Page.Session.
Try to hover your mouse over the Session text in Visual Studio. The tooltip should show you that Session is of type
System.Web.SessionState.HttpSessionState
If it's showing something else, you need to search both your markup (.aspx file) and code behind file to see if you have declared something else with the name/id Session and then change that name/id.

Resources