C# web-service instances - c#

I have the following class in Web-service App_Code:
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : WebService
{
private readonly MyServiceFacade myService;
static MyService()
{
}
public MyService()
{
myService = new MyServiceFacadeImpl();
}
}
And now I have a question about how instances of this service are created.
For example, let we have the following class:
public class MyServiceFacadeImpl()
{
private List<DateTime> dts;
public MyServiceFacadeImpl()
{
dts.Add(DateTime.Now);
}
}
Now, 15 users connect to the server and authenticate using basicauth and what will happen?
There will be 15 instances of MyServiceFacadeImpl with one DateTime in each dts
There will be a single instance of MyServiceFacadeImpl with 15 DateTimes in dt
And, now, if I make this List static, what will happen?
I just need to implement a mechanism which will restrict the number of requests from a single user \ session per minute.

And, now, if I make this List static, what will happen?
There will be 15 instances of MyServiceFacadeImpl with 15 DateTime in static instance of dts
I just need to implement a mechanism which will restrict the number of
requests from a single user \ session per minute.
You can use Dictionary <string, DateTime> where string stores the user name. It would be static or you can store dictionary in Application object. If you want to use Application object to store the state of user then this MSDN article How to: Save Values in Application State explains it.
The above method are not safe to store the information that you do not want to loose. You would consider to store in information in persistent medium like database if you want it even the web services go down.

There are several different ways you can solve this.
The easiest is to implement a singleton pattern where which has an internal dictionary to register a user to the number of times a user has made a request.
public sealed class UserRequests{
private static readonly UserRequests instance = new UserRequests();
public static UserRequests Instance { get { return instance; } }
static UserRequests() {}
private UserRequests() {}
private Dictionary<Users,List<DateTime>> _userRequestList;
private void AddRequest(User user){
//Add request to internal collection
}
public bool CanUserMakeRequest(User user){
//Call clean up method to remove old requests for this user
// check the requests to see if user has made too many
// if not call AddRequest and return true, else return false
}
}

Related

Share Data Between Threads when using SpecFlow + SpecRunner

I am working on a test suit implementation which uses the SpecFlow + SpecRunner and XUnit. and we are trying to do parallel test execution and i would like to know is there are a way that i can run a hook in the begining of the test run and store the token value in a static variable so that that can be shared among threads.
to summarize is there a way that specflow offers a mechanism to share data between threads during parallel execution.
We can share the data using any one of the below approach
Scenario Context
Context Injection
Here, Approach 1 and 2 will not have any issue in multiple thread. Since, Context Injection life is specific to the scenario Level.
Approach 1 : we can define the Token Generation Step within the BeforeScenario hooks and the generated Token values can be updated in the ScenarioContext.
we can directly access the token from the scenario context in any place like below
Here, Token will be generated before each scenario run and it will not affect the Parallel execution.For more Details, Parallel-Execution
Scenarios and their related hooks (Before/After scenario, scenario block, step) are isolated in the different threads during execution and do not block each other. Each thread has a separate (and isolated) ScenarioContext.
Hooks Class:
public class CommonHooks
{
[BeforeScenario]
public static void Setup()
{
// Add Token Generation Step
var adminToken = "<Generated Token>";
ScenarioContext.Current["Token"] = adminToken;
}
}
Step Class:
[Given(#"I Get the customer details""(.*)""")]
public void WhenIGetTheCustomerDetails(string endpoint)
{
if(ScenarioContext.Current.ContainsKey("Token"))
{
var token = ScenarioContext.Current["Token"].ToString();
//Now the Token variable holds the token value from the scenario context and It can be used in the subsequent steps
}
else
{
Assert.Fail("Unable to get the Token from the Scenario Context");
}
}
If you wish to share the same token across multiple Step, then you can assign this token value within constructor and it can be used
For Example,
[Binding]
public class CustomerManagementSteps
{
public readonly string token;
public CustomerManagementSteps()
{
token= ScenarioContext.Current["Token"].ToString();
}
[Given(#"I Get the customer details""(.*)""")]
public void WhenIGetTheCustomerDetails(string endpoint)
{
//Now the Token variable holds the token value from the scenario context and It can be used in the subsequent steps
}
}
Approach 2: Context Injection details can be referred in the below link with an example
Context Injection
Updated
Given the downvote and comments, I've updated my code example to better show exactly one way you can use dependency injection here with code of your own design. This shared data will last the lifetime of the scenario and be used by all bindings. I think that's what you're looking for unless I'm mistaken.
//Stores whatever data you want to share
//Write this however you want, it's your code
//You can use more than one of these custom data classes of course
public class SomeCustomDataStructure
{
//If this is run in paralell, this should be thread-safe. Using List<T> for simplicity purposes
//Use EF, ConcurrentCollections, synchronization (like lock), etc...
//Again, do NOT copy this code for parallel uses as List<int> is NOT thread-safe
//You can force things to not run in parallel so this can be useful by itself
public List<int> SomeData { get; } = new List<int>();
}
//Will be injected and the shared instance between any number of bindings.
//Lifespan is that of a scenario.
public class CatalogContext : IDisposable
{
public SomeCustomDataStructure CustomData { get; private set; }
public CatalogContext()
{
//Init shared data however you want here
CustomData = new SomeCustomDataStructure();
}
//Added to show Dispose WILL be called at the end of a scenario
//Feel free to do cleanup here if necessary.
//You do NOT have to implement IDiposable, but it's supported and called.
public void Dispose()
{
//Below obviously not thread-safe as mentioned earlier.
//Simple example is all.
CustomData.SomeData.Clear();
}
}
[Binding]
public class SomeSteps
{
//Data shared here via instane variable, accessable to multiple steps
private readonly CatalogContext catalogContext;
//Dependency injection handled automatically here.
//Will get the same instance between other bindings.
public SomeSteps(CatalogContext catalogContext)
{
this.catalogContext = catalogContext;
}
[Given(#"the following ints")]
public void GivenTheFollowingInts(int[] numbers)
{
//This will be visible to all other steps in this binding,
//and all other bindings sharing the context
catalogContext.CustomData.SomeData.AddRange(numbers);
}
}

ASP.NET OWIN vs Singleton Pattern

I'm working on a Web App where I instantiated my a Singleton class below in Startup.cs in order to be reused (more like making a programmable session):
app.CreatePerOwinContext<XYZManager>(XYZManager.Create);
But I'm encountering a problem, as soon as UserA logs in on the app, the information inside XYZManager class gets overwritten when UserB enters and vice versa when they perform some action.
The problem I think is, they're sharing the same application pool, how can this be resolve, any hack?
An meanwhile the whole essence of this approach, I want to be able to call any getter / setter of method inside XYZManager for the current logged user for example:
HttpContext.GetOwinContext().Get<XYZManager>().GetFullDetails();
But sometimes throw details for another logged on user based on operations.
public class XYZManager : IDisposable
{
private static XYZManager instance { get; set; }
public static XYZManager Create()
{
var xyzManager = instance ?? (instance = new XYZManager());
xyzManager.ApplicationDbContext = new ApplicationDbContext();
return xyzManager;
}
public string GetFullDetails () {
return "blah blah";
}
}
As described in msdn, the CreatePerOwinContext method will accept a factory method to create an instance of your class (in this cas XYZManager), and it will keep it for all same context requests with.
HttpContext.GetOwinContext().Get<XYZManager>()
So each time a new Owin Context is created (a new http request received) XYZManager.Create will be invoked. In your case this method returns the same instance, so all contexts will share that instance.
Depending if you want to share that instance for all contexts or not you should return new or the same instances. Also note, that for singleton shared instances there is a different Owin extension method that will keep the singleton for you.
Check out this answer as it explains what is the purpose of the CreatePerOwinContext method, as well as provide some examples how to create a inter context shared instance.
This is how you create Context shared service
public class XYZManager : IDisposable
{
public static XYZManager Create()
{
return new XYZManager(new ApplicationDbContext());
}
private readonly ApplicationDbContext DbContext;
public XYZManager(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
public string SomeInfo {get;set;}
public string GetFullDetails ()
{
return dbContext.getFullDetails();
}
// dispose
}
Note: Since you will be creating instances each time a new owin context is creates it is advisable, to make sure any unmanaged objects are disposed.

Static Provider Dictionary Design

I'm rethinking a current WCF service we're using right now. We do A LOT of loading XML to various databases. In some cases, we can store it as XML data, and in others, we need to store it as rowsets.
So I'm redesigning this service to accept different providers. My first thought, classic abstract factory, but now I'm having my doubts. Essentially, the service class has one operation contract method, Load. But to me, it seems silly to new-up provider instances every time Load is called.
Currently:
// Obviously incomplete example:
public class XmlLoaderService : IXmlLoaderService
{
readonly IXmlLoaderFactory _xmlLoaderFactory;
readonly IXmlLoader _xmlLoader;
public XmlLoaderService()
{
_xmlLoader = _xmlLoaderFactory(ProviderConfiguration configuration);
}
public void Load(Request request)
{
_xmlLoader.Load(request);
}
}
I'm thinking about changing to:
public class XmlLoaderService : IXmlLoaderService
{
static readonly IDictionary<int, IXmlLoader> _providerDictionary;
static public XmlLoaderService()
{
_providerDictionary = PopulateDictionaryFromConfig();
}
public void Load(Request request)
{
// Request will always supply an int that identifies the
// request type, can be used as key in provider dictionary
var xmlLoader = _providerDictionary[request.RequestType];
xmlLoader.Load(request);
}
}
Is this a good approach? I like the idea of caching the providers, seems more efficient to me... though, I tend to overlook the obvious sometimes. Let me know your thoughts!
Why can't you use both? Pass in your dependency into the Load method and if the type is already cached use the cached instance.
public void Load(Request request)
{
// Request will always supply an int that identifies the
// request type, can be used as key in provider dictionary
IXmlLoader xmlLoader;
if(_providerDictionary.ContainsKey(request.RequestType))
{
xmlLoader = _providerDictionary[request.RequestType];
}
else
{
xmlLoader = //acquire from factory
_providerDictionary.Add(request.RequestType, xmlLoader);
}
xmlLoader.Load(request);
}

Make available a variable in multiple forms in compact framework

I'm doing an application for a Windows CE 5.0 device that asks for the username in the first form (when the application is launched), and then I get the userId from a database table.
After that a menu form appears which receives the userId, and I have to send to each constructor of the menu options the userId in order to use it in those forms. I assume there must be a better way to do something like this.
Example:
public partial class Menu : Form
{
int userId;
public Menu(int userId)
{
InitializeComponent();
this.userId = userId;
}
private void buttonDelivery_Click(object sender, EventArgs e)
{
Delivery delivery = new Delivery(userId);
delivery.Show();
this.Hide();
}
...
May be I should use a global variable like this?
public static class UserConfiguration
{
public static int userId;
}
Isn't that also bad practice?
Finally bear in mind that compact framework doesn't support app.config files
Personally I'd vote for "neither", but would instead use some other architectural tools available.
I'd be highly inclined to have a class that incorporates all user info (the ID you're using and then maybe anything else, like name, etc). I'd create an instance and populate that info when the first Form (login) is submitted and I'd keep it in a DI container (I use this one specifically, but any CF-supporting container would work).
I'd then either use injection to either automatically push that instance into any class that needs it, or have the consumer pull it from the container as needed. Which mechanism I use would depend on which container I'm using and exactly how/when I need the info.
Since the data you're after is coming from a database, I'd actually be inclined to use an ORM (I use this one) to pull the data, which would give you the entity instance containing the user info you're after automatically anyway.
in my opinion both ways are good, in some cases some controls do not work properly if you change the constructor signature or in some cases your constructor would not be called if the framework always calls the one with no parameters. But really depends on the specific case.
I like more the method parameters way to pass the values, but the external class with static field would also work fine.
P.S. app.config is not the best place anyway to store runtime specific values so doesn't matter if supported or not by CF in this case ;-)
If you use a controller it can hold all the variables needed. The controller can have a static Instance property that instantiates itself (see Singleton object design pattern). When developing Mobile applications this is very common as memory is often a constraint. The rest of the methods are public members (not static) so you would access like this. You can either make them properties or just use the public member. Even with mobile we tend to not use properties as it just adds unecessary fluff and boxing/unboxing.
In one form you can use:
MainController.Instance.loginID = "me123";
on another you can use
MessageBox.Show("my loginID is: " + MainController.Instance.loginID);
You can also add methods like:
MainController.Instance.ClearSession();
Which internally just sets loginID to null. etc. Personally I use the main controller to show windows as well. Because in mobile we need to make sure our resources are cleaned up as well.
MainController.Instance.ShowLoginForm();
the MainController code as a start should look something like this:
public class MainController : IDisposable {
//all forms we are controlling
LoginForm _loginForm = null;
//all public members
public string loginID = null;
#region Singleton Instance stuff
private static MainController me = null;
private void MainController() { }
public static Instance {
get {
if(me == null) {
me = new MainController();
}
return me;
}
}
#endregion
//all public methods
public void Init(someargshere) {
//TODO some init like load config files, etc.
}
public void Dispose() {
//TODO cleanup
}
public void ClearSession() {
loginID = "";
}
public void ShowLoginForm() {
if(loginForm!=null) {
loginForm.Dispose();
loginForm == null;
}
loginForm = new LoginForm();
loginForm.Show();
loginForm.BringToFront();
}
//etc
}
So the very first thing you do in the Program.cs code is init your main controller
main(string[] args) {
//start a controller
MainController.Instance.Init(passomeargs if needed);
//now fire off our main form
Application.Run(new MainForm());
}
Now all forms there after can access it's data through the MainController
Personally I use commands and have the main controller hide and show forms based on the commands passed in so there is as little logic in the forms as possible. This may or may not lend well to what you are doing.
Good luck

is using private shared objects/variables on class level harmful?

Thanks for your attention and time. I need your opinion on an basic architectural issue please.
In page behind classes I am using a private and shared object and variables (list or just client or simplay int id) to temporary hold data coming from database or class library. This object is used temporarily to catch data and than to return, pass to some function or binding a control.
1st: Can this approach harm any way ? I couldn't analyze it but a thought was using such shared variables may replace data in it when multiple users may be sending request at a time?
2nd: Please comment also on using such variables in BLL (to hold data coming from DAL/database). In this example every time new object of BLL class will be made.
Here is sample code:
public class ClientManager
{
Client objclient = new Client(); //Used in 1st and 2nd method
List<Client> clientlist = new List<Client>();// used in 3rd and 4th method
ClientRepository objclientRep = new ClientRepository();
public List<Client> GetClients()
{
return clientlist = objclientRep.GetClients();
}
public List<Client> SearchClients(string Keyword)
{
return clientlist = objclientRep.SearchClients(Keyword);
}
public Client GetaClient(int ClientId)
{
return objclient = objclientRep.GetaClient(ClientId);
}
public Client GetClientDetailForConfirmOrder(int UserId)
{
return objclientRep.GetClientDetailForConfirmOrder(UserId);
}
}
I am really thankful to you for sparing time and paying kind attention.
If you are creating a new instance of this class for every page refresh, then it won't be a problem as each request will run with its own instances of all the classes.
If you are making new instance for each page and functions like GetClients() are heavy you might want to consider not running it for every page/session but use some caching mechanism instead.
On the other way around - if there is only one instance of this class system wide you need synchronization so one thread will not change data while other thread reading it.

Categories

Resources