How would I do this in with in nhibernate? Automatically changing fields? - c#

I linq to sql I could make a partial view and do something like this
public partial class User
{
partial void OnNameChanged()
{
UserName = StringFormatter.ToTitleCase(UserName.Trim());
}
partial void OnEmailChanged()
{
Email = Email.ToLower().Trim();
}
}
can I do something like this in nhibernate. Also if you can. Can you do something like that OnQuery or OnSave?

The best way to do that with NHibernate would be to use the property accessors directly:
public class User
{
...
private string userName;
public virtual string UserName
{
get{return StringFormatter.ToTitleCase(userName.Trim());}
set{userName = StringFormatter.ToTitleCase(value.Trim());}
}
private string email
public virtual string Email
{
get{return email.Trim().ToLower();}
set{email= value.Trim().ToLower();}
}
...
}
Since NHibernate doesn't generate the DAO, but instead just uses your existing domain object, you have complete control over get/set logic. No need for a partial (though you could set it up that way to, if you really wanted).

Related

What is the proper way to set up a domain class MongoDB/C#

I am currently making a WPF application and am now ready to add a mongo database, however I can't seem to find the best process to do this with. right now I am doing it like so:
MongoManagment.cs:
namespace MoneyManagment
{
class MongoManagment
{
public void Connect()
{
String connectionString = "mongodb://localhost";
MongoClient client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase database = server.GetDatabase("MoneyManagment"); //Connect to the database
MongoCollection<Users> _users = database.GetCollection<Users>("user"); // "user" is the collection name, "Users" is the domain class
}
}
public class Users
{
public ObjectId _id { get; set; }
public string username { get; set; }
}
}
then I try to access the data from the domain class in MainWindow.xaml.cs:
namespace MoneyManagment
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
foreach (Users user in _users.FindAll())
{
//do something with users data here
}
}
}
And I get an error here that VS can not access _users, which to an extent makes sense, the problem is though, I have tried a plethora of different ways to make that accessible and it's just not working which leads me to believe that there is a better way to go about this. Any ideas?
First, you need the variable that you want to access to be publicly visible.
public class MongoManagment
{
public MongoCollection<Users> MongoUsers {get; set;}
public void Connect()
{
....
this.MongoUsers = database.GetCollection<Users>("user");
}
then, you need to reference the object in the external class:
public MainWindow()
{
....
MongoManagement mm = new MongoManagement();
mm.Connect();
foreach (Users user in mm.MongoUsers.FindAll())
{
//do something with users data here
}
note this is a very simplistic example, and you may not want a copy of MongoManagment for every window, etc. You will still want to spend a bit of time exploring the concepts of variable lifecycles, scope....

C# sharing form data with a class

This is a kind of a newbie question. I haven't done C# programming in a while especially with creating with custom classes. I want to share some data between my forms, I was thinking of creating a class,
public class User
{
public string id;
public string name;
public User()
{
}
public User(string id, string name)
{
this.id = id;
this.name = name;
}
}
Does the class have to be in a separate file (User.cs)?
If I had the following code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
User user1 = new User("abc","cde");
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
}
How should I create the class in Form1 and how should I access it in Form2?
Typically, you separate classes out into separate files, so I would suggest making a User.cs file that contains the User class.
How you are instantiating the class in Form1 is fine, but to get the instance of the class to Form2 you need to pass it to the constructor of Form2, like this:
Form2 theForm2 = new Form2(user1);
Note: To accomplish the code above requires modifying the constructor of Form2, or in this case creating a non-default constructor, and creating a member variable to hold the User class instance, like this:
public partial class Form2 : Form
{
private User _user;
public User TheUser
{
get
{
return _user;
}
}
public Form2()
{
InitializeComponent();
}
public Form2(User theUser)
{
_user = theUser;
}
}
Now you can use the User class in Form2 by simply referencing the property TheUser.
How you distribute the classes ove files its all up to you. In this example I made you could have UserHandler.cs, User.cs, Form1.cs & Form2.cs. Hope it helps.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public static class UserHandler
{
private static List<User> Users = new List<User>();
public static void AddNewUser(User user)
{
Users.Add(user);
}
public static void RemoveUser(User user)
{
Users.Remove(user);
}
public static User GetUserById(int id)
{
if(Users.Exists(x => x.userId == id))
{
return Users.Find(user => user.userId == id);
}
return null;
}
}
public class User
{
public int userId { get; set; }
public string userName { get; set; }
public User(int id, string name)
{
this.userId = id;
this.userName = name;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var _user = new User(1,"user2252502");
UserHandler.AddNewUser(_user);
MessageBox.Show(UserHandler.GetUserById(1).userName);
Form2 form2 = new Form2();
}
}
public partial class Form2 : Form
{
public Form2()
{
MessageBox.Show(UserHandler.GetUserById(1).userName);
}
}
}
There are multiple ways of doing this. one way can be that you pass the class in constructor of Form2. like below.
public partial class Form1 : Form
{
User user1 = new User("abc","cde");
public Form1()
{
InitializeComponent();
new Form2(user1);
}
}
public partial class Form2 : Form
{
User user1;
public Form2(User u)
{
InitializeComponent();
user1 = u;
}
}
Other ways of doing this can be to expose a public property in form1 that returns User. and you access that property in Form2.
They can be in the same file. If you want to access data from Form1 in Form2, add Form1 as a parameter to the constructor of Form2. Or add it as a property in Form2 and allow it to be "set".
How should I create the class in Form1 and How should I access it in Form 2?
This depends on its use. Since your desire is to share it between forms, I am assuming you would like its scope to be class wide. Define it as a class property. Preferably above your constructor for Form1.
Does the class have to be in a separate file, User.cs If I had the following code
It does not have to be, but best practice is that it is.
How do I share it with Form2?
A. Make it a parameter of the constructor of Form2:
public partial class Form2 : Form
{
public User MyUser { get; set; }
public Form2(User user)
{
InitializeComponent();
MyUser = user;
}
}
B. Make it a public property of Form2 and set it from Form1
var frm2 = new Form2();
frm2.User = user;
I'm speaking purely from a "I think I've been down the same road you're going down" point of view.
It might be time to break down your application into some patterns. A User class is usually a special kind of entity within an application. In typical cases, it can define the attributes of a user, or it can be used to define the Identity and Claims for a particular user, or all of the above.
It would be good to make a service or utility class for your user. If any given Form, or class for that matter, in your application needs to have information about a User, your service is there to answer the call. This service could provide a CurrentUser property which would inform other classes that the currently logged in user is (null | Bob | xyz...) It can perform validation, access background utilities to cache attributes about the user. but I digress. While writing my answer, #Iker Ruiz Amauda has given a practical example of how might implement this service.
As to how to make this available across your application: it depends on the magnitude of your project. I've like Dependency Injection as mentioned by Karl Anderson. To go along with Dependency Injection would be Inversion of control (IoC). My current flavor of IoC is MEF (http://mef.codeplex.com/documentation). By defining an IUserService that is implemented by UserService, you can "Inject" this service into any form that relies on the userservice. In my current project this is achieved practically using attributes to export and import items.
For more information on Inversion of Control (I think Dependency Injection is pretty straight forward but Google is your friend on that one,) see This answer on stack overflow:
https://stackoverflow.com/a/3140/93964
or this was a decent blog entry I found while google the subject:
http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/

Entity Framework Code First, nonempty setter or getter?

I am working with an EF Code First project, and all is well. I have a simple Class, Customer. In my Customer Class I have a field I want to encrypt (Yes, I know I can encrypt at the DB level but requirements dictate I encrypt at the Domain/Code level), so I am hoping that I can do something like the following:
public class Customer
{
public int CustomerID { get; set; }
public string FieldToEncrypt { get; set { _FieldToEncrypt = MyEncryptionFunction.Encrypt(); } }
}
However, I assume that if the setter has a definition, entity framework code first may ignore that property when generating the schema. So my question is, is there a way to do EF Code First with provided getters/setters, or should I move this functionality into a constructor? Should I override one of the methods/events that happens when the Context is saving, instead?
EDIT ********************
As a note, I am using DataService to transmit the data over an OData protocol service. This automatically generates insert/update/select methods. Some of the suggestions require creating a second property, but the DataService class does not seem to pass through NotMapped properties. This throws a bit of a kink into my earlier question.
public class Customer
{
public int CustomerID { get; set; }
public string EncryptedField { get; private set; }
[NotMapped]
public string Field
{
get { return MyEncryptionFunction.Decrypt(EncryptedField); }
set { EncryptedField = MyEncryptionFunction.Encrypt(value); }
}
}

The "Model" in .Net MVC

How do data frameworks such as Linq 2 SQL, ADO.Net Data Entities and DataSets relate to the "Model" as defined by .Net MVC.
The reason I ask is I'm trying to learn the ins and outs of the .Net framework without relying on many of the tools that make it easy and hide the workings from you.
The "model" I'm building in my exploratory app is simply PostgreSQL commands to update the database. I'm purposefully not using a data "framework".
I'm finding that much of the functionality that comes as part of the .Net MVC framework isn't working for me. Stuff like UpdateModel() and anything related to ModelState doesn't seem to acknowledge what's going on.
Is much of that functionality tied to using Linq 2 SQL or ADO.Net Data Entities? If so, that's fine, I just don't quite understand the relationship yet.
Unlike Views and Controllers, there's not really any restrictions on what the Model is in an ASP.NET MVC app. It just enables you to model the data in your app and clearly and safely express your intent without having to resort to using dictionaries such as ViewData to pass data around.
In terms of the model-related functionality, I believe (not 100% sure) that it is based on having public properties on your model objects. If you call UpdateModel or its relatives, it will set public properties on the model object based on the form data etc. All it does it set properties on that in-memory object if it finds appropriate ones that match form inputs etc. You still need to include the logic to actually persist that to a database or whatever else it is you want to do.
Hope this points you in the right direction at least.
Basically your "Model" object needs to have a parameterless constructor and public get/set properties for it to function easily with the DefaultModelBinder.
Tip: I believe that if you fail to define a parameterless constructor, an empty one is inferred for you (just so you don't freak out: "ahh! i don't hav a parameterless constructor").
So this would generally work fine:
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public string Email { get; set; }
}
Figured it out. For the sake of completeness...
Ok, so there is a "minimum standard" for models in .Net.
This is NOT accepted as a model:
namespace MVCApplication.Models
{
public class Person
{
public int ID;
public string Name;
public string Title;
public string Description;
public string Phone;
public string Address;
public string Country;
public Person()
{
}
}
}
This IS accepted as a model:
namespace MVCApplication.Models
{
public class Person
{
private int _ID;
private string _Name;
...
public Person() {}
public int ID { get{ return _ID } set{ this._ID = value } }
public int Name { get{ return _Name } set{ this._Name = value } }
...
}
}
I can't say I completely understand why, but at least now I know.

Splitting up a class into sub-classes

I've got a business logic layer class containing access methods for each table in a database. As there are quite a few tables now I'd like to restructure it to group the methods by entity (for easier access when coding). So, from this:
BLL.Database MyDB = new BLL.Database();
BLL.Entity.User MyUser = Database.UserGetById(42);
to this:
BLL.Database MyDB = new BLL.Database();
BLL.Entity.User MyUser = Database.User.GetById(42);
I'd like the class to remain non-static if possible, with all the classes 'partial' too (to allow me to add additional methods to the main generated class). What are my options for achieving this? Here's the current layout:
namespace BLL
{
public partial class Database
{
// private members..
// constructor
#region User
public IQueryable<BLL.Entity.User> UserGetAll()
{
// ...
}
public BLL.Entity.User UserGetById(int UserId)
{
// ...
}
public void UserSave(ref BLL.Entity.User user)
{
// ...
}
public void UserDelete(int userId)
{
// ...
}
#endregion
// More sets of methods for other entities in database here..
}
}
Is this feasible?
namespace BLL
{
public partial class Database
{
private _User;
public User
{
if (_User == null)
{
_User = new User();
}
return _User;
}
// Other data access classes here..
}
public partial class User
{
public IQueryable<BLL.Entity.User> GetAll()
{
// ...
}
// GetById, Save & Delete methods here..
}
}
Thanks.
Aside from the use of partial, your layout looks good. I don't think partial is going to do the trick for you as far as making the classes extensible, as partial classes must all reside in the same assembly.
A better solution would likely be creating extension methods.
Yes, that is feasible. In fact I implemented something a lot like that.
Of course, after doing so I heard about Linq to SQL and we started using that instead... so you might want to check that out as another option.

Categories