how to pass structure variables - global-variables

Am having a set of structure variable in one form, i want to use that structure variable as a global variables. i need to use those structure variable in through out my whole application, how to use structure as global variable??
am using C#..

Put your structure variables as static members of a static helper class.

What you're looking for is a singleton class. Here is an example.
public class SingletonClass
{
#region Singleton instance
private static SingletonClass _instance;
public static SingletonClass Instance
{
get { return _instance ?? (_instance = new SingletonClass()); }
}
#endregion
#region Contructor
/// <summary>
/// Note that your singleton constructor is private.
/// </summary>
private SingletonClass()
{
// Initialize your class here.
}
#endregion
#region Public properties
// Place your public properties that you want "Global" in here.
public enum SomeEnumTypes
{
Type1,
Type2,
Type3
}
public int SomeMeasurements { get; set; }
public string SomeID { get; set; }
#endregion
}
So when you need this global class, just call on it like so:
var currentMeasurements = SingletonClass.Instance.SomeMeasurements;
Have fun.

Related

Moq dbContext if there are entities with jsonb (postgresql)

I try to moq my DbContext like in memory db. I use PostgreSql in my app, so I have entities with jsonb properties. For example:
[Table("examples")]
public class Example
{
/// <summary>
/// id (autogenerated by DB)
/// </summary>
[Column("id", TypeName = "bigserial")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
/// <inheritdoc/>
[Column("layout_config", TypeName = "jsonb")]
[Required]
public LayoutConfigDto LayoutConfig { get; set; }
}
[Keyless]
public class LayoutConfigDto
{
/// <summary>
/// Координата X расположения виджета
/// </summary>
public byte X { get; set; }
/// <summary>
/// Координата Y расположения виджета
/// </summary>
public byte Y { get; set; }
}
so LayoutConfigDto just a model for JSON, that doesn't need a table. And doesn't need any relation or configuration for table.
Then I create Test class:
[TestFixture]
public class ExampleServiceTests
{
private IExampleService _exampleService;
[SetUp]
public void Setup()
{
DbContextOptions<ExampleDbContext> options = new DbContextOptionsBuilder<ExampleDbContext>()
.UseInMemoryDatabase(databaseName: "InMemoryExampleDatabase")
.Options;
ExampleDbContext dbContext = new(options);
new FakeDatabaseDataGenerator().Generate(dbContext);
Mock<ILogger<ExampleService>> mock = new();
_exampleService = new ExampleService(dbContext, mock.Object);
}
[Test]
[TestCase(0)]
[TestCase(3)]
public async Task GetExampleTest(long id)
{
ExampleModel example = await _exampleService.GetExample(id);
if (id <= 0)
{
Assert.AreEqual(example, null);
return;
}
Assert.AreNotEqual(null, example);
}
}
When I run GetExampleTest it fails on Exceptions like:
System.InvalidOperationException : Unable to determine the relationship represented by navigation 'UserWidgetModel.LayoutConfig' of type 'LayoutConfigDto'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
I can't use [NotMapped] attribute on LayoutConfig field, because I need to get it from DB and with pgsql driver all works and serializes. But with in memory db it fails. How can I change my Test to make it works? Is there any other options to mock db context?
The error it returns is pretty clear; it tells you what you need to do. If you can't use the [NotMapped] attribute, you need to configure a relationship for the fields it needs

ASP.NET MVC How to avoid static variables?

recently posted about questioning how unsafe static variables are, I've since discovered I need to get rid of them. But I cannot figure out how to? Was thinking a static Get() method for each class, that returns a single instance, but then that instance would have to be declared static.
So the only way to do it, is to have the instance references (for each helper, I.E user helper.cs, imagehelper.cs etc.) is to declare them as instance properties on some sort of globally accessible class? But which class? Is there something I'm missing here?
Code below of a sample class I need to change:
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc.Mailer;
namespace MVCWebsite.Helpers
{
public class AppSettings
{
public static void OnAppInit()
{
//General
AppName = "MyApp";
DesktopBaseURLs = new Dictionary<string, string>();
DesktopBaseURLs.Add("dev", "localhost:50560");
DesktopBaseURLs.Add("test", "www.test.whatever.com");
DesktopBaseURLs.Add("live", "www.whatever.com");
MobileBaseURLs = new Dictionary<string, string>();
MobileBaseURLs.Add("dev", "m.local.whatever.com");
MobileBaseURLs.Add("test", "m.test.whatever.com");
MobileBaseURLs.Add("live", "m.whatever.com");
//Emails
EmailHostName = AppName + ".com"; //For the moment atleast
NoReplyEmailAddress = "no-reply#" + EmailHostName.ToLower();
SupportEmailAddress = "support#" + EmailHostName.ToLower();
ErrorEmailAddress = "errors#" + EmailHostName.ToLower();
//Resources
TempFileURL = "/content/temp/";
UserDataURL = "/content/user-content/";
ProfilePicturesURL = UserDataURL + "profile-pictures/";
var a = GlobalHelper.GetURLAsServerPath(ProfilePicturesURL);
var b = a;
}
//General
public static string AppName { get; set; }
public static Dictionary<string, string> DesktopBaseURLs;
public static Dictionary<string, string> MobileBaseURLs;
//Emails
public static string EmailHostName { get; set; }
public static string NoReplyEmailAddress { get; set; }
public static string SupportEmailAddress { get; set; }
public static string ErrorEmailAddress { get; set; }
//Resources
public static string UserDataURL { get; set; }
public static string TempFileURL { get; set; }
public static string ProfilePicturesURL { get; set; }
//Methods
public static void SetAppURL()
{
}
}
}
I recommend creating an interface for your AppSettings class, so that you can use it in your controllers now, and implement it in different ways as you see fit:
public interface IAppSettings
{
string AppName { get; set; }
...
}
You can then implement it immediately with your static class via a wrapper class:
public class AppSettingsWrapper : IAppSettings
{
public AppName
{
get
{
return AppSettings.AppName;
}
set
{
AppSettings.AppName = value;
}
}
...
}
Later on, you can create an implementation of IAppSettings that uses session, or cookies, or database values, or whatever. The important thing is to abstract the way you store things so that you can implement in a way that meets your needs.
The answer to you previous question clearly stated that the IDictionary was the only unsafe variable in your static method because it's not thread safe. You just need to store these variables differently. You don't need to get rid of all of your static variables. You just need to change IDictionary to something thread safe.
By the way, someone there makes a good coment about web.config
Right I think I've figured it out, they should be stored as instance variables within Global.asax.cs. This file contains your Application class which inherits from System.Web.HttpApplication. This master class is limited to one instance (of itself) per request. So if you store any references to your helpers here, you can reference them by going, MvcApplication.MyHelper.DoSomething(); Someone please correct me if this is wrong, but seems right to me. "At any single point of time, an HTTPApplication instance handles only one request, so we don't need to think about locking and unlocking of any non static members, but for static members we do require. " -from : http://www.codeproject.com/Articles/87316/A-walkthrough-to-Application-State#c

Code First Generic Repository with existing Database tables

I have a Generic Repository class using code first to perform data operations.
public class GenericRepository<T> where T : class
{
public DbContext _context = new DbContext("name=con");
private DbSet<T> _dbset;
public DbSet<T> Dbset
{
set { _dbset = value; }
get
{
_dbset = _context.Set<T>();
return _dbset;
}
}
public IQueryable<T> GetAll()
{
return Dbset;
}
}
I have an entity class Teacher, which maps to an existing table "Teacher" in my database, with exactly the same fields.
public class Teacher
{
public Teacher()
{
//
// TODO: Add constructor logic here
//
}
public int TeacherID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
I have the following code below which binds data from Teacher to a repeater control.
GenericRepository<Teacher> studentrepository = new GenericRepository<Teacher>();
rptSchoolData.DataSource = studentrepository.GetAll().ToList();
rptSchoolData.DataBind();
But I get an exception exception "The entity type Teacher is not part of the model in the current context". Do I have to do any additional work when using an existing database for code first?
You must create a context class that derives from DbContext. The class should have properties of type DbSet<T> which will give EF enough information to create and communicate with a database with default naming and association conventions. It will use properties like Student.Teacher (if any) to infer foreign key associations:
public class MyContext: DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Student> Students { get; set; }
...
}
If the defaults are not what you want, or when you've got an existing database that you want to match with the names and associations in your model you can do two (or three) things:
Override OnModelCreating to configure the mappings manually. Like when the tables in the database have those ugly prefixes (to remind people that they see a table when they see a table):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Teacher>()
.Map(e => e.ToTable("tblTeacher"));
...
}
(Less favorable) Use data annotations to do the same.
Turn it around and use Entity Framework Powertools to reverse-engineer a database into a class model including fluent mappings and a DbContext-derived context. Maybe easier to modify an existing model than to start from scratch.

How to create multiple Repository object inside a Repository class using Unit Of Work?

I am newbie to MVC3 application development, currently, we need following Application technologies as requirement
MVC3 framework
IOC framework – Autofac to manage object creation dynamically
Moq – Unit testing
Entity Framework
Repository and Unit Of Work Pattern of Model class
I have gone through many article to explore an basic idea about the above points but still I am little bit confused on the “Repository and Unit Of Work Pattern “. Basically what I understand Unit Of Work is a pattern which will be followed along with Repository Pattern in order to share the single DB Context among all Repository object, So here is my design :
IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
IPermitRepository Permit_Repository{ get; }
IRebateRepository Rebate_Repository { get; }
IBuildingTypeRepository BuildingType_Repository { get; }
IEEProjectRepository EEProject_Repository { get; }
IRebateLookupRepository RebateLookup_Repository { get; }
IEEProjectTypeRepository EEProjectType_Repository { get; }
void Save();
}
UnitOfWork.cs
public class UnitOfWork : IUnitOfWork
{
#region Private Members
private readonly CEEPMSEntities context = new CEEPMSEntities();
private IPermitRepository permit_Repository;
private IRebateRepository rebate_Repository;
private IBuildingTypeRepository buildingType_Repository;
private IEEProjectRepository eeProject_Repository;
private IRebateLookupRepository rebateLookup_Repository;
private IEEProjectTypeRepository eeProjectType_Repository;
#endregion
#region IUnitOfWork Implemenation
public IPermitRepository Permit_Repository
{
get
{
if (this.permit_Repository == null)
{
this.permit_Repository = new PermitRepository(context);
}
return permit_Repository;
}
}
public IRebateRepository Rebate_Repository
{
get
{
if (this.rebate_Repository == null)
{
this.rebate_Repository = new RebateRepository(context);
}
return rebate_Repository;
}
}
}
PermitRepository .cs
public class PermitRepository : IPermitRepository
{
#region Private Members
private CEEPMSEntities objectContext = null;
private IObjectSet<Permit> objectSet = null;
#endregion
#region Constructors
public PermitRepository()
{
}
public PermitRepository(CEEPMSEntities _objectContext)
{
this.objectContext = _objectContext;
this.objectSet = objectContext.CreateObjectSet<Permit>();
}
#endregion
public IEnumerable<RebateViewModel> GetRebatesByPermitId(int _permitId)
{
// need to implment
}
}
PermitController .cs
public class PermitController : Controller
{
#region Private Members
IUnitOfWork CEEPMSContext = null;
#endregion
#region Constructors
public PermitController(IUnitOfWork _CEEPMSContext)
{
if (_CEEPMSContext == null)
{
throw new ArgumentNullException("Object can not be null");
}
CEEPMSContext = _CEEPMSContext;
}
#endregion
}
So here I am wondering how to generate a new Repository for example “TestRepository.cs” using same pattern where I can create more then one Repository object like
RebateRepository rebateRepo = new RebateRepository ()
AddressRepository addressRepo = new AddressRepository()
because , what ever Repository object I want to create I need an object of UnitOfWork first as implmented in the PermitController class. So if I would follow the same in each individual Repository class that would again break the priciple of Unit Of Work and create multiple instance of object context.
So any idea or suggestion will be highly appreciated.
Thank you
Your IUnitOfWork interface has too many responsibilities. Each time you add a new repository, you would need to change your IUnitOfWork interface and all of its implementations.
Instead, how about something like this?
public interface IUnitOfWork
{
int SaveChanges();
}
You can then implement this interface in your Entity Framework ObjectContext or DbContext:
public MyCustomContext : DbContext, IUnitOfWork
{
// ... this class already implements the SaveChanges method
}
You can then constructor inject the unit of work into each of your repositories. AutoFac can make certain the same instance is shared among multiple repositories used within the same HttpContext:
public class PermitRepository : IPermitRepository
{
#region Private Members
private readonly IObjectSet<Permit> _objectSet;
private readonly IUnitOfWork _unitOfWork;
#endregion
#region Constructors
public PermitRepository(IUnitOfWork unitOfWork, IObjectSet<Permit> objectSet)
{
_unitOfWork = unitOfWork;
_objectSet = objectSet;
}
#endregion
public IEnumerable<RebateViewModel> GetRebatesByPermitId(int _permitId)
{
// need to implment
}
}
Then, when you constructor inject the repository into the controller, the IUnitOfWork will automatically be constructor injected into the repository.
public class PermitController : Controller
{
#region Private Members
private readonly IPermitRepository _permitRepos;
#endregion
#region Constructors
public PermitController(IPermitRepository permitRepos)
{
if (permitRepos== null)
{
throw new ArgumentNullException("permitRepos");
}
_permitRepos = permitRepos;
}
#endregion
}
Note that when querying data out of your repository, you're really not doing any work, so the IUnitOfWork interface does not apply here. It applies when inserting, updating, and deleting entities, not when selecting them.

Registering Composite Classes in Unity

in my implementation, I have an interface as: ICachingManager. I've got now one implementation. I also created a manager class as:
public class CachingManager
{
#region Members
private ICachingManager service;
#endregion
#region Constructors
public CachingManager(ICachingManager service)
{
this.service = service;
}
#endregion
#region Public Methods
public void EnCache<T>(string key, T value)
{
this.service.EnCache<T>(key, value);
}
public T DeCache<T>(string key)
{
return this.service.DeCache<T>(key);
}
#endregion
}
In case I had one implementation, then I can easily register the CachingManager class with Unity, automatically Unity resolves and injects the ICachingManager.
In case I had more than one implementation using named types, then how can I can make use of Unity? Do I need to make use of an Abstract Factory to decide on which named type to initialize?
Is it a good idea to make use of such a composite class or use directly implementations of the interface with Abstract Factory?
You don't have to create an abstract factory. You can inject a given named implementation:
public class MyClient
{
[Dependency("NamedManager")]
public ICachingManager CachingManager { get; set; }
// or in the constructor
public MyClient([Dependency("NamedManager")] ICachingManager cachingManager) {
// ...
}
}
or you can configure the container to do the same thing:
public class MyClient
{
public MyClient(ICachingManager cachingManager) {
// ...
}
}
...
void ContainerBuilder() {
...
Container.RegisterType<MyClient>(
new InjectionConstructor(
new ResolvedParameter<ICachingManager>("NamedManager")));
...
}

Resources