Service fabric Statefulservice throwing error at CreateServiceRemotingListener - azure-service-fabric

I am getting the below error. I have added required nuget package Microsoft.ServiceFabric.Services.Remoting v3.0.472.
'VotingDataService' does not contain a definition for
'CreateServiceRemotingListener' and no extension method
'CreateServiceRemotingListener' accepting a first argument of type
'VotingDataService' could be found (are you missing a using directive
or an assembly reference?)
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting;
using Microsoft.ServiceFabric.Services.Remoting.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using System;
using System.Collections.Generic;
using System.Fabric;
using System.Threading.Tasks;
namespace VotingDataService
{
public interface IVotingDataService2 : IService
{
Task<int> AddVote(string voteItem);
}
/// <summary>
/// The FabricRuntime creates an instance of this class for each service type instance.
/// </summary>
internal sealed class VotingDataService : StatefulService, IVotingDataService2
{
public VotingDataService(StatefulServiceContext context)
: base(context)
{ }
public Task<int> AddVote(string voteItem)
{
throw new NotImplementedException();
}
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
return new[]
{
new ServiceReplicaListener(context =>
this.CreateServiceRemotingListener(context))
};
}
}
}

Don't forget to implement an interface that extends IService. The extension method works on IService.
(IMyService in the example)
More info here.

Related

Error while creating remote listener in service fabric stateful service (.NET Core application)

Error: Does not contain a definition for 'CreateServiceRemotingListener' and no extension method 'CreateServiceRemotingListener' accepting a first argument of type could be found (are you missing a using directive or an assembly reference?)
Below are the steps which I followed,
Created an interface that implements IService.
`
using Microsoft.ServiceFabric.Services.Remoting;
using System.Threading.Tasks;
public interface IFileService: IService
{
Task<string> GetStringByName(string name);
}
`
Included following packages in stateful service named as FileService.
`
using System. Fabric;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
`
Implemented IFileService interface in FileService.
`
internal sealed class FileService : StatefulService, IFileService
{
public FileService(StatefulServiceContext context)
: base(context)
{ }
public FileService(StatefulServiceContext context, IReliableStateManagerReplica stateManagerReplica) : base(context, stateManagerReplica)
{
}
public Task<string> GetStringByName(string name)
{
return Task.FromResult<string>(name);
}
/// <summary>
/// Optional override to create listeners (e.g., HTTP, Service Remoting, WCF, etc.) for this service replica to handle client or user requests.
/// </summary>
/// <remarks>
/// For more information on service communication, see https://aka.ms/servicefabricservicecommunication
/// </remarks>
/// <returns>A collection of listeners.</returns>
protected override IEnumerable<ServiceReplicaListener>
CreateServiceReplicaListeners()
{
return new[] { new ServiceReplicaListener(this.CreateServiceRemotingListener) };
}}
`
The ServiceRemotingExtensions class is located in Microsoft.ServiceFabric.Services.Remoting.Runtime namespace (that isn't included).
The important point to mention is that CreateServiceRemotingListener is deprecated. The recommended method to use is CreateServiceRemotingReplicaListeners.
Hope this helps.
UPDATE 2019/01/28
Here is the sample code:
using System.Collections.Generic;
using System.Fabric;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting;
using Microsoft.ServiceFabric.Services.Remoting.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
namespace JustService
{
public interface IRemotingService : IService
{
// Remoting methods
}
internal sealed class JustService : StatefulService, IRemotingService
{
public JustService(
StatefulServiceContext context)
: base(context)
{
}
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
return this.CreateServiceRemotingReplicaListeners();
}
}
}
Please note that in order to use CreateServiceRemotingReplicaListeners extension method the service should implement an interface derived from IService.

Will my Unit of Work implementation cause memory leak?

I implemented my repository pattern and unit of work in the following way:
How to create a simple data access layer
How to create unit of work
and I was asked if create multiple instance of my database (which is the unit of work) will cause memory leak? and what are the downside of such implementation? or is the implementation done right?
Thanks.
What you should worry about is the creation of the DbContext as this is expensive.
I typically use one DbContext per request instead of creating multiple DbContext instances everywhere.
I store it in the HttpContext object and dispose of it at the end of the request.
You can find more info on it here
Find below my modified implementation. (original was from the link above and used ObjectContext).
My context class
using System.Data.Entity;
using System.Data.Objects;
using System.Web;
using Fot.Admin.Models;
namespace Context
{
public static class ContextManager
{
internal const string DB = "MY_DB_CONTEXT";
/// <summary>
/// Get an instance that lives for the life time of the request per user and automatically disposes.
/// </summary>
/// <returns>Model</returns>
public static T AsSingleton<T>() where T : DbContext, new()
{
HttpContext.Current.Items[DB] = (T)HttpContext.Current.Items[DB] ?? new T();
return (T)HttpContext.Current.Items[DB];
}
}
}
My Context Module
using System;
using System.Data.Entity;
using System.Data.Objects;
using System.Web;
namespace Context
{
/// <summary>
/// Entity Module used to control an Entities DB Context over the lifetime of a request per user.
/// </summary>
public class ContextModule : IHttpModule
{
private const string DB = ContextManager.DB;
void context_EndRequest(object sender, EventArgs e)
{
Dispose();
}
#region IHttpModule Members
public void Dispose()
{
if(HttpContext.Current != null)
{
if (HttpContext.Current.Items[DB] != null)
{
var entitiesContext = (DbContext) HttpContext.Current.Items[DB];
entitiesContext.Dispose();
HttpContext.Current.Items.Remove(DB);
}
}
}
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(context_EndRequest);
}
#endregion
}
}
In my web.config under <httpModules> i add this below.
<add name="ContextModule" type="Context.ContextModule" />
This ensures that the end_Request is called after every request so you can dispose the context properly.
When you need the DbContext usage is as below.
var Context = ContextManager.AsSingleton<MyDBContext>();

Generated moles type for a static internal class is not accessible in test class

I am trying to get access to an internal static class to override some of its methods so that I can test classes that depend on that class
From what I read that should be possible but I am not obviously not understanding everything as even a simple example seems to fail to generate a mole type for the internal static class.
I have two classes in a namespace and assembly
namespace SimpleClassToTest
{
public class Class1
{
public string SayOla() { return Class2.ReturnMe("Ola"); }
}
}
namespace SimpleClassToTest
{
internal static class Class2
{
static public string ReturnMe(string m)
{
return m;
}
}
}
In AssemblyInfo.cs I also have
[assembly: InternalsVisibleTo("SimpleClassToTest")]
[assembly: InternalsVisibleTo("SimpleClassToTest.Moles")]
In the test project I have a single test class
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SimpleClassToTest;
using SimpleClassToTest.Moles;
namespace SimpleClassToTest.Moles
{
[TestClass]
public class UnitTest1
{
public UnitTest1()
{
}
[TestMethod]
[HostType("Moles")]
public void TestMethod1()
{
Class1 c1 = new Class1();
Assert.AreEqual(c1.SayOla(), "Ola");
MClass2.ReturnMeString = (ignored) => { return "ReturnMe"; };
Assert.AreEqual(c1.SayOla(), "ReturnMe");
}
}
}
Unfortunately that is not compiling. The error is
UnitTest1.cs(25,13): error CS0122: 'SimpleClassToTest.Moles.MClass2' is inaccessible due to its protection level
Any tips to get this going would certainly be appreciated!
Thanks!
Peter
PS Tried this both on VS2008 and on VS2010 with moles version Microsoft Moles v0.94.51023.0
(Edit : From Comment Below)
As a workaround, in the unit test:
Type mClass2Type = typeof(SimpleClassToTest.Moles.MClass1)
.Assembly.GetType("SimpleClassToTest.Mole‌​s.MClass2");
PropertyInfo returnMeProp = mClass2Type.GetProperty("ReturnMeString");
Microsoft.Moles.Framework.MolesDelegates.Func<String, String> molesDelegate =
(ignore) => { return "ReturnMe"; };
returnMeProp.SetValue(mClass2Type, molesDelegate, null);
Assert.AreEqual(c1.SayOla(), "ReturnMe");
If your assembly under test is strongly signed, then the moles assembly is also strongly signed, and you must specify the public key in the InternalsVisibleTo attribute. See the section "Code Generation and Compilation" of the moles reference manual for details.
Here is a quote that might be relevant:
... use this snippet as a
starting point to add InternalsVisibleTo attribute to your project.
[assembly: InternalsVisibleTo(“FileSystem.Moles, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e92decb949446f688ab9f6973436c535bf50acd1fd580495aae3f875aa4e4f663ca77908c63b7f0996977cb98fcfdb35e05aa2c842002703cad835473caac5ef14107e3a7fae01120a96558785f48319f66daabc862872b2c53f5ac11fa335c0165e202b4c011334c7bc8f4c4e570cf255190f4e3e2cbc9137ca57cb687947bc”)]

Use repository in referenced dll using entity framework

I have created a DLL that contains lots of authentication and user management that I'm trying to use in a separate project (MVC 3 Website).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Authentication;
namespace TestSite.MVC.Areas.Admin.Controllers
{
public class TestController : Controller
{
AuthenticationRepository authrep = new AuthenticationRepository();
public ActionResult Index()
{
authrep.DeleteUser(1);
return View();
}
}
}
Now this obviously does'nt work, which is understandable.
Is it dependency injection I need here?
And in that case, how would the basic code look for that?
Do I need to add something in the constructor for the referenced DLL?
Try structuring your controller like this:
public class TestController : Controller
{
IAuthenticationRepository AuthenticationRepository { get;set; }
public void TestController (IuthenticationRepository authenticationRepository)
{
this.AuthenticationRepository = authenticationRepository;
}
public ActionResult Index()
{
this.AuthenticationRepository.DeleteUser(1);
return View();
}
}
Create an interface for your repository. You could then use a DI framework (like Ninject for MVC 3) to inject instances of AuthenticationRepository into usages of IAuthenticationRepository.
https://github.com/ninject/ninject/wiki

MVC2 & Ninject2 - Controllers not resolving dependency

I foolishly decided to try something new on a Friday job!
So I have used NuGet to add Ninject.Web.Mvc 2.2.x.x to my .Net MVC2 project.
I've altered my Global.asax.cs
using System.Web.Mvc;
using System.Web.Routing;
using IntegraRecipients;
using Mailer;
using Ninject;
using Ninject.Web.Mvc;
using Ninject.Modules;
namespace WebMailer
{
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Mail", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
return new StandardKernel(new INinjectModule[] { new MailModule()});
}
internal class MailModule : NinjectModule
{
public override void Load()
{
Bind<IMailing>().To<Mailing>();
Bind<IMailingContext>().To<MailingContext>();
Bind<IRecipientContext>().To<RecipientContext>();
}
}
}
}
and I've created a controller like so...
using System.Linq;
using System.Web.Mvc;
using WebMailer.Models;
namespace WebMailer.Controllers
{
[ValidateInput(false)]
public class MailController : Controller
{
private readonly IMailingContext _mailContext;
private readonly IRecipientContext _integraContext;
public MailController(IMailingContext mail,IRecipientContext integra)
{
_mailContext = mail;
_integraContext = integra;
}
public ActionResult Index()
{
return View(_mailContext.GetAllMailings().Select(mailing => new MailingViewModel(mailing)).ToList());
}
}
}
But the controller is still insisting that
The type or namespace name 'IRecipientContext' could not be found (are you missing a using directive or an assembly reference?)
and
The type or namespace name 'IMailingContext' could not be found (are you missing a using directive or an assembly reference?)
My google-fu has failed me and I really hope this is just a silly typo/missing line thing
Thanks in advance
P
Ninject does not change the way assemblies are compiled! It deos not magically add references to other assemblies or add using directives. If you are using interfaces from other assemblies you have to add a using directive and a reference to this assembly.
All Ninject is about is to wire up your application at runtime.
I am have what appears to be a similar problem.
I have a simple WPF Window project with the compiled Ninject.dll linked in. However, the following is giving me errors...
using Ninject;
namespace CatalogueManager
{
public class ServiceLocator
{
public IMainWindowViewModel GetMainWindowViewModel()
{
return Kernel.Get<IMainWindowViewModel>();
}
static IKernel Kernel;
static ServiceLocator()
{
Kernel = new StandardKernel(new NinjectConfiguration());
}
}
}
In particular, "Ninject" namespace and IKernel are prompting the compile time message "type or name space 'X' not found..."