How to allow client pass my object through webservice? - asp.net

Sorry if this is stupid question, because I'm a bit confused about .NET remoting and distributed object.
I want to write a webservice, and in one of its methods, I want user to pass one my object's instance as parameter. It will greatly reduces number of parameters, and help user call this method more effectively. I create some class, but when distributing them to client, only class name remains, all properties and methods are gone, just like this
public class CameraPackages
{
private readonly List<CameraPackage> _packages;
public CameraPackages()
{
_packages = new List<CameraPackage>();
}
public void AddNewCamera(CameraPackage package)
{
_packages.Add(package);
}
public void RemoveCamera(CameraPackage package)
{
if(_packages.Contains(package))
_packages.Remove(package);
else
throw new ArgumentException();
}
}
into this: (in Reference.cs)
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3082")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/")]
public partial class CameraPackages {
}
How can I do to allow user use my object?
Thank you so much.

Web Services will only serialise public properties, so you can't do that (in that way) using web services.
You will need to manage your list of objects client side, then send the data in a transfer object (a class with just properties).
Have a look at this.

Related

How to decorate objects created by a custom factory using .NET Core DI?

Given I have a factory class responsible for constructing instances of a certain service that has constructor parameters that can only be resolved at runtime, is there a way to leverage container-driven decoration?
Consider the following class which relies on a parameter that is only defined at runtime:
interface IFooService
{
void DoServicyStuff();
}
class MyFooService : IFooService
{
public MyFooService(string somePeskyRuntimeArgument)
{
this.peskyValue = somePeskyRuntimeArgument;
}
public void DoServicyStuff()
{
// do some stuff here with the peskyValue...
}
}
Since the value can only be provided at runtime, we need to move away from the constructor injection and into a method-level parameter passing. This is commonly achieved using a factory implementation like this:
interface IFooServiceFactory
{
IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter);
}
class FooServiceFactory : IFooServiceFactory
{
public IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return new MyFooService(heyItsNowAMethodLevelPeskyParameter);
}
}
While this works fine if the intent is to just abstract away the construction of the service, it poses a challenge to decorate the IFooService instance.
For scenarios where no runtime parameter is involved, this can be easily achieved by tapping into the container to provide our service for us. The example below uses the Scrutor library to decorate the interface with a logging decorator implementation:
class FooServiceFactory : IFooServiceFactory
{
private readonly IServiceProvider serviceProvider;
public FooServiceFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider
}
public IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return this.serviceProvider.GetRequiredInstance<IFooService>();
}
}
...
services
.AddTransient<IFooService, MyFooService>()
.AddTransient<IFooServiceFactory, FooServiceFactory>()
.Decorate<IFooService, LoggingFooService>();
But since MyFooService takes a primitive value as an argument, we cannot rely on GetRequiredService<T> to obtain the instance, as it will fail to find "a registration for string" when building the concrete class.
Similarly, changing the factory to rely on ActivatorUtilities's .CreateInstance or .CreateFactory methods will end up creating the objects while completely ignoring the container registrations, thus leaving us without any decorator.
I know I have at least 2 options to decorate the objects manually, namely:
Using the factory itself to manually create the decorator:
public IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return new LoggingService(
new MyFooService(heyItsNowAMethodLevelPeskyParameter));
}
Using a factory decorator to inject a decorator after the instance is created:
abstract class FooServiceFactoryDecorator : IFooServiceFactory
{
private readonly IFooServiceFactory fooServiceFactory;
protected FooServiceFactory(IFooServiceFactory fooServiceFactory)
{
this.fooServiceFactory = fooServiceFactory;
}
public virtual IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return this.fooServiceFactory.CreateService(heyItsNowAMethodLevelPeskyParameter);
}
}
class LoggingFooServiceFactory : FooServiceFactoryDecorator
{
private readonly IFooServiceFactory fooServiceFactory;
public FooServiceFactory(IFooServiceFactory fooServiceFactory)
{
this.fooServiceFactory = fooServiceFactory;
}
public override IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return new LoggingFooService(
this.fooServiceFactory.CreateService(heyItsNowAMethodLevelPeskyParameter));
}
}
...
services
.AddTransient<IFooServiceFactory, FooServiceFactory>()
.Decorate<IFooServiceFactory, LoggingFooServiceFactory>()
Neither of these allows me to directly use .Decorate on top of the service interface. The first option works but is heavily coupled (meaning I'd have to keep changing it if I want to add other decorators into the mix), while the second version is less coupled, but still forces me to writing one factory decorator per service decorator and thus leads into a much more complex solution.
Another pain point is dependencies on the decorators themselves (for example, ILogger<T> on the LoggingFooService), which I could potentially solve by leveraging ActivatorUtilities to create the decorators instead of newing them up manually.
I could also potentially generalize the "factory decorator" so that the decoration function is parameterized and thus the class can be reused, but it is still very convoluted and hard to maintain, while also not providing as good a syntax for consumers to add new decorators.
class DecoratedFooServiceFactory<TDecorator> : FooServiceFactoryDecorator
where TDecorator : IFooService
{
private readonly IFooServiceFactory fooServiceFactory;
private readonly IServiceProvider serviceProvider;
public FooServiceFactory(
IFooServiceFactory fooServiceFactory,
IServiceProvider serviceProvider)
{
this.fooServiceFactory = fooServiceFactory;
this.serviceProvider = serviceProvider;
}
public override IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return ActivatorUtilities.CreateInstance<TDecorator>(
this.serviceProvider,
this.fooServiceFactory.CreateService(heyItsNowAMethodLevelPeskyParameter));
}
}
...
services
.AddTransient<IFooServiceFactory, FooServiceFactory>()
.Decorate<IFooServiceFactory, DecoratedFooServiceFactory<LoggingFooService>>()
And finally, if I ever want to move away from using a factory and want to change to using the service directly, this will cause a significant setup change where I'd then have to configure all the decorators again in the container directly instead of just removing the factory registration as one normally would do.
How can I use a factory like this, while still keeping the capability of configuring decorators at the container level using the simple Scrutor syntax?
Ok, a couple of disclaimers first:
I agree with Steven here in that this looks like an anti-pattern and you will probably be better off redesigning your code to not require run-time values on service construction.
I additionally want to caution against using scrutor-like Decorate. While much less confident in this than in the first point, I believe hiding logging in decorators is much less convenient in the long run than it seems at first. Or at least that's what I saw after about a year of trying them out.
That said, let's see what can be done.
First, let's put some constraints on where the value is coming from. Specifically, let's say we can have a service providing that value, that looks like this:
public interface IValueProvider
{
string Get();
}
This actually allows us to have quite a bit of range. Implementation of that interface can:
Get value from external API - once or periodically in the background. It can even call it every time Get is called, but this is a very bad idea, as it will make construction asynchronous.
Get value that is stored in memory and allow some other service to update it. Say, expose a 'configuration' endpoint where a user can set a new value every once in a while.
Calculate the value based on some algorithm of your choice.
Once you have this service, you can register it like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IValueProvider, AwesomeValueProvider>();
services.AddSingleton<IFooServiceFactory, FooServiceFactory>();
services.AddTransient<IFooService>(sp =>
{
var factory = sp.GetRequiredService<IFooServiceFactory>();
var valueProvider = sp.GetRequiredService<IValueProvider>();
return factory.Create(valueProvider.Get());
});
}
Hope this helps

Data Transfer Object, Business Object, Domain Object or something else?

In database I have table: Notes and table Comments. In my solution I have 3 projects: DAL, BLL and Web.
I need to show a user notes with comments which aren't set as spam so I have created in DAL project that class:
public class NotesWithComments
{
public Notes Note { get; set; }
public IEnumerable<Comments> Comments { get; set; }
}
I use above class in each project: DAL, BLL and Web. Is this class Data Transfer Object, Business Object, Domain Object or what?
In a repository class I have that query:
public class NotesRepository
{
DatabaseContext context;
public NotesRepository(DatabaseContext context)
{
this.context = context;
}
public IQueryable<NotesWithComments> GetNotesWithNoSpamComments()
{
IQueryable<NotesWithComments> notesWithNoSpamComments = context.Notes.Include(x => x.Comments).OrderByDescending(x => x.CreateDate)
.Select(x => new NotesWithComments
{
Note = x,
Comments = x.Comments.Where(y => y.IsSpam == false).OrderBy(y => y.CreateDate)
});
return notesWithNoSpamComments;
}
}
In BLL project I use the method from the repository class:
public class NotesService
{
private readonly IUnitOfWork _unitOfWork;
public NotesService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IEnumerable<NotesWithComments> GetNotesWithComments()
{
IQueryable<NotesWithComments> result = _unitOfWork.NotesRepository.GetNotesWithNoSpamComments();
return result;
}
}
And in Web project I use the method form the service class:
public ActionResult Index()
{
List<NotesWithComments> result = _notesService.GetNotesWithComments();
return View(result);
}
Since it neither exposes any behavior (properties or getters/setters don't qualify) nor encapsulates its structure (again, properties or getters/setters that do nothing but expose the underlying data don't qualify) it is no object at all.
No matter if the language you use calls it an object or not. It is just a data structure (which is perfectly fine if you only want to move data from one place, like a database, to another, like a UI.)
Or, to quote Dan North:
Data Transfer Object is an oxymoron
Is this class Data Transfer Object, Business Object, Domain Object or
what?
A DTO is typically a class that is mainly used for transferring data between layers or some type of boundaries..typically just an object with no behavior.
I have always referred to Domain Objects as something that maps directly to a database table. So In your example, your domain models would be Notes, and Comments.
I would consider your NotesWithComments object a dto, or possibly a view model (as you're using it as your asp.net mvc model for the view).
The practice I would normally use here is use your NotesWithComments as a dto (transfer data, no behavior, easily serializable, very clean ect), and create another class to act as your view model.
In the beginning these classes would probably be very similar, possibly the same..but if you make changes over time, or your view needs to display different things, you would just change your view model, and populate it from other dtos, or tranform your data however you need to. You could also then get rid of the properties on your view model that your view doesn't need.. (unless your view magically maps directly to every property on your current dto). It's a bit more work up front but if you're working on a big long living project I think you'd be happy you did it later on.
So you would populate your domain models using EF in your data layer, you would then use your dto and transfer that data to the Biz layer, do w/e you need there, then use your dto (could be the same one) to transfer your data to your presentation layer (mvc), and populate your view model from the dtos you receive.
Anyway that's my take on it.

Inserting data using Linq C# with MVC 3 Architecture in asp.net

I m inserting data using controller,
SignUpcontroller.cs
[HttpPost]
public ActionResult Index(SignUpModel sm)
{
using(DataClassesDataContext dc= new DataClassesDataContext())
{
Dummytable dm= new Dummytable();
{
dm.Name=sm.password;
}
//then conncetion string and submit
}
}
and redirection
My question is, is it correct to write this code in the controller module or do i need to write it in models module, if i need to write it in models module then how to define the setter help me out
It is better practice to move all data access code in a data access layer. So simply put this code in a separate class that you could reference and call from your controller. For example you could define an interface that will define the different operations:
public interface IRepository
{
void Insert(SignUpModel model);
}
and then have a specific implementation that is working with the data access technology you are using (EF for example):
public class RepositoryEF : IRepository
{
public void Insert(SignUpModel model)
{
using(DataClassesDataContext dc= new DataClassesDataContext())
{
Dummytable dm = new Dummytable();
dm.Name = sm.password;
}
}
}
and the next step is to have your controller take this repository as constructor dependency:
public class SomeController : Controller
{
private readonly IRepository repo;
public SomeController(IRepository repo)
{
this.repo = repo;
}
[HttpPost]
public ActionResult Index(SignUpModel sm)
{
this.repo.Insert(sm);
...
}
}
Now all that's left is pick up some DI framework and wire up the dependencies.
This way you have a clear separation between your controller logic and the data access layer. This would allow you to unit test the various layers of your application in separation.
first question is Where is your DataAccessLayer ?
So the better practise is write the codes in another one class for read and write database values .
The controller have only for UI logics
and you can use Interface for increase reusability reason and Unit Testing .
This is not common to use for vital data storing/accessing like signup. Consider web security tools and don't work directly with this type of data. Or change your meaning to work with common data.
for the Implementation to work i jst give memory of class to interface with the help of casting from the controller
[HttpPost]
public ActionResult Index(SignUpModel sm)
{
ISignUpModel ISign= (ISignUpModel)this.sm;
ISign.Insert(sm);
}
thanks everyone else, because of you all i learn this :)
and at the SignUpModel.cs, is normal "Interface named as ISignUp with Insert method" Implementation

Factory pattern to "set" product in addition to "get" product?

I am new to design patterns. I am looking for a pattern similar to the factory pattern but that will also let me "set" the product. Something like this:
class VehicleFactory
{
IVehicle static GetVehicle();
void static SetVehicle(IVehicle vehicle);
}
Is there any known pattern similar to this? Thank you.
EDIT: I am looking to store "POCO" objects in the Session object and use a class to set/ get them. I may want to switch persistance to ViewState/ database in the future. This is what I have:
// object to persist in Session.
class Vehicle
{
string Make { get; set; }
string Model { get; set; }
}
// class to set/ get object from Session.
// Please see VehicleFactory above.
Factory pattern is a creational design pattern with encapsulates the creation of a complex object and isolates the creation process from your business logic.
Here it looks like you want a cache to store and manage the Vehicle instances. I would recommend that you call this class a VehicleCache rather than Factory and implement like a cache.
Firstly you should consider having and identifier for the Vehicle object like a vehicleId. I would also recommend that you implement it as an entity object as described in Domain Driven Design.
Then you can implement your cache like this -
public class VehicleCache
{
public void Add(IVehicle instanceToAdd)
{
// Store instance in session object
}
public IVehicle Get(string id)
{
// search and return vehicle from cache
}
// more methods and indexer if required
}
Here are some links that explain how you can implement such cache for your application in a thread safe fashion -
https://blogs.infosupport.com/blogs/frankb/archive/2008/12/31/Implementing-a-Thread-Safe-cache-using-the-Parallel-Extensions.aspx
http://www.objectreference.net/post/Implementing-Generic-Caching.aspx
Like Unmesh says, the name is kind of misleading.
You simply want to cache IVehicle object.
IVehicleCache
{
IVehicle GetVehicle();
void SetVehicle(IVehicle vehicle);
}
// Implementation for http session
public class HttpSessionVehicleCache : IVehicleCache
{
public IVehicle GetVehicle()
{
return (IVehicle)HttpContext.Current.Session["Vehicle"];
}
void SetVehicle(IVehicle vehicle)
{
HttpContext.Current.Session["Vehicle"] = vehicle;
}
}

How to pass unit of work container into constructor of repository using dependency injection

I'm trying to work out how to complete my implementation of the Repository pattern in an ASP.NET web application.
At the moment, I have a repository interface per domain class defining methods for e.g. loading and saving instances of that class.
Each repository interface is implemented by a class which does the NHibernate stuff. Castle Windsor sorts out the DI of the class into the interface according to web.config. An example of an implemented class is provided below:
public class StoredWillRepository : IStoredWillRepository
{
public StoredWill Load(int id)
{
StoredWill storedWill;
using (ISession session = NHibernateSessionFactory.OpenSession())
{
storedWill = session.Load<StoredWill>(id);
NHibernateUtil.Initialize(storedWill);
}
return storedWill;
}
public void Save(StoredWill storedWill)
{
using (ISession session = NHibernateSessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(storedWill);
transaction.Commit();
}
}
}
}
As pointed out in a previous thread, the repository class needs to accept an unit of work container (i.e. ISession) rather than instantiating it in every method.
I anticipate that the unit of work container will be created by each aspx page when needed (for example, in a property).
How do I then specify that this unit of work container instance is to be passed into the constructor of StoredWillRepository when Windsor is creating it for me?
Or is this pattern completely wrong?
Thanks again for your advice.
David
I have a persistence framework built on top of NHibernate that is used in a few Web apps. It hides the NH implementation behind an IRepository and IRepository<T> interface, with the concrete instances provided by Unity (thus I could in theory swap out NHibernate for, say, Entity Framework fairly easily).
Since Unity doesn't (or at least the version I'm using doesn't) support the passing in of constructor parameters other than those that are dependency injections themselves, passing in an extant NH ISession isn't possible; but I do want all objects in the UOW to share the same ISession.
I solve this by having a controlling repository class that manages access to the ISession on a per-thread basis:
public static ISession Session
{
get
{
lock (_lockObject)
{
// if a cached session exists, we'll use it
if (PersistenceFrameworkContext.Current.Items.ContainsKey(SESSION_KEY))
{
return (ISession)PersistenceFrameworkContext.Current.Items[NHibernateRepository.SESSION_KEY];
}
else
{
// must create a new session - note we're not caching the new session here... that's the job of
// BeginUnitOfWork().
return _factory.OpenSession(new NHibernateInterceptor());
}
}
}
}
In this example, PersistenceFrameworkContext.Current.Items accesses an IList<object> that is stored either ThreadStatic if not in a Web context, or within HttpContext.Current.Items if it is in a Web context (to avoid thread-pool problems). The first call to the property instantiates the ISession from the stored factory instance, subsequent calls just retrieve it from storage. The locking will slow things down slightly but not as much as just locking an appdomain-scoped static ISession instance.
I then have BeginUnitOfWork and EndUnitOfWork methods to take care of the UOW - I have specifically disallowed nested UOWs because frankly they were a pain to manage.
public void BeginUnitOfWork()
{
lock (_lockObject)
{
if (PersistenceFrameworkContext.Current.Items.ContainsKey(SESSION_KEY))
EndUnitOfWork();
ISession session = Session;
PersistenceFrameworkContext.Current.Items.Add(SESSION_KEY, session);
}
}
public void EndUnitOfWork()
{
lock (_lockObject)
{
if (PersistenceFrameworkContext.Current.Items.ContainsKey(SESSION_KEY))
{
ISession session = (ISession)PersistenceFrameworkContext.Current.Items[SESSION_KEY];
PersistenceFrameworkContext.Current.Items.Remove(SESSION_KEY);
session.Flush();
session.Dispose();
}
}
}
Finally, a pair of methods provide access to the domain-type-specific repositories:
public IRepository<T> For<T>()
where T : PersistentObject<T>
{
return Container.Resolve<IRepository<T>>();
}
public TRepository For<T, TRepository>()
where T : PersistentObject<T>
where TRepository : IRepository<T>
{
return Container.Resolve<TRepository>();
}
(Here, PersistentObject<T> is a base class providing ID and Equals support.)
Access to a given repository is thus in the pattern
NHibernateRepository.For<MyDomainType>().Save();
This is then facaded over such that you can use
MyDomainType.Repository.Save();
Where a given type has a specialised repository (ie needs more than it can get from IRepository<T>) then I create an interface deriving from IRepository<T>, an extending implementation inheriting from my IRepository<T> implementation, and in the domain type itself I override the static Repository property using new
new public static IUserRepository Repository
{
get
{
return MyApplication.Repository.For<User, IUserRepository>();
}
}
(MyApplication [which is called something less noddy in the real product] is a facade class which takes care of supplying the Repository instance via Unity so you have no dependency on the specific NHibernate repository implementation within your domain classes.)
This gives me full pluggability via Unity for the repository implementation, easy access to the repository in code without jumping through hoops, and transparent, per-thread ISession management.
There's lots more code than just what's above (and I've simplified the example code a great deal), but you get the general idea.
MyApplication.Repository.BeginUnitOfWork();
User user = User.Repository.FindByEmail("wibble#wobble.com");
user.FirstName = "Joe"; // change something
user.LastName = "Bloggs";
// you *can* call User.Repository.Save(user), but you don't need to, because...
MyApplication.Repository.EndUnitOfWork();
// ...causes session flush which saves the changes automatically
In my Web app, I have session-per-request, so BeginUnitOfWork and EndUnitOfWork get called in BeginRequest and EndRequest respectively.
I have a pretty similar structure to yours, and here's how I solve your question:
1) To specify my container on each method, I have a separate class ("SessionManager") which I then invoke via a static property. By doing so, here's an example using my Save implementation:
private static ISession NHibernateSession
{
get { return SessionManager.Instance.GetSession(); }
}
public T Save(T entity)
{
using (var transaction = NHibernateSession.BeginTransaction())
{
ValidateEntityValues(entity);
NHibernateSession.Save(entity);
transaction.Commit();
}
return entity;
}
2) My container is not created on each ASPX page. I instantiate all of my NHibernate goodness on the global.asax page.
** A few more things spring up **
3) You don't need to have a helper to instantiate the Load. You might as well use Get instead of Load. More information # Difference between Load and Get.
4) Using your current code, you would have to repeat pretty much the same code for each domain object you need (StoredWillRepository, PersonRepository, CategoryRepository, etc..?), which seems like a drag. You could very well use a generic class to operate over NHibernate, like:
public class Dao<T> : IDao<T>
{
public T SaveOrUpdate(T entity)
{
using (var transaction = NHibernateSession.BeginTransaction())
{
NHibernateSession.SaveOrUpdate(entity);
transaction.Commit();
}
return entity;
}
}
In my implementation, I could then use something like:
Service<StoredWill>.Instance.SaveOrUpdate(will);
Technically, the answer to my question is to use the overload of container.Resolve which allows you to specify the constructor argument as an anonymous type:
IUnitOfWork unitOfWork = [Code to get unit of work];
_storedWillRepository = container.Resolve<IStoredWillRepository>(new { unitOfWork = unitOfWork });
But let's face it, the answers provided by everyone else have been much more informative.

Resources