Detecting Web vs Windows application - c#

We have a library that is shared in .net between both Web and Windows (forms and console) applications. When used as a Web application, a couple of variables need to be read from cookies. Otherwise it needs to read the same variables from the Windows registry. I cannot seem to work out a good solution to doing this such that the same library compiles for all environments. Specifically, the web libraries for reading cookies would not be included in the Windows apps (and thus break the compile), let alone detecting one environment vs another. Does anyone have a solution to this?

If you host in IIS you can read Environment.GetEnvironmentVariables("APP_POOL_ID") and then act accordingly if the variable exists

Depending on architecture of your library, this information should be provided by the client code. I.e you provide some abstraction layer that will be up to client code to fill in.
I'll show a simple example of what I mean. In your library you have an interface like this:
public interface ISettingsProvider
{
public string GetSettingA();
public string GetSettingB();
}
And then your library code that needs access to settings will have to take a dependency on ISettingsProvider:
public class MyLibraryClient
{
private readonly ISettingsProvider settingsProvider;
public MyLibraryClient(ISettingsProvider settingsProvider)
{
this.settingsProvider = settingsProvider;
}
public void MyAwesomeMethod()
{
var settingA = settingsProvider.GetSettingA();
// do more stuff with your settings
}
}
Then your client code should implement ISettingsProvider:
public class WebSettingsProvider : ISettingsProvider
{
public string GetSettingA()
{
// go get the value from cookies
return Cookies["MyCookie1"];
}
public string GetSettingB()
{
// go get the value from cookies
return Cookies["MyCookie2"];
}
}
And very similar thing goes for settings stored in registry.
And when client code is accessing your library, they will have to instantite an instance of settings provider and give it to you.
This way your library does not know anything about web or Windows. You got to keep your code cleaner and it is all a lot more testable. And you don't have to take dependencies on System.Web and ultimately push that depdency on client code that does not work with web, i.e. Windows applications.
I know you have said you are limited in the amount of changes you can do. My answer to this is: you can't make an omlet without breaking eggs. This will be the most clean way to do what you want, everything else will have drawbacks.

In a Web-Environment you should have HttpContext.Current. If you are calling the same from the Console (or a WinForms-Application) this should be null instead of the Context.
To access this you need a reference to Sytem.Web. There should be no issue when you add this reference and access your backend from the Winforms-Application.
Example:
public bool ImInDaWeb() {
return System.Web.HttpContext.Current!=null;
}
Even in a web-application, HttpContext.Current can be null, but as you are needing this detection for reading/writing cookies you will have to detect this within a valid request already (and not on Application start for example).

Related

StructureMap and HTTP request-scoped services - why is my service created twice in a single scope?

I have an ASP.NET MVC application using StructureMap.
I have created a service called SecurityContext which has a static Current property. A simplified version looks like this:
public class SecurityContext : ISecurityContext
{
public bool MyProperty { get; private set; }
public static SecurityContext Current
{
get
{
return new SecurityContext() { MyProperty = true };
}
}
}
I've hooked this up in my StructureMap registry as follows:
For<ISecurityContext>().Use(() => SecurityContext.Current);
My understanding of this Linq expression overload of the Use method is that the returned concrete object is the same for the entire HTTP request scope.
However, I've set up a test case where my context interface is injected in two places, once in the controller's constructor and again using the SetterProperty attribute in the base class my view inherits from.
When debugging I observe the Current static method being hit twice so clearly my assumptions are wrong. Can anyone correct what I'm doing here? The reason I want this request-scoped is because I'm loading certain data into my context class from the database so I don't want this to happen multiple times for a given page load.
Thanks in advance.
The default lifecycle for a configuration is Transient, thus each request for an ISecurityContext will create a new instance of SecurityContext. What I think you want is to use the legacy HttpContext lifecycle.
Include the StructureMap.Web nuget package. Then change your configuration to the following:
For<ISecurityContext>()
.Use(() => SecurityContext.Current)
.LifeCycleIs<HttpContextLifecycle>();
More information on lifecyles can be found here.
The HttpContextLifecycle is obsolete, however I do not know if or when it will be removed. The StructureMap team does recommend against using this older ASP.Net lifecycle. They state in the documentation that most modern web frameworks use a nested container per request to accomplish the same scoping. Information about nested containers can be found here.
I don't know if the version of ASP.Net MVC you are using is considered a modern web framework. I doubt it is because ASP.Net Core 1.0 is the really the first in the ASP.Net line to fully embrace the use of DI. However, I will defer to #jeremydmiller on this one.

What RPC technology can I use to call a compiled assembly (rather than my own class) in C#?

I want to access a .NET compiled assembly through RPC (the calling code is Python but that is not really relevant).
The assembly represents an API to a running third-party application (Autodesk AutoCAD, for example). It contains several namespaces which contain static classes which contain API objects. I need to access all kinds of stuff in that object hierarchy: properties, objects, methods and, perhaps most complex, transactions that use IDisposable interface (that essentially means that state, i.e. objects storage, should be maintained between RPC calls).
Rather than continuing to develop my own solution (which uses ZeroMQ messaging and reflection-based call dispatch), I wonder what RPC technology would suit my needs.
I looked into basic examples of popular libraries that implement JSON-RPC and SOAP. I see that these libraries demand that you inherit your callable class from their base classes and put attributes into class declaration, for example
[SoapMethod("RequestResponseMethod")]
in order for RPC to work. Obviously, I cannot do that in the case of an external pre-compiled assembly.
I would like to know if JSONRPC or SOAP are indeed the wrong choice for the task that I described or there actually is a way to make RPC work with an external assembly that I don't know about.
Any guidance, comments or basic advice would be much appreciated since I have no experience using any of the existing RPC technologies.
If you are talking about JSON / SOAP I guess you are using HTTP, which is stateless => you need to supply some kind of "state variable". This can be done via e.g. a cookie or like in my examle:
To access your external API create a "wrapper service" (using WCF or "old-school web-services"):
public class MyApiAccess : IMyApiService
{
private static Dictionary<int, MyAPI> apiInstances = new Dictionary<int, MyAPI>();
public int StartSession()
{
var api = new MyAPI();
int id = api.Id; // or some other way to get an unique id
apiInstances.Add(id, api);
return id;
}
public void EndSession(int sessionId)
{
// ensure "sessionId" is valid
var api = apiInstances[sessionId];
api.Dispose();
apiInstances.Remove(api);
}
public MyType MyMethod(myParameter param)
{
// ensure "sessionId" is valid
var api = apiInstances[sessionId];
return api.MyMethod(param);
}
}
This should give you a starting point how such a service could be implemented.

How to configure ASMX web service URL from remote source

We are working on a legacy C# enterprise app. Its client uses several web services, whose URLs, among lots of other settings, are read from the local app.config file. We want to migrate these settings into a global DB to simplify their management. However, I can't figure out how (and whether) it is possible to migrate the web service URLs. These are read from the service client code generated by VS and I can't seem to find a way to tell VS to use a different settings provider than the one generated into Settings.Designer.cs .
We can overwrite the service facade's Url property with the value we want, after it is created - this is the solution currently used in several places in the code. However, I wouldn't like to touch every part of our codebase where any of these services is used (now and in the future). Even less would I like to modify generated code.
There has to be a better, cleaner, safer solution - or is there?
Btw our app runs on .NET 2.0 and we won't migrate to newer versions of the platform in the foreseeable future.
The Refernce.cs file that is generated by the Visual Studio indicates that the URL of the webservice will be retrieved from the settings:
this.Url = global::ConsoleApplication1.Properties.
Settings.Default.ConsoleApplication1_net_webservicex_www_BarCode;
I believe that John Saunders gave you a wonderful suggestion in his comment. You need a SettingsProvider class which:
...defines the mechanism for storing configuration data used in the
application settings architecture. The .NET Framework contains a
single default settings provider, LocalFileSettingsProvider, which
stores configuration data to the local file system. However, you can
create alternate storage mechanisms by deriving from the abstract
SettingsProvider class. The provider that a wrapper class uses is
determined by decorating the wrapper class with the
SettingsProviderAttribute. If this attribute is not provided, the
default, LocalFileSettingsProvider, is used.
I don't know how much you have progressed following this approach, but it should go pretty straighforward:
Create the SettingsProvider class:
namespace MySettings.Providers
{
Dictionary<string, object> _mySettings;
class MySettingsProvider : SettingsProvider
{
// Implement the constructor, override Name, Initialize,
// ApplicationName, SetPropertyValues and GetPropertyValues (see step 3 below)
//
// In the constructor, you probably might want to initialize the _mySettings
// dictionary and load the custom configuration into it.
// Probably you don't want make calls to the database each time
// you want to read a setting's value
}
}
Extend the class definition for the project's YourProjectName.Properties.Settings partial class and decorate it with the SettingsProviderAttribute:
[System.Configuration.SettingsProvider(typeof(MySettings.Providers.MySettingsProvider))]
internal sealed partial class Settings
{
//
}
In the overridden GetPropertyValues method, you have to get the mapped value from the _mySettings dictionary:
public override SettingsPropertyValueCollection GetPropertyValues(
SettingsContext context,
SettingsPropertyCollection collection)
{
var spvc = new SettingsPropertyValueCollection();
foreach (SettingsProperty item in collection)
{
var sp = new SettingsProperty(item);
var spv = new SettingsPropertyValue(item);
spv.SerializedValue = _mySettings[item.Name];
spv.PropertyValue = _mySettings[item.Name];
spvc.Add(spv);
}
return spvc;
}
As you can see in the code, in order to do that, you need to know the setting name as it was added in the app.config and the Settings.settings when you have added the reference to the web service (ConsoleApplication1_net_webservicex_www_BarCode):
<applicationSettings>
<ConsoleApplication30.Properties.Settings>
<setting name="ConsoleApplication1_net_webservicex_www_BarCode"
serializeAs="String">
<value>http://www.webservicex.net/genericbarcode.asmx</value>
</setting>
</ConsoleApplication30.Properties.Settings>
</applicationSettings>
This is a very simple example, but you might use a more complex object to store the configuration information in conjunction with other properties available in the context such as item.Attributes or context in order to get the proper configuration value.

what are the %Field in returned list from web service?

I'm starting my journey in the web web service world, please excuse me if my question is very noob.
After calling web service, I got the result in a List object that I defined, but the strange thing for me is that every entry in the list is duplicated, the real one (which I defined) and the other new one with +"Field", like:
aStatus.Result
and
aStatus.resultField
Please see the attached image,
my question is what is the %Field, and why its coming?
Thanks,
They are simply the private backing fields for the public properties, so nothing to worry about. In the C# code generated by Visual Studio for the web service proxy you will see things like this:
private string subscriptionPINField;
public string SubscriptionPIN
{
get
{
return this.subscriptionPINField;
}
set
{
this.subscriptionPINField = value;
}
}

Proper use of [Import] attribute in MEF

I'm learning MEF and I wanted to create a simple example (application) to see how it works in action. Thus I thought of a simple translator. I created a solution with four projects (DLL files):
Contracts
Web
BingTranslator
GoogleTranslator
Contracts contains the ITranslate interface. As the name applies, it would only contain contracts (interfaces), thus exporters and importers can use it.
public interface ITranslator
{
string Translate(string text);
}
BingTranslator and GoogleTranslator are both exporters of this contract. They both implement this contract and provide (export) different translation services (one from Bing, another from Google).
[Export(typeof(ITranslator))]
public class GoogleTranslator: ITranslator
{
public string Translate(string text)
{
// Here, I would connect to Google translate and do the work.
return "Translated by Google Translator";
}
}
and the BingTranslator is:
[Export(typeof(ITranslator))]
public class BingTranslator : ITranslator
{
public string Translate(string text)
{
return "Translated by Bing";
}
}
Now, in my Web project, I simply want to get the text from the user, translate it with one of those translators (Bing and Google), and return the result back to the user. Thus in my Web application, I'm dependent upon a translator. Therefore, I've created a controller this way:
public class GeneralController : Controller
{
[Import]
public ITranslator Translator { get; set; }
public JsonResult Translate(string text)
{
return Json(new
{
source = text,
translation = Translator.Translate(text)
});
}
}
and the last piece of the puzzle should be to glue these components (parts) together (to compose the overall song from smaller pieces). So, in Application_Start of the Web project, I have:
var parts = new AggregateCatalog
(
new DirectoryCatalog(Server.MapPath("/parts")),
new DirectoryCatalog(Server.MapPath("/bin"))
);
var composer = new CompositionContainer(parts);
composer.ComposeParts();
in which /parts is the folder where I drop GoogleTranslator.dll and BingTranslator.dll files (exporters are located in these files), and in the /bin folder
I simply have my Web.dll file which contains importer. However, my problem is that, MEF doesn't populate Translator property of the GeneralController with the required translator. I read almost every question related to MEF on this site, but I couldn't figure out what's wrong with my example. Can anyone please tell me what I've missed here?
OK what you need to do is (without prescribing for performance, this is just to see it working)
public class GeneralController : Controller
{
[Import]
public ITranslator Translator { get; set; }
public JsonResult Translate(string text)
{
var container = new CompositionContainer(
new DirectoryCatalog(Path.Combine(HttpRuntime.BinDirectory, "Plugins")));
CompositionBatch compositionBatch = new CompositionBatch();
compositionBatch.AddPart(this);
Container.Compose(compositionBatch);
return Json(new
{
source = text,
translation = Translator.Translate(text)
});
}
}
I am no expert in MEF, and to be frank for what I use it for, it does not do much for me since I only use it to load DLLs and then I have an entry point to dependency inject and from then on I use DI containers and not MEF.
MEF is imperative - as far as I have seen. In your case, you need to pro-actively compose what you need to be MEFed, i.e. your controller. So your controller factory need to compose your controller instance.
Since I rarely use MEFed components in my MVC app, I have a filter for those actions requiring MEF (instead of MEFing all my controllers in my controller facrory):
public class InitialisePluginsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
CompositionBatch compositionBatch = new CompositionBatch();
compositionBatch.AddPart(filterContext.Controller);
UniversalCompositionContainer.Current.Container.Compose(
compositionBatch);
base.OnActionExecuting(filterContext);
}
}
Here UniversalCompositionContainer.Current.Container is a singleton container initialised with my directory catalogs.
My personal view on MEF
MEF, while not a DI framework, it does a lot of that. As such, there is a big overlap with DI and if you already use DI framework, they are bound to collide.
MEF is powerful in loading DLLs in runtime especially when you have WPF app where you might be loading/unloading plugins and expect everything else to work as it was, adding/removing features.
For a web app, this does not make a lot of sense, since you are really not supposed to drop a DLL in a working web application. Hence, its uses are very limited.
I am going to write a post on plugins in ASP.NET MVC and will update this post with a link.
MEF will only populate imports on the objects which it constructs itself. In the case of ASP.NET MVC, it is ASP.NET which creates the controller objects. It will not recognize the [Import] attribute, so that's why you see that the dependency is missing.
To make MEF construct the controllers, you have to do the following:
Mark the controller class itself with [Export].
Implement a IDependencyResolver implementation which wraps the MEF container. You can implement GetService by asking the MEF container for a matching export. You can generate a MEF contract string from the requested type with AttributedModelServices.GetContractName.
Register that resolver by calling DependencyResolver.SetResolver in Application_Start.
You probably also need to mark most of your exported parts with [PartCreationPolicy(CreationPolicy.NonShared)] to prevent the same instance from being reused in several requests concurrently. Any state kept in your MEF parts would be subject to race conditions otherwise.
edit: this blog post has a good example of the whole procedure.
edit2: there may be another problem. The MEF container will hold references to any IDisposable object it creates, so that it can dispose those objects when the container itself is disposed. However, this is not appropriate for objects with a "per request" lifetime! You will effectively have a memory leak for any services which implement IDisposable.
It is probably easier to just use an alternative like AutoFac, which has a NuGet package for ASP.NET MVC integration and which has support for per-request lifetimes.
As #Aliostad mentioned, you do need to have the composition initialise code running during/after controller creation for it to work - simply having it in the global.asax file will not work.
However, you will also need to use [ImportMany] instead of just [Import], since in your example you could be working with any number of ITranslator implementations from the binaries that you discover. The point being that if you have many ITranslator, but are importing them into a single instance, you will likely get an exception from MEF since it won't know which implementation you actually want.
So instead you use:
[ImportMany]
public IEnumerable<ITranslator> Translator { get; set; }
Quick example:
http://dotnetbyexample.blogspot.co.uk/2010/04/very-basic-mef-sample-using-importmany.html

Categories

Resources