How can the below line be replaced in .net4.0 - .net-4.0

How can I write below line of code in .net 4.0:
EventHandlerTaskAsyncHelper asyncHelper = new EventHandlerTaskAsyncHelper(WriteLogMessages);--> this is in .net 4.5
Thanks

EventHandlerTaskAsyncHelper is simply a helper that provides an APM-style (BeginOperation/EndOperation) interface over a Task. A Task does implement IAsyncResult so you can return it directly from a BeginOperation method. The EndOperation method only has to cast its IAsyncResult argument back to a Task and await it. This is shown in the MSDN article
TPL and Traditional .NET Framework Asynchronous Programming:
public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state)
{
Task<string> f = Task<string>.Factory.StartNew(_ => Compute(decimalPlaces), state);
if (ac != null) f.ContinueWith((res) => ac(f));
return f;
}
public string Compute(int numPlaces)
{
...
}
public string EndCalculate(IAsyncResult ar)
{
return ((Task<string>)ar).Result;
}
The EventHandlerTaskAsyncHelper class just makes it easier to write such code, with some checks for already completed tasks etc. The concept isn't something specific to .NET 4.5.
That said, the best solution would be to upgrade the rest of your code to .NET 4.5, not try to backport the application to .NET 4.0. While you can get some of the 4.5 functionality with the Microsoft.Bcl.Async package, significant parts will be missing. Newer libraries like TPL Dataflow, Immutable Collections etc simply require .NET 4.5 to work.
Unless you target Windows XP there is no reason to remain in .NET 4.0, especially when the application is already written in 4.5.

The main problem of such migration is that you are trying to fit into architecture solution available only in .NET 4.5. According MSDN, EventHandlerTaskAsyncHelper the only purpose is:
Converts task-returning asynchronous methods into methods that use the asynchronous programming model used in previous versions of ASP.NET and that is based on begin and end events.
And Remarks section:
To handle asynchronous tasks in ASP.NET 4.5, you implement the logic to return a task as a TaskEventHandler delegate. This model of asynchronous task-based programming supersedes the model used in previous versions of ASP.NET, which bases all event handling on begin and end events. ...
So this class is used for the wrapping other code to fit into the new version of ASSP.NET MVC site. Thus you have to reconsider the whole class diagram and architecture of your application according rules of the MVC version you'll be using in your project.
May be this thread will be a good start:
ASP.NET MVC - IHttpModule, Asynchronous Event Handler, EventHandlerTaskAsyncHelper

Related

Read assembly version of class library Project from .netCore web app project

I have 4 web applications based on .net core. all of them call a business logic layer (class library)
i want my version to get updated on all 4 web applications.
I have tried to make a static class on my business logic layer. and on this class i have a property that gets the version as the following:
Assembly.GetEnteryAssembly().GetName().Version
i tried to call this static class from one of the applications, sadly it brings the version of the web application instead of the class library version.
I want a code that always brings me the version of class library regardless from where it is called.
You can use Assembly.GetAssembly(typeof(YourClass)), being YourClass any class within desired assembly.
You can use typeof(Startup).Assembly.GetName().Version.ToString()

SimpleInjector With API, How to do late binding with SimpleInjector? [duplicate]

(Related to this question, EF4: Why does proxy creation have to be enabled when lazy loading is enabled?).
I'm new to DI, so bear with me. I understand that the container is in charge of instantiating all of my registered types but in order to do so it requires a reference to all of the DLLs in my solution and their references.
If I weren't using a DI container, I wouldn't have to reference the EntityFramework library in my MVC3 app, only my business layer, which would reference my DAL/Repo layer.
I know that at the end of the day all DLLs are included in the bin folder but my problem is having to reference it explicitly via "add reference" in VS in order to be able to publish a WAP with all necessary files.
If I wasn't using a DI container, I wouldn't have to reference EntityFramework library in my MVC3 app, only my business layer which would reference my DAL/Repo layer.
Yes, that's exactly the situation DI works so hard to avoid :)
With tightly coupled code, each library may only have a few references, but these again have other references, creating a deep graph of dependencies, like this:
Because the dependency graph is deep, it means that most libraries drag along a lot of other dependencies - e.g. in the diagram, Library C drags along Library H, Library E, Library J, Library M, Library K and Library N. This makes it harder to reuse each library independently from the rest - for example in unit testing.
However, in a loosely coupled application, by moving all the references to the Composition Root, the dependency graph is severely flattened:
As illustrated by the green color, it's now possible to reuse Library C without dragging along any unwanted dependencies.
However, all that said, with many DI Containers, you don't have to add hard references to all required libraries. Instead, you can use late binding either in the form of convention-based assembly-scanning (preferred) or XML configuration.
When you do that, however, you must remember to copy the assemblies to the application's bin folder, because that no longer happens automatically. Personally, I rarely find it worth that extra effort.
A more elaborate version of this answer can be found in this excerpt from my book Dependency Injection, Principles, Practices, Patterns.
If I wasn't using an DI container, I wouldn't have to reference
EntityFramework library in my MVC3 app
Even when using a DI container, you don't have to let your MVC3 project reference Entity Framework, but you (implicitly) choose to do this by implementing the Composition Root (the startup path where you compose your object graphs) inside your MVC3 project. If you are very strict about protecting your architectural boundaries using assemblies, you can move your presentation logic to a different project.
When you move all MVC related logic (controllers, etc) from the startup project to a class library, it allows this presentation layer assembly to stay disconnected from the rest of the application. Your web application project itself will become a very thin shell with the required startup logic. The web application project will be the Composition Root that references all other assemblies.
Extracting the presentation logic to a class library can complicate things when working with MVC. It will be harder to wire everything up, since controllers are not in the startup project (while views, images, CSS files, must likely stay in the startup project). This is probably doable but will take more time to set up.
Because of the downsides I generally advice to just keep the Composition Root in the web project. Many developers don’t want their MVC assembly to depend on the DAL assembly, but that should not be a problem. Don't forget that assemblies are a deployment artifact; you split code into multiple assemblies to allow code to be deployed separately. An architectural layer on the other hand is a logical artifact. It's very well possible (and common) to have multiple layers in the same assembly.
In this case you'll end up having the Composition Root (layer) and the Presentation Layer in the same web application project (thus in the same assembly). And even though that assembly references the assembly containing the DAL, the Presentation Layer still does not reference the DAL—this is a big distinction.
Of course, when you do this, you're losing the ability for the compiler to check this architectural rule at compile time. But most architectural rules actually can't be checked by the compiler. In case you're afraid your team won't follow the architectural rules, I'd advise introducing code reviews, which is an important practice to increase code quality, consistency and improve the skills of a team. You can also use tools like NDepend (which is commercial), which help you verifying your architectural rules. When you integrate NDepend with your build process, it can warn you when somebody checked code in that violates such architectural rule.
You can read a more elaborate discussion on how the Composition Root works in chapter 4 of my book Dependency Injection, Principles, Practices, Patterns.
If I wasn't using an DI container, I wouldn't have to reference
EntityFramework library in my MVC3 app, only my business layer which
would reference my DAL/Repo layer.
You can create a seperate project called "DependencyResolver".
In this project you have to reference all your libraries.
Now the UI Layer doesn't need NHibernate/EF or any other not UI relevant library except of Castle Windsor to be referenced.
If you want to hide Castle Windsor and DependencyResolver from your UI layer you could write an HttpModule which calls the IoC registry stuff.
I have only an example for StructureMap:
public class DependencyRegistrarModule : IHttpModule
{
private static bool _dependenciesRegistered;
private static readonly object Lock = new object();
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, args) => EnsureDependenciesRegistered();
}
public void Dispose() { }
private static void EnsureDependenciesRegistered()
{
if (!_dependenciesRegistered)
{
lock (Lock)
{
if (!_dependenciesRegistered)
{
ObjectFactory.ResetDefaults();
// Register all you dependencies here
ObjectFactory.Initialize(x => x.AddRegistry(new DependencyRegistry()));
new InitiailizeDefaultFactories().Configure();
_dependenciesRegistered = true;
}
}
}
}
}
public class InitiailizeDefaultFactories
{
public void Configure()
{
StructureMapControllerFactory.GetController = type => ObjectFactory.GetInstance(type);
...
}
}
The DefaultControllerFactory doesn't use the IoC container directly, but it delegates to IoC container methods.
public class StructureMapControllerFactory : DefaultControllerFactory
{
public static Func<Type, object> GetController = type =>
{
throw new InvalidOperationException("The dependency callback for the StructureMapControllerFactory is not configured!");
};
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
return base.GetControllerInstance(requestContext, controllerType);
}
return GetController(controllerType) as Controller;
}
}
The GetController delegate is set in a StructureMap Registry (in Windsor it should be an Installer).
There is a dependency : if an object instantiate another object.
There is no dependency : if an object expects an abstraction (contructor injection, method injection ...)
Assembly References (referencing dll, webservices..) are independant from the dependency concept, because to resolve an abstraction and be able to compile the code, the layer must reference it.

Intellisense in VS 2012 RC not working for SignalR classes

I have imported SignalR Nuget package and SignalR sample is working well in my project. But even after having all required using statements I can't get the intellisense working for the classes in SignalR (like Hub class).
The hubs proxy is dynamically generated at runtime, so you won't get any intellisense for it.
You can use Hubify.exe (see Hubify-section on http://weblogs.asp.net/davidfowler/archive/2012/06/10/signalr-0-5-1-released.aspx ) to generate a static javascript-file.
Or you can create your own T4-Template that does the same thing. See: https://github.com/SignalR/SignalR/issues/106
Update:
Regarding intellisense for C#
You won't get intellisense for Clients and Caller, since they are dynamic.
Absence of compile-time type checking leads to the absence of IntelliSense as well. Because the C# compiler doesn't know the type of the object, it can't enumerate its properties and methods. This problem might be solved with additional type inference, as is done in the IronPython tools for Visual Studio, but for now C# doesn't provide it.
http://visualstudiomagazine.com/articles/2011/02/01/understanding-the-dynamic-keyword-in-c4.aspx
public class Chat : Hub
{
public void Send(string message)
{
// No intellisense for addMessage, sorry
Clients.addMessage(message);
}
}
look at the SignalR documentation here
the Hub.Caller and Clients are dynamic in nature.
dynamic is a new keyword added in .Net 4 and dosent support compile time checking so you cannot get intellisense for dynamic objects. all the dynamic objects are checked at runtime only. so even if you your self create a dynamic object like
dynamic d = new ExpandoObject();
and try to do this "d.". you wont get any intellisense because the framework dosent know whats all is present in the dynamic object. and will be discovered only at runtime.

protobuf-net v2 and Monotouch : How does it mix?

I have been trying to use protobuf-net with MonoTouch but I have no idea how, and despite having heard that it is possible, I haven't been able to find any tutorial or any example that actually work.
It was confirmed by Marc Gravell on his blog that it does work on MonoTouch. I have also looked through the blogs of the two people he states in this article, but I haven't found anything related to protobuf.
Having no lead on the subject, i decided to download protobuf-net and try it out anyway. So I created the following object for testing purposes :
[ProtoContract]
public class ProtoObject
{
public ProtoObject()
{
}
[ProtoMember(1)]
public byte[] Bytes { get; set; }
}
and I tried to send it through WCF from a service running on windows using a [ServiceContract] interface with
[OperationContract]
ProtoObject GetObject();
but the instance of ProtoObject recieved on the device is always null. This is not really unexpected since i have read that to make protobuf-net work with WCF you need to modify the app.config/web.config.
It's a little hard to accomplish since a MonoTouch project has no app.config, but I did not yet give up. To replace the app.config, I tried to add the ProtoEndpointBehavior to the client's endpoint's behaviors programmatically, and there I hit a wall. ProtoBuf.ServiceModel.ProtoEndpointBehavior, available on .NET 3.0 implementation of protobuf-net is not available on the iOS release.
How would I go about using protobuf-net to deserialize objects received from a windows-based WCF endpoint using protobuf-net serialization.
It is actually pretty much the same as described in this blog entry by Friction Point Studios. Since meta-programming on the device is not really an option, the trick is to pre-generate a serialization dll. This can be done by creating a small console exe (this is just a tool - it isn't designed to be pretty) that configures a RuntimeTypeModel (by adding the types you are interested in), and then call .Compile(...):
var model = TypeModel.Create();
model.Add(typeof (ProtoObject), true);
model.Compile("MySerializer", "MySerializer.dll");
This generates a serializer dll; simply reference this dll (along with the iOS version protobuf-net), and use the serializer type in the dll to interact with your model:
var ser = new MySerializer();
ser.Serialize(dest, obj); // etc
Just to bring this up to date there are a few issues with using WCF + Protobuf on MonoTouch. As you have observed the current releases of System.ServiceModel and protobuf light for ios don't include all the necessary bits.
However if you go and get the full System.ServiceModel from the Mono repository on GitHub and build it against the full Protobuf source then you can get it to work; I have done so.
You need to generate a serialisation assembly using the precompile tool then edit the ProtoOperationBehavior attribute to give it some way to reference your serialisation assembly. All the changes are too extensive to document here but it can be done and it is a lot faster than DatacontractSerializer which is pretty awful on iOS.

Castle Monorail and Ninject 2 integration

I want to use Ninject 2 on Castle Monorail. Searching on google, I found nothing about this.
I know there is Windsor which magically can integrate with Monorail, same as Ninject (with MVC extension) with ASP.NET MVC.
What steps I need to do to integrate DI framework (other than Windsor) with Monorail ? (any website link, tutorial, or code sample (preferably using Ninject 2))
fyi, I'm using C#
I don't think there's any documentation about this, but it's quite simple really. There's no magic to it. Since MonoRail and Windsor are completely separate projects, all you have to do is see how they integrate, then do the same for Ninject instead of Windsor.
More concretely, start with the MonoRailFacility which is the root of the integration. Instead of a Windsor facility, you'd use a Ninject module. Note it registers some components: IControllerTree, IWizardPageFactory, etc. The most important is IControllerFactory, which lets you resolve controllers from the container (in your case Ninject). You can leave all others as default for now (e.g. IFilterFactory/DefaultFilterFactory), and implement them as needed (i.e. when you need container control of filters).
Then call ServiceProviderLocator.Instance.AddLocatorStrategy(new NinjectAccessorStrategy()); where NinjectAccessorStrategy is an implementation of IAccessorStrategy which returns the Ninject kernel as a Castle.Core.IServiceProviderEx (which is nothing but a trivial extension of System.IServiceProvider). Since the Ninject kernel already implements IServiceProvider, it's trivial to write an adapter for IServiceProviderEx.