Pattern for Single Connection in C# - c#

We would like to use single instance of Http Connection to communicate to server as it's guaranteed to communicate to one end http endpoint
Ex:
MyConnection.GetRoute<ABC>.DoStuff() --https://user.site.com/abc/
MyConnection.GetRoute<XYZ>.DoStuff() --https://user.site.com/xyz/
From the design patterns, Singleton seems to make perfect case
public class MyConnectionHelper
{
private static MyConnection instance;
private MyConnectionHelper() {}
public static MyConnectionHelper Instance
{
get{
if(instance == null){
instance = new MyConnection();
}
return instance;
}
}
}
But we need some credentials to make connection and proxy information to be used if required, these properties should be exposed
public class MyConnectionHelper
{
public static string authKey;
public static string proxyUrl;
private static MyConnection instance;
private MyConnectionHelper() {}
public static MyConnectionHelper Instance
{
get{
if(instance == null) {
instance = new MyConnection(proxyUrl, authKey);
}
return instance;
}
}
}
Is there any better design pattern suits for this use case and better way to expose required/optional parameters that can be provided before creating the connection and reuse it through out the cycle.

You could use something like the code below. When you set the credentials, it flags the connection to be reset. When you access the connection for the first time after that, it will recreate the connection.
private static bool resetConnection;
private static string authKey;
private static string proxyUrl;
public static string AuthKey
{
get => authKey;
set
{
authKey = value;
resetConnection = true;
}
}
public static string ProxyUrl
{
get => proxyUrl;
set
{
proxyUrl = value;
resetConnection = true;
}
}
public static MyConnection HelperInstance
{
get
{
if(resetConnection == null)
{
instance = new MyConnection(proxyUrl, authKey);
resetConnection = false;
}
if(instance == null)
{
instance = new MyConnection(proxyUrl, authKey);
resetConnection = false;
}
return instance;
}
}

Related

Multithread Singeleton Substitution with NSubstitute

I have a public method ValidateWords inside FooService.To test the ValidateWord method, I created IAppSettingWrapper and AppSettingWrapper which returns the Instance of AppSettings.
Inside the test method, I want to substitute NotAllowedWords using NSubstitute. However, it throws an object reference exception. Is there any way for substitution? If it's not possible, how can I refactor my static instance?
public sealed class AppSettings
{
private static object _lockObject = new object();
private static volatile AppSettings? _instance;
private static DateTime _cacheTime;
private Settings[] _settings;
public AppSettings()
{
try
{
_settings = GetSettings();
}
catch { }
}
public static AppSettings Instance
{
get
{
lock (_lockObject)
{
if (_instance == null)
{
_instance = new AppSettings();
}
}
return _instance;
}
}
public List<string> NotAllowedWords
{
get
{
return new List<string>() {
"index",
"change"
};
}
}
public T GetValues<T>(string key,T defaultValue)
{
T result = defaultValue;
var settings = _settings.Where(i => i.Key == key).FirstOrDefault();
result = (T)Convert.ChangeType(settings.Value, typeof(T));
return result;
}
private Settings[]? GetSettings()
{
//gets data from web services
return base.Channel.GetSettings();
}
}
public class Settings
{
public string Key { get; set; }
public string Value { get; set; }
}
public interface IAppSettingsWrapper
{
public AppSettings Instance();
}
public class AppSettingsWrapper : IAppSettingsWrapper
{
public AppSettings Instance()
{
return AppSettings.Instance;
}
}
[TestClass]
public class FooServiceTest{
private IAppSettingsWrapper _appSettingsWrapper;
[TestInitialize]
public void TestInitialize(IAppSettingsWrapper appSettingsWrapper)
{
_appSettingsWrapper = Substitute.For<IAppSettingsWrapper>();
}
private FooService CreateFooService()
{
return new FooService(_appSettingsWrapper);
}
[TestMethod]
public void Throw_Exception_When_Given_Word_Not_Allowed() {
var service = this.CreateFooService();
_appSettingsWrapper.Instance().NotAllowedWords.Returns(new List<string> { "index" });
var word = "index";
Exception ex = Assert.ThrowsException<Exception>(() => service.ValidateWords(word));
Assert.AreEqual("this word is not allowed", ex.Message);
}
}
public class FooService
{
private IAppSettingsWrapper _appSettingsWrapper;
public FooService(IAppSettingsWrapper appSettingsWrapper)
{
_appSettingsWrapper = appSettingsWrapper;
}
public void ValidateWords(string word)
{
if (_appSettingsWrapper.Instance().NotAllowedWords.Contains(word))
{
throw new Exception("this word is not allowed");
}
}
}
The AppSettings.NotAllowedWords property is not substitutable due to it not being virtual and the class being sealed. If you add NSubstitute.Analyzers to your test project it will help you find these cases. (The How NSubstitute Works documentation outlines why this is the case.)
One option is to make AppSettings implement an IAppSettings interface and inject that into FooService (rather than the wrapper). Then you can use a substitute for tests, and AppSettings.Instance for your real code.

C# refactoring Facade for API

I create a dll for my application. I am using Facade design pattern for encapsulate API who makes some programmers (not my organization) because they decision is uncomfortable.
Their API works like this:
Initialize object of DiadocApi
Auth for getting token
For initialize DiadocApi object I need developerKey (get for a subscription).
For authorization I need login, password.
My decision badly because it's a singleton and I need make unit-tests. That can I change in my code?
//I GET IT FROM NUGET PACKAGE
using Diadoc.Api;
public sealed partial class DiadocApiFacade
{
private static readonly object _mutex = new object();
private static DiadocApiFacade _instance;
private string _token;
private DiadocApi _api;
private DiadocApiFacade() { }
public static string DefaultUrl => "url was here";
public string DefaultFromBoxId { get; set; }
public DiadocApi Api { get => _api; private set => _api = value; }
public static DiadocApiFacade GetInstance()
{
if (_instance == null)
{
lock (_mutex)
{
if (_instance == null)
{
_instance = new DiadocApiFacade();
}
}
}
return _instance;
}
public string Authenticate(string login, string password, string privateDeveloperKey)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(developerKey))
throw new ArgumentNullException();
Api = new DiadocApi(developerKey, DefaultUrl, new WinApiCrypt());
return _token = _api.Authenticate(login, password);
}
//method for example, >60% methods like that
public Document GetDocument(string messageId, string documentId, string boxId = null)
{
return _api.GetDocument(_token, boxId ?? DefaultFromBoxId, messageId, documentId);
}
}
I assume you want to make unit tests for your code that's consuming DiadocApiFacade.
Dependency inversion to the rescue! Abstract your DiadocApiFacade with an interface. Make use of the Factory Pattern to create the object. Below is a simple example but you can expand the factory if you need the facade to behave a certain way (like a settings class to change where it's connecting to).
GetOrCreate Will return the same instance but if you're using a dependency injection framework in your project (there are many that might suite your needs), use that instead.
public interface IDiadocApiFacade
{
string Authenticate(string login, string password, string privateDeveloperKey);
public Document GetDocument(string messageId, string documentId, string boxId);
public Document GetDocument(string messageId, string documentId);
}
public class DiadocApiFacadeFactory
{
private static IDiadocApiFacade? _instance = null;
public IDiadocApiFacade Create() //Add parameters
{
return new DiadocApiFacade();
}
public IDiadocApiFacade GetOrCreate()
{
if(_instance == null)
_instance = Create();
return _instance;
}
}
public sealed partial class DiadocApiFacade : IDiadocApiFacade
{
internal DiadocApiFacade() { }
public string Authenticate(string login, string password, string privateDeveloperKey) => string.Empty;
public Document GetDocument(string messageId, string documentId)
=> GetDocument(messageId, documentId, null);
public Document GetDocument(string messageId, string documentId, string? boxId) => new Document();
}
Then you can just make use of [moq)[https://www.nuget.org/packages/moq/] for your unit testing and fake the implementation of IDiadocApiFacade

How to make WCF set a connection string for use with EntityFramework

Using EntityFramework, I have an auto-generated file with:
namespace Chaos.Data
{
public partial class ChaosModel : OpenAccessContext, IChaosModelUnitOfWork
{
private static string connectionStringName = #"ChaosLibraryConnection";
private static BackendConfiguration backend = GetBackendConfiguration();
private static MetadataSource metadataSource = XmlMetadataSource.FromAssemblyResource("EntitiesModel.rlinq");
public ChaosModel()
:base(connectionStringName, backend, metadataSource)
{ }
public ChaosModel(string connection)
:base(connection, backend, metadataSource)
{ }
......................
In the WCF Service, I am using:
namespace Chaos.DataService
{
[ServiceContract]
public class ChaosService
{
[OperationContract]
public IEnumerable<Encountertime> GetEncounterTimes(DateTime? encountertime)
{
if (encountertime == null) return null;
using (var context = new ChaosModel())
{
var query = from et in context.Encountertimes
where et.Tencounter.Date == ((DateTime)encountertime).Date
select et;
var result = context.CreateDetachedCopy(query.ToList());
return result;
}
}
.............................
How can I make the WCF service on startup execute a method (once) that will return a new connection string so that I can change the calls to ChaosModel() to:
using (var context = new ChaosModel(connectionString))
(I am looking for a way to add a static constructor within the WCF service--or something better?).
(The method will determine the network I am on and construct an appropriate connection string to the network server.)
Note: I can make no changes to the auto-generated Entity file.
Use static constructor.
[ServiceContract]
public class ChaosService
{
private static string connectionString;
static ChaosService(){
connectionString = your logic...
}
[OperationContract]
public IEnumerable<Encountertime> GetEncounterTimes(DateTime? encountertime)
{
using (var context = new ChaosModel(connectionString))
{
...
}
}
}
or eventually a singleton pattern:
public class ConnectionInfo
{
public string ConnectionString { get; private set; }
private ConnectionInfo()
{
var connectionstring = string.Empty;
//some logic
this.ConnectionString = connectionstring;
}
private static ConnectionInfo current;
public static ConnectionInfo Current {
get {
if (current != null)
current = new ConnectionInfo();
return current;
}
}
}
[OperationContract]
public IEnumerable<Encountertime> GetEncounterTimes(DateTime? encountertime)
{
using (var context = new ChaosModel(ConnectionInfo.Current.ConnectionString))
{
...
}
}

Create a Singleton Factory for a Class that takes parameters / arguements

First of all I read this on an article - which basically tells me I should not be using a singleton at all -
Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.)
Since I need parameters, and same instances with same parameters - I concluded I need a factory pattern.
But I was unable to find a good factory pattern implementation anywhere.
Kindly direct me if you find any good c# singleton factory pattern implementation with parameters
Ok I am going to try and be very specific here... hope this explains my situation.
Alternate methods are most welcome. I just combined a lot of implementations - my understanding may be off.
So I have a class 'A'. It is a class used to connect to a database - Database connection.
The connection needs 4 parameters & the constraints are:
I need to have multiple connections possible - with different databases (parameters differ)
I need only 1 instance of a specific connection - a singleton with parameters which are same (in my understanding)
I will need a factory model as per the article mentioned above and also to limit the number of connections, close the connection after a timeout etc.
On this basis I need a singleton factory with paramenters/arguements... I assume
So the class A is going to look something like this
<which access modifier ?> Class A {
private Class A(string hostname, string port, string username, string pw_hash) {
//create a new instance with the specified parameters
}
//other methods on the connection
protected void close() {
//close the connection
}
}
public class AFactory//should it inherit class A?? {
private IList<A> connections = new List<A>();
private AFactory()
{
//do something
}
private static readonly Lazy<AFactory> lazy
= new Lazy<AFactory>(() => new AFactory());
public static AFactory Instance { get { return lazy.Value; } }
public A getA(string hostname, string service, string username, string pw_hash)
{
foreach (A a in A)
{
if (a.hostname == hostname && a.service == service && a.username == username)
return a;
}
A d = new A(hostname, service, username, pw_hash);
connections.Add(d);
return d;
}
Now this works well and good as long as the class A constructor is public - but It kind of defeats the purpose of a singleton.
What do I need to do to get this code to work.
I need only 1 instance of class A for the specified parameters.
Thanks
Indrajit
Factory is used to generate object rather than manage object. I think a DB connection manager is more suitable in your situation. You can declare the manager as singleton. For individual connection you can use internal class/struct.
See below example:
class DBConnectionManager
{
struct Connection
{
public string Hostname;
public string ServerName;
public string UserName;
public string Password;
public void Connect()
{
}
public void Close()
{
}
}
private static s_instance;
public static DBConnectionManager Instance
{
get {return s_instance; }
}
private List<Connection> m_connections;
public Connection GetConnection(string hostname, string serverName, string userName, string password)
{
// if already exist in m_connections
// return the connection
// otherwise create new connection and add to m_connections
}
public void CloseConnection(string hostname, string serverName, string userName, string password)
{
// if find it in m_connections
// then call Close()
}
public void CloseAll()
{
//
}
}
So I have done this and it works... can you tell me if it is correct. And also is it Thread-Safe?
public Class A
{
private A(string hostname, string port, string username, string pw_hash) {
//create a new instance with the specified parameters
}
//other methods on the connection
protected void close() {
//close the connection
}
public class AFactory
{
private IList<A> connections = new List<A>();
private AFactory()
{
//do something
}
private static readonly Lazy<AFactory> lazy
= new Lazy<AFactory>(() => new AFactory());
public static AFactory Instance { get { return lazy.Value; } }
public A getA(string hostname, string service, string username, string pw_hash)
{
foreach (A a in connections)
{
if (a.hostname == hostname && a.service == service && a.username == username)
return a;
}
A d = new A(hostname, service, username, pw_hash);
connections.Add(d);
return d;
}
}
}
I am using it like this:
A.AFactory fact = A.AFactory.Instance;
A conn = fact.getA(a, b, c, d);
A conn2 = fact.getA(e, f, g, h);
Is there something glaringly wrong with this implementation?
you could try this:
public static class Singlett<Param,T>
where T : class
{
static volatile Lazy<Func<Param, T>> _instance;
static object _lock = new object();
static Singlett()
{
}
public static Func<Param, T> Instance
{
get
{
if (_instance == null)
{
_instance = new Lazy<Func<Param, T>>(() =>
{
lock (Singlett<Param,T>._lock)
{
try
{
ConstructorInfo constructor = null;
Type[] methodArgs = { typeof(Param) };
constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, methodArgs, null);// Binding flags excludes public constructors.
if (constructor == null)
{
constructor = typeof(T).GetConstructor(BindingFlags.Public, null, methodArgs, null);
if (constructor == null)
return delegate(Param o) { return (T)Activator.CreateInstance(typeof(T), new object[] { o }); };
}
return delegate(Param o) { return (T)constructor.Invoke(new object[] { o }); };
}
catch (Exception exception)
{
throw exception;
}
}
});
}
return _instance.Value;
}
}
}
then to use it:
instead of
int i = 10;
MyClass class = new MyClass(i);
you can write:
int i = 10;
MyClass class = Singlett<int,MyClass>.Instance(i);
Try this:
This interface is exposed from the factory initializer and contains the exposed methods and properties.
public interface IDatabase
{
string ConnectionString { get; set; }
IDataReader ExecuteSql(string sql);
}
Factory base abstract class where you can perform common features to different types of database factories.
public abstract class FactoryBase
{
public FactoryBase() { }
public abstract IDatabase GetDataLayer();
}
Concrete sql class that contains your calls. Have a look at the ExecuteSql method. The connection is self contained in the command so you don't have to worry about opening and closing and disposing of it.
public class SQL : IDatabase
{
private string m_ConnectionString = string.Empty;
public string ConnectionString
{
get { return m_ConnectionString; }
set { m_ConnectionString = value; }
}
public IDataReader ExecuteSql(string sql)
{
using (var command = new SqlCommand(sql, new SqlConnection(ConnectionString)) { CommandType = CommandType.Text, CommandText = sql, CommandTimeout = 0 })
{
if (command.Connection.State != ConnectionState.Open) command.Connection.Open();
return command.ExecuteReader();
}
}
}
Sql factory class that creates an instance of the Sql concrete class.
class SQLFactory : FactoryBase
{
public override IDatabase GetDataLayer()
{
return new SQL();
}
}
The factory initializer class that a developer will use to pass in a type of factory and it will return the IDatabase.
public static class FactoryInitializer
{
public static IDatabase LoadFactory<T>(string connectionstring) where T : FactoryBase, new()
{
var factory = new T();
var data = factory.GetDataLayer();
data.ConnectionString = connectionstring;
return data;
}
}
Then use it as:
var factory = FactoryInitializer.LoadFactory<SQLFactory>(connectionString);
factory.ExecuteSql("SELECT ...");
You can then create may be an OracleFactory and an Oracle concrete class and use it the same way.

Proper way of using C# global variables in ASP.NET?

I am using ASP.NET Web Forms and C# in my application. I have a class file named Global.cs, in which I define variables using set and get properties. I use those variables anywhere on any pages by instantiating that class object.
Here is my Global.cs file:
using System;
using System.Data;
using System.Linq;
using System.Web;
/// <summary>
/// Contains my site's global variables.
/// </summary>
public static class Global
{
/// <summary>
/// Global variable storing important stuff.
/// </summary>
public static string gDate;
public static string gMobLength;
public static string gDateFormat;
public static string gApplicationNo;
public static string gBranchNo;
public static string gMemId;
public static string gIsEditable="false";
public static string gLoggedInUserName;
public static string ImportantData
{
get
{
return gDate;
}
set
{
gDate = value;
}
}
public static string MobileLength
{
get
{
return gMobLength;
}
set
{
gMobLength = value;
}
}
public static string DateFormat
{
get
{
return gDateFormat;
}
set
{
gDateFormat = value;
}
}
public static string ApplicationNo
{
get
{
return gApplicationNo;
}
set
{
gApplicationNo = value;
}
}
public static string BranchNo
{
get
{
return gBranchNo;
}
set
{
gBranchNo = value;
}
}
}
Is this a proper way of using variables throughout the project? What are the possible pros and cons with this approach and what approach would you guys take for using global variables?
First, I'd recommend using autoimplemented properties.
public static string BranchNo { get; set; }
Simplifies your code a bit. As to whether or not this is a good approach, it depends. Sometimes simple and straight-forward is better, and this falls into that category. If the values should not change once initialized, you may want to use a proper singleton with initialization:
public class Settings
{
private static Settings _current;
private static readonly object _lock = new object();
public static Settings Current
{
get
{
lock(_lock)
{
if (_current == null) throw new InvalidOperationException("Settings uninitialized");
return _current;
}
}
set
{
if (value == null) throw new ArgumentNullException();
if (_current != null) throw new InvalidOperationException("Current settings can only be set once.");
if (_current == null)
{
lock(_lock)
{
if (_current == null) _current = value;
}
}
}
}
public string ImportantData { get; private set; }
// etc.
}
Initializing settings:
Settings.Current = new Settings{ ImportantData = "blah blah blah"};
Accessing:
var data = Settings.Current.ImportantData;
Outside of the two bromides "globals are bad" and "properties are good" ... there's nothing intrinsically wrong with your approach. Go for it!
IMHO .. PSM
The reason why you do not see the variable after you instantiate that class object is because the variables are declared as static. Static variables are meant to be used by that manor ClassName.variableName or ClassName.PropertyName

Categories

Resources