Using singleton asp.net c# - c#

I am new in programming and trying to learn singleton but stuck in somewhere.
Here is my user class:
public class User
{
private static User user;
private User()
{
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string isim;
public string Isim
{
get { return isim; }
set { isim = value; }
}
private string soyad;
public string Soyad
{
get { return soyad; }
set { soyad = value; }
}
public static User CreateUser()
{
if (user == null)
user = new User();
return user;
}
}
In my web form I tried this:
User myuser = User.CreateUser();
to create an object but it gives me an error like there is nothing as CreateUser()..What am I doing wrong

All you have to do is like following:
You have to modify The User class to make it like this
public class User
{
public int Id { get; set; }
public string Isim { get; set; }
public string Soyad { get; set; }
public class User(){}
public User(int id, string isim, string soyad)
{
Id = id;
Isim = isim;
Soyad = soyad;
}
}
Then you implement Singleton (user buisiness logic) class like this
using System;
public sealed class UserBusiness
{
private static volatile UserBusiness instance;
private static readonly object syncRoot = new Object();
private UserBusiness() { }
public static UserBusiness Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new UserBusiness();
}
}
return instance;
}
}
public void AddUser(User userToAdd)
{
//TODO use your ORM or whatever to acces database and add the user
//for example if you use entityFramework you will need to do
//Context.Customers.Add(user)
//Context.SaveChanges();
//Just For Example
}
}
There are many implementation of singleton like mentioned in this MSDN article
and finally in your webForm Code you put the following :
var newUser = new User(1, "user1Isim", "user1Soyad");
UserBusiness.Instance.AddUser(newUser);
After All, there are many ways to do this, depends on your needs. I found this as the simpliest way to explain.

Related

I want to create a register method and store it in list, is this approach fine? C#

Hi there I am trying to create a terminal based application in C#. However I am getting confused. I have a list in memberrecord class, User is the parent class whereas admin & ProjectMember are its children. I want to be able to register a projectmember object by getting inputs from user; I want the new registered projectmember to be added in the list in memberrecord.
In the admin class I want to check if the register method is working fine and it is printing out the users list.
When I try to code it out and create a register method in User Parent class and try to print it, it is not printing and not showing up.
In which class should I create the regiter method? And also the print method?
public class UserRecord
{
private List<User> _users;
public UserRecord()
{
_users = new List<User>();
}
public List<User> Users
{
get { return _users; }
set { _users = value; }
}
public void AddUser(User u)
{
_users.Add(u);
}
public int NoOfUser()
{
return _users.Count;
}
public void PrintUser()
{
foreach (User u in _users)
{
Console.WriteLine(u.Id + u.Name);
}
}
public void RegisterUser()
{
ProjectMember projectMember = new ProjectMember();
System.Console.WriteLine("Enter ID:");
projectMember.Id = Convert.ToInt16(Console.ReadLine());
System.Console.WriteLine("Enter Name:");
projectMember.Name = Console.ReadLine();
System.Console.WriteLine("Type of member");
int input;
input = Convert.ToInt16(Console.ReadLine());
if (input == 1)
{
projectMember.MemberType = MemberType.Manager;
}
else
{
projectMember.MemberType = MemberType.Member;
}
Console.WriteLine(projectMember.Id + projectMember.Name);
UserRecord userRecord = new UserRecord();
userRecord.AddUser(projectMember);
}
}
and enum MemberType:
public enum MemberType
{
Manager, Member
}
And ProjectMember class:
public class ProjectMember : User
{
private MemberType _memberType;
public MemberType MemberType
{
get { return _memberType; }
set { _memberType = value; }
}
public ProjectMember(int id, string name, MemberType memberType) : base(id, name)
{
_memberType = MemberType;
}
public ProjectMember(){ }
}
and Admin class:
public class Admin : User
{
public Admin(int id, string name) : base(id, name)
{ }
}
and User class:
public abstract class User
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public User(int id, string name)
{
_id = id;
_name = name;
// _users = new List<User>();
}
public User(){ }
}
and Program class:
class Program
{
public static void Main(string[] args)
{
UserRecord userRecord = new UserRecord();
userRecord.RegisterUser();
userRecord.NoOfUser();
userRecord.PrintUser();
}
}
I am developing it further along. So I know I have to work in while loop in the main, but I wanted to test it along the way

Builder Design Pattern C#

there is a concept about inheritance which I do not quite understand.
I have a
protected DeveloperReport DeveloperReport; // Field
Wouldn't PersonalInfoBuilder be able to access that field ?
If yes,
public PersonalInfoBuilder MyPersonalInfo => new PersonalInfoBuilder(DeveloperReport);
Why do I still have to pass the DeveloperReport(field) into PersonalInfoBuilder constructor, when I can
just modify the protected DeveloperReport field by calling new PersonalInfoBuilder(), instead of
new PersonalInfoBuilder(DeveloperReport)?
And, how the concept of "return this" return the changes made to DeveloperReport(field) back to
DeveloperReportBuilder?
Thanks !
class DeveloperReport
{
// Properties
public int Id { get; set; }
public string Name { get; set; }
public DeveloperLevel Level { get; set; }
public int WorkingHours { get; set; }
public int HourlyRate { get; set; }
// Methods
public double CalculateSalary() => WorkingHours * HourlyRate;
}
class DeveloperReportBuilder
{
protected DeveloperReport DeveloperReport;
public PersonalInfoBuilder MyPersonalInfo => new PersonalInfoBuilder(DeveloperReport);
public DeveloperReportBuilder()
{
DeveloperReport = new DeveloperReport();
}
// return developer report.
public DeveloperReport Build() => DeveloperReport;
}
class PersonalInfoBuilder : DeveloperReportBuilder
{
public PersonalInfoBuilder(DeveloperReport report)
{
DeveloperReport = report;
}
public PersonalInfoBuilder()
{
}
public PersonalInfoBuilder NameIs(string name)
{
DeveloperReport.Name = name;
return this;
}
public PersonalInfoBuilder IDis(int id)
{
DeveloperReport.Id = id;
return this;
}
}
You only have to pass the report instance if you want to have both instances of DeveloperReportBuilder and PersonalInfoBuilder have acces to the same instance of DeveloperReport.
Inheritance will not copy the instance values.

Static Nested Type

So i have nested type classes that go something like this:
namespace MyNamespace
{
public class User
{
private int id = 0;
private string userId = "";
private string userPassword = "";
public int Id
{
get { return id; }
set { id = value; }
}
public string UserId
{
get { return userId; }
set { userId = value; }
}
public string UserPassword
{
get { return userPassword; }
set { userPassword = value; }
}
public User()
{
id = 0;
userId = "";
userPassword = "";
}
public static class SignonInfo
{
private static string sesstoken = "";
private static DateTime sessstart = new DateTime();
public static string SessToken
{
get { return sesstoken; }
set { sesstoken = value; }
}
public static DateTime SessStart
{
get { return sessstart; }
set { sessstart = value; }
}
}
}
}
My end goal here was to be able to access the nested static class like this:
User user = new User();
string token = user.SignonInfo.SessToken;
I'm trying to avoid instantiating the class like this:
User.SignonInfo user = new User.SignonInfo()
I need to be able to access properties of both User and SignonInfo classes.
Could someone help me to get on track or slap me about and tell me i'm doing it all wrong?
TIA
The problem is that it's a static class, so an "instance" doesn't have access to it. This is a good thing, as it prevents global state from masquerading as a well-encapsulated object.
I'd suggest making the nested class non-static, and having theUser class create an instance as needed by the caller (maybe add a public SignonInfo GetSignonInfo() method.)
You are trying to access your nested class as if it were a member of the instance of the outer class.
Change
string token = user.SignonInfo.SessToken;
to
User.SignonInfo.SessToken;
Note, that you do not get an instance of the static nested type per outer instance, there is only one for the entire outer class.

Entity framework can't add with singleton

My persons class:
public class User
{
public int Id { get; private set; }
public string Isim { get; set; }
public string Soyad { get; set; }
public User(string isim, string soyad)
{
Isim = isim;
Soyad = soyad;
}
}
My UserBusiness class:
public sealed class UserBusiness
{
JuqueryDbEntities entity = new JuqueryDbEntities();
private static volatile UserBusiness instance;
private static readonly object syncRoot = new Object();
private UserBusiness() { }
public static UserBusiness Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new UserBusiness();
}
}
return instance;
}
}
public void AddUser(User userToAdd)
{
entity.PersonelTable.Add(userToAdd);
entity.SaveChanges();
}
}
And lastly my webform codebehind onclick of a login button:
protected void Button1_Click(object sender, EventArgs e)
{
string isim = TextBox1.Text;
string soyad = TextBox2.Text;
var newUser = new User(isim, soyad);
UserBusiness.Instance.AddUser(newUser);
}
Here is my problem: I get an error in AddUser method of my UserBusiness class.
An error in 'entity.PersonelTable.Add(newUser);' line says
'The best overload method match for 'System.Data.Entity.DbSet.Add(SuperQquery.PersonelTable)' has some invalid arguments.' What am I doing wrong(Btw my Id is autoincrement so I am not setting it any value.)
your problem here is that the method Add of System.Data.Entity.DbSet does simply not take argument of type user.
like mentioned in the error
System.Data.Entity.DbSet.Add(SuperQquery.PersonelTable)' has some
invalid arguments
it takes objects of type SuperQquery.PersonelTable
So what you need to do is change AddUser method
public void AddUser(User userToAdd)
{
SuperQquery.PersonelTable pt = new SuperQquery.PersonelTable();
pt.FieldName1 = userToAdd.Isim;
pt.FieldName2 = userToAdd.Soyad;
entity.PersonelTable.Add(pt);
entity.SaveChanges();
}
where FieldName are names of columns in the table of the database
EDIT: if this works, we can say that you made a conversion of type user to type SuperQquery.PersonelTable the way you can insert data in database, but the best way here is to change the class User by a new class PersonelTable with the same logic. No need to do a conversion.

Creating connection string with dependency injection using MVVM Light

I'm writing login window using WPF, MVVM and dependency injection patterns. My problem is that I must create connection string using login and password which user writes in my login form and I don't know how to do it according to good practice. Object is created by SimpleIoc class and I pass part of connection string like database adress and port during initialization. When user write his login and password I need to pass this data to database manager to create full connection string. I don't want to pass login and password every time when some function is called to connect part of connection string with user and password. I can create function in interface like Initialize but in my point of view that it isn't good idea and I think there is better way to do it.
Here is sample how I do it:
public interface ILoginService
{
bool SomeAction(string parameter);
}
public class LoginService : ILoginService
{
private string _connectionString;
public LoginService(string connectionStringPart)
{
_connectionString = connectionStringPart;
}
public bool SomeAction(string parameter)
{
//Create connection, execute query etc.
return true;
}
}
public class MainViewModel : ViewModelBase
{
private ILoginService _loginService;
private string _login;
public string Login
{
get { return _login; }
set
{
_login = value;
RaisePropertyChanged("Login");
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
_password = value;
RaisePropertyChanged("Password");
}
}
public MainViewModel(ILoginService loginService)
{
_loginService = loginService;
}
private RelayCommand _loginCommand;
public ICommand LoginCommand
{
get { return _loginCommand ?? (_loginCommand = new RelayCommand(ExecuteLogin)); }
}
private void ExecuteLogin()
{
//And here I must add login and password to _loginService but I don't want to do it by passing them to SomeAction method
_loginService.SomeAction("some parameter");
}
}
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<ILoginService>(()=>{return new LoginService("Server=myServerAddress;Database=myDataBase;");});
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
How About:
public interface ILoginService
{
bool SomeAction(string parameter);
string Password {set; }
string UserName {set; }
}
public class LoginService : ILoginService
{
private System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
private string _connectionString
{
get
{ return builder.ConnectionString;}
}
public LoginService(string connectionStringPart)
{
_connectionString = connectionStringPart;
}
public string Password
{
set { builder["Password"] =value; }
}
public string UserName
{
set { builder["user"] =value; }
}
public bool SomeAction(string parameter)
{
//Create connection, execute query etc.
return true;
}
}
public class MainViewModel : ViewModelBase
{
private ILoginService _loginService;
private string _login;
public string Login
{
get { return _login; }
set
{
_login = value;
_loginService.UserName = value;
RaisePropertyChanged("Login");
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
_password = value;
_loginService.Password= value;
RaisePropertyChanged("Password");
}
}
public MainViewModel(ILoginService loginService)
{
_loginService = loginService;
}
private RelayCommand _loginCommand;
public ICommand LoginCommand
{
get { return _loginCommand ?? (_loginCommand = new RelayCommand(ExecuteLogin)); }
}
private void ExecuteLogin()
{
_loginService.SomeAction("some parameter");
}

Categories