In entire application use the static class tConfig.ConnectionString to download the necessary connectionstring. Unfortunately, I need to be able to modify connectionsting depending on whether the reference is to the TransactionScope. Currently, I have this piece of code, but static class calls me StackOverflow error. Please help to implement the functionality in this class static (or some better solution).
public static class tConfig
{
public static string ConnectionString
{
get {
if (System.Transactions.Transaction.Current != null)
return "ConnectionString with scope";
else
return "ConnectionString without scope";
}
}
}
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetData;
[OperationContract]
string GetDataWithScope;
}
public class MyService : IMyService
{
public string GetData
{
using (var context = new MyEntities(tConfig.ConnectionString)
{
return context.table1.where(x=>x.ID == 1).Select(x=> x.F_NAME).FirstOrDefault().ToString();
}
}
public string GetDataWithScope
{
using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(600)))
{
using (var context = new MyEntities(tConfig.ConnectionString)
{
return context.table1.where(x=>x.ID == 1).Select(x=> x.F_NAME).FirstOrDefault().ToString();
}
}
}
}
I think that it is bad idea to use transdactions this way. When the transaction completes? in your code there is no Complete or RollBack call. The scope for every call will be different because of different threads of each call.
see this link. It describes the approach to use trasactions on wcf level.
In this situation client can create and complete transaction scope.
Related
Task assigned to me is to refactor a code but should't modify static access modifier of class. I am trying to implement service layer , unit of work , repository pattern . static repository code is below , how can i implement unit of work and repository pattern for a static class? i like to implement a solution applying solid principles and unit testable application.
static class
using System;
using System.Data.SqlClient;
namespace Contoso
{
public static class UsersRepository
{
private static string ConnectionString = #"Data Source=(local); Database=Users;User Id=sa;Password=password;";
public static User Load(int userId)
{
User user = new User();
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Users WHERE UserId = " + userId,
connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
user.Name = reader["Name"].ToString();
user.DateOfBirth = DateTime.Parse(reader["DateOfBirth"].ToString());
user.Country = reader["Country"].ToString();
}
connection.Close();
return user;
}
}
}
How can i implement unit of work and repository pattern for a static class?
You can leverage the fact that whenever someone calls the code here, they do so via a public entry point. This means that when the caller first enters the class (via said public method), you create a unit of work and dispose of it only when that same method returns a value to the caller (or simply ends).
Something along the lines of:
public static class MyClass
{
public static User LoadUser(int userId)
{
using (var uow = new UnitOfWork())
{
DoSomething(uow);
var user = uow.UserRepository.GetById(userId);
return user;
}
}
}
Essentially, every public method should create, use and dispose of a single unit of work instance. This ensures two things:
Concurrent calls use their own separate unit of work.
No unit of work will ever linger in-memory after the entry method has finished.
This does get trickier when you start using async programming, but I'm omitting that consideration since you never mentioned it either.
i like to implement a solution applying solid principles and unit testable application
It gets slightly trickier when you deal with dependency injection. Static classes do not have an injectable constructor (note: they do have a constructor, but they don't allow for constructor arguments).
So injecting your dependency is going to be... atypical. One solution I can think of is to explicitly set the kernel (I am using NInject here as a matter of example):
public static class MyClass
{
public static IKernel Kernel { get; set; }
public static User LoadUser(int userId)
{
using (var uow = Kernel.Get<IUnitOfWork>())
{
DoSomething(uow);
var user = uow.UserRepository.GetById(userId);
return user;
}
}
}
How you set the kernel (either by setting it explicitly or assigning it a default value directly) is up to you.
Without NInject or any similar library, you could achieve dependency injection using a Func<IUnitOfWork> as your factory method to create a unit of work on demand:
public static class MyClass
{
public static Func<IUnitOfWork> CreateUnitOfWork { get; set; }
public static User LoadUser(int userId)
{
using (var uow = CreateUnitOfWork())
{
DoSomething(uow);
var user = uow.UserRepository.GetById(userId);
return user;
}
}
}
Again, how you set the factory method's content is up to you, e.g.:
MyClass.CreateUnitOfWork = () => new UnitOfWork();
I have an ASP.NET MVC 5 Application with a SignalR 2 hub and using autofac for the DI.
The entire business logic is encapsulated in manager classes in their own layer. Some manager methods need informations about the current logged in user (UserId, TenantId, ..).
I solved this problem by injecting an AuthorizationProvider into each manager class that needs the user information.
public interface IAuthorizationProvider
{
long? GetUserId();
long? GteTenantId();
}
public class MyManager : IMyManager
{
private IAuthorizationProvider _authorizationProvider;
public MyManager(IAuthorizationProvider authorizationProvider)
{
_authorizationProvider = authorizationProvider;
}
public void MyMethod()
{
// Getting the User information here is pretty simple
long userId = _authorizationProvider.GetUserId();
}
}
Normally I can get the user information from the HttpContext and from the session. So I wrote a SessionAuthorizationProvider:
public class SessionAuthorizationProvider{
public long? GetUserId()
{
HttpContext.Current?.Session?[SessionKeys.User]?.Id;
}
public long? GteTenantId() { ... }
}
But now I have a new method in the SignalR hub that use the same mechanism.
[HubName("myHub")]
public class MyHub : Hub
{
private IMyManager _myManager;
public MyHub(IMyManager myManager)
{
_myManager = myManager;
}
[HubMethodName("myHubMethod")]
public void MyHubMethod(long userId, long tenantId)
{
_myManager.MyMethod();
}
}
The problem is that a SignalR request doesn't have a session. Therefore I have also set the required user information in the hub method as parameters postet from the client.
So I thought it is the best solution for this problem to write a new AuthorizationProvider for SignalR and adapt the depdendency resolver. But I can't get the current user in the new SignalrAuthorizationProvider.
public class SignalrAuthorizationProvider{
public long? GetUserId()
{
// How to get the user information here???
}
public long? GteTenantId() { /* and here??? */ }
}
Is there a recommended solution to this problem?
Of course, I can extend MyMethod to accept the user information as a parameter. But MyMethod calls another method from another manager and that manager also calls another method. The user information is only needed for the last method call. So I had to change at least 3 methods and many more in the future.
Here is a sketch of the problem
This is a potential solution. But it's very bad
Session is not supported by SignalR by default and you should avoid using it. See No access to the Session information through SignalR Hub. Is my design is wrong?. But you still can use cookie or querystring to get the desired value.
In both case you need to have access to the HubCallerContext of the underlying hub, the one that is accessible through the Context property of the Hub.
In a ideal word you should just have to had the dependency to the SignalAuthorizationProvider
ie :
public class SignalrAuthorizationProvider {
public SignalrAuthorizationProvider(HubCallerContext context){
this._context = context;
}
private readonly HubCallerContext _context;
public long? GetUserId() {
return this._context.Request.QueryString["UserId"]
}
}
But due to SignalR design it is not possible. Context property is assigned after construction of the Hub and AFAIK there is no way to change it.
Source code here : HubDispatcher.cs
One possible solution would be to inject a mutable dependency inside the Hub and alter the object in the OnConnected, OnReconnected methods.
public class SignalrAuthorizationProvider : IAuthorizationProvider
{
private Boolean _isInitialized;
private String _userId;
public String UserId
{
get
{
if (!_isInitialized)
{
throw new Exception("SignalR hack not initialized");
}
return this._userId;
}
}
public void OnConnected(HubCallerContext context)
{
this.Initialize(context);
}
public void OnReconnected(HubCallerContext context)
{
this.Initialize(context);
}
private void Initialize(HubCallerContext context) {
this._userId = context.QueryString["UserId"];
this._isInitialized = true;
}
}
and the Hub
public abstract class CustomHub : Hub
{
public CustomHub(IAuthorizationProvider authorizationProvider)
{
this._authorizationProvider = authorizationProvider;
}
private readonly IAuthorizationProvider _authorizationProvider;
public override Task OnConnected()
{
this._authorizationProvider.OnConnected(this.Context);
return base.OnConnected();
}
public override Task OnReconnected()
{
this._authorizationProvider.OnReconnected(this.Context);
return base.OnReconnected();
}
}
Having a mutable dependency is not the best design but I can't see any other way to have access to IRequest or HubCallerContext.
Instead of having an abstract Hub class which is not a perfect solution. You can change the RegisterHubs autofac method to use AOP with Castle.Core and let the interceptor calls the methods for you.
I have some problem with understanding how to create injectable classes…
Here is my example:
public interface IService
{
string FindSomeData()
}
Now we create a class which implements the interface:
public class FolderService : IService
{
private string _path;
public FolderService(string path)
{
_path = path;
}
public string FindSomeData()
{
//Open a folder using _path and find some data
}
}
And maybe other class:
public class DbService : IService
{
private MyConnectionClass _connection;
public DbService(MyConnectionClass connection)
{
_connection = connection;
}
public string FindSomeData()
{
//Connect to database using _connection object and find some data
}
}
Now I would like to add one of the classes to IoC Container e.x.:
if (InDebug)
SimpleIoc.Default.Register<IService, FolderService>();
else
SimpleIoc.Default.Register<IService, DbService>();
And know I have a problems.
When I want to pass this object to the constructor of some other classes:
public MyViewModel(IService service)
{
_service = service;
}
// Read folder name from TextBox on View and then call _service.FindSomeData
Then I would like to pass user selected path to the IService object (FolderService) in this case.
How should I do this in a correct way (according to SOLID and other good practiciess patterns…)?
Once I should pass string (folder path), once a MyConnectionClass (if connection to database).
What is the best way to do that kind of things?
Best regards,
Michal
You can encapsulate folder path provide/change logic into a separate provider like IFolderPathProvider and inject it into FolderService
public interface IFolderPathProvider {
string GetFolderPath();
void SetFolderPath(string);
}
public class FolderPathProvider : IFolderPathProvider {
...
}
public class FolderService : IService
{
private IFolderPathProvider _folderPathProvider;
public FolderService(IFolderPathProvider folderPathProvider)
{
_folderPathProvider = folderPathProvider;
}
public string FindSomeData()
{
string path = _folderPathProvider.GetFolderPath();
//Open a folder using path and find some data
}
}
When user changes the path, inject IFolderPathProvider to the handler and call SetFolderPath. Similarly, you can create IDbConnectionProvider. Depending on the situation, they can be combined into one DataConfigProvider but I 'm not sure what exactly do you need there; the main idea is to separate folderpath/dbconnection changing logic from the services and keep using dependency injection.
I would like to improve my .NET project by adding another layer when accessing the database. This is my code:
namespace Company.Models
{
public static class AgencyBean
{
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static String createGUID(string name)
{
DataAccess dataAccess = new DataAccess();
bool exists = dataAccess.checkIfExists(Id);
if(exist)
{
dataAccess.delete(Id);
}
retur "ok";
}
}
}
I placed DataAccess class in a separate folder called "Helpers" and it contains most of my queries:
public class DataAccess
{
public bool checkIfExists(String Id)
{
try
{
SqlConnection cnn = new SqlConnection(dataConnection);
cnn.Open();
SqlCommand check_Id = new SqlCommand("SELECT COUNT(*) FROM TABLE_GUID WHERE ([USER_ID] = #Id)", cnn);
check_Id.Parameters.AddWithValue("#Id", Id);
int UserExist = (int)check_Id.ExecuteScalar();
if (UserExist > 0)
{
return true;
}
else
{
return false;
}
}
catch (SqlException ex)
{
Debug.WriteLine("SQL Exception " + ex);
DisplaySqlErrors(ex);
throw ex;
}
}
}
public class AgentBeanController : Controller
{
// GET: AgentBean
public ActionResult Index(string name)
{
return View();
}
[AllowAnonymous]
[WebMethod]
public string AgentURL() //here we create Agent URL and return it to the view
{
string var = Models.AgentBean.createGUID("TODO");
return var;
}
}
I'm accessing the database pretty much in very direct way. How would it be with a better technique, so this access can be more secure, like accessing thru a service layer?
I'm connecting to a existing sql database in some server and working with MVC architecture in my project.
So here is what I have done in the past.
First, that is your "models" namespace... models should never have database connectivity. Instead you have a seperate class, such as a controller, that hydrates some model.
Second, I've had a "service" class, which hooks up to a "repository" class. The repository class implements an interface to identify the exact "type" of database you're using.. but if that's not a part of your requirements you probably don't need to go that far.
Third, look up dependency injection (aka, DI). There are several frameworks out there. Personally I've used Autofac, but others exist as well to get the job done easier.
Fourth, on your your "controllers", "services" and "respository" classes, implement dependency injection, as well as any interfaces as needed to form a contract.
Fifth, I would use an actual controller namespace and not be working out of your models namespace to be pushing http calls band and forth.... Instead, create an action in your controller class, and instantiate an instance of your "agencyBean", hydrate it with data, and return that model out to your view.
Basically, in a scenario like this you're trying to keep each component doing what it is designated to do... breaking down responsibilities into smaller pieces and focusing on that. Your controller should just "fetch" your model and maybe do some transformations on it as needed or any other business-type logic.
Your service should handle the communication between your controller and your database layer.
Your data access layer (ie, in this case, some "repository" class...) would do all of those new data connections and/or setting up calls to stored procedures or queries.
Doing things this way has a lot of benefit. Some of the big ones are maintainability, readability, code re-use. Sure it makes your project a bit more complicated in terms of files sitting wherever... but that can be a good thing. It's so much better than slamming everything into one single class and have it do everything :)
But, just FYI, this is from an implementation I've done in the past... I'm sure there are better ways but this setup worked quite well for my team and I.
Here is a small example using some of your code you posted. I DID NOT check this for typos and it wouldn't compile, but should help give a general idea of what I'm talking about....
namespace Company.Models
{
public class AgencyBean
{
public AgencyName{get;set;}
public AgencyId{get;set;}
// other properties...
}
}
namespace Company.Controllers
{
public class MyController : Controller
{
private readonly IMyService myService;
public MyController(IMyService myService) // <-- this is your dependency injection here...
{
this.myService = myService;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static String createGUID(string name)
{
var model = new AgencyBean();
model.AgencyId = 1;
model = myService.getAgency(agencyBean);
return model;
}
}
}
namespace Company.Services
{
public class MyService
{
private readonly IMyRepository myRepository;
public MyService(IMyRepository myRepository) // <-- this is your dependency injection here...
{
this.myRepository = myRepository;
}
public AgencyBean getAgency(AgencyBean model){
var dataTable = myRepository.getAgencyData(model.AgencyId);
// fill other properties of your model you have...
// ...
// ...
return model;
}
}
}
namespace Company.Repositories
{
public class MyRepository : IDatabaseCommon // <-- some interface you would use to ensure that all repo type objects get connection strings or run other necessary database-like setup methods...
{
private readonly String connectionString{get;set;}
public MyRepository()
{
this.connectionString = //get your connection string from web.config or somewhere else...;
}
public DataTable getAgencyData(int id){
var dataTable = new DataTable();
// perform data access and fill up a data table
return dataTable;
}
}
}
We have an application that contacts several diffrent remote services(SOAP, HTTPREQUEST). We then do different actions(import, export, update, delete).
Today we have two client classes and four action classes.
QUESTION!
How can I decouple these two modules so that I have to do the least changes. IE only add a new action/new client. Nothing more.
Client class
Authorizes our client against the remote service, it handles logging in and out.
Action class
Holds the url, method to invoke against the client. Aswell as the ExecuteActionMethod
Usage
Client class get's decorated with an action and then performs the action with the client.
Fears
I dont want to: - create a new action class everytime I add a new client class - create a new client class everytime I add a new action class - No god object factory that needs to know everything
Problem
The problem with this approach is that when talking to different clients, I need diffrent information in this case different URLS, talking to the Soap service needs invoking of the correct method. The action itself is the keeper of this information. But as I dig deeper this certainly is something that will change.
Scenario 1#
I end up creating classes that combine both action and result. So I have classes like "HttpImport"(based on HttpClient and ImportAction). Which results in X(Clients) * Y(Actions) which now would total at 8 classes, which is really bad.
Scenario 2#
Time for some code! In this scenario the implementation binds my classes together even though I use abstractions.
Problem here is that every action need to have a property for each of the clients(remember they visit different endpoints). So if i were to add one more client I would have to go through all the actions and add another property for that clients endpoint, aswell as add another deocrator to delegete all calls to the correct endpoint(remember i have three properties now in every action). If I were to create another action, it would just be that action. So N*times actions + 1(the action), in this case 5 changes. A little bit better but still not there.
Scenario 3#
This is the God object factory. Here we get rid of the properties holding the endpoints, and we supply the enpoint via the constructor. This will result in methods for creating all sorts of clients and actions. Same as above X(Clients) * Y(Actions) if something were to be added, these accumulate into 8 new methods inside the factory. The factory must also hold endpoint information.
Code
My code has evolved to the 2:nd scenario. I dont want to build the factory, and I'm looking to you guys.
Something tells me that the client classes does to much and should somehow be decoupled, from the classes they instansiate inside.
Main
static void Main(string[] args)
{
IAction iact = new ImportAction();
IDecorator idec = new HttpDecorator(iact);
IClient icli = new HttpClient(idec);
Console.Write(icli.connect().ToString());
Console.ReadKey();
}
IAction
public interface IAction
{
string[] Execute();
string HttpString { get; }
string SoapMethod { get; }
}
ImportAction
class ImportAction : IAction
{
private string soapmethod;
private string httpUrl;
public ImportAction()
{
this.HttpString = #"http://www.hereiswereactionsgo.com";
}
public string[] Execute()
{ //Execute the action!
return null;
}
public string HttpString { get; set; }
public string SoapMethod { get; set; }
}
IDecorator
public interface IDecorator
{
string GetActionString();
}
HttpDecorator
class HttpDecorator : IDecorator
{
private IAction _action;
public HttpDecorator(IAction action)
{
this._action = action;
}
public string GetActionString()
{
return _action.HttpString;
}
public string[] Execute()
{
throw new NotImplementedException();
}
}
IClient
public interface IClient
{
bool connect();
}
HttpClient
class HttpClient : IClient
{
private string _username;
private string _password;
private IDecorator _myaction;
private HttpWebRequest webReq;
public HttpClient(IDecorator action)
{
this._username = "myusername";
this._password = "mypassword";
this._myaction = action;
}
public bool connect()
{
bool result = false;
webReq = (HttpWebRequest)WebRequest.Create(_myaction.GetActionString());
webReq.Credentials = new NetworkCredential(_username, _password);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)webReq.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
{
result = true;
}
return result;
}
}
Visitor pattern seems suitable for this (Visitor) .
Treat Actions as the Visitors and Clients as Elements to visit. Keeping Action as an abstract class rather than interface may help by providing the boilerplate code.
To add a new Action extend BaseAction. Implement methods such as getHttpUrl(), getHttpBody() etc.
To add a new Client will require changes to existing classes. You have to implement corresponding methods in each Action class. I assume adding a new Client will happen less frequently.
The sample code below follows Java syntax.
public static void main() {
new HttpClient().performAction(new ImportAction());
}
public interface Client {
performAction(Action);
}
public class HttpClient implements Client {
public void accept(IAction a) {
a.visitHttp(this);
}
}
public abstract class Action {
public visitHttp(HttpClient c) {
getHttpUrl();
c.connect(getHttpUrl());
c.send(getHttpBody());
c.close;
}
public visitSoap(SoapClient c) {
}
public abstract String getHttpUrl();
public abstract String getHttpBody();
}
ImportAction extends Action {
#Override
getHttpUrl() {
}
#Override
getHttpBody() {
}
}