Namespace for Keyword "Populate" C# (MvcMailer) - c#

I've converted my project from .Net framework 4 to 4.5.
I have done this to make use of the Nuget package MvcMailer.
All is good except in the UserMailer class the following code exists:
public virtual MvcMailMessage Welcome()
{
//ViewBag.Data = someObject;
return Populate(x =>
{
x.Subject = "Welcome";
x.ViewName = "Welcome";
x.To.Add("some-email#example.com");
});
}
The Populate word throws an error:
The name 'Populate' does not exist in the current context
To what Namespace does the word Populate belong to?
Or is it an extension?
I can't find anything on the net.

It's a class method of MailerBase controller with this signature (from source code on GitHub):
public virtual MvcMailMessage Populate(Action<MvcMailMessage> action)
To use it you must derive your controller from MailerBase (it's the base class for Mailers. Your mailer should subclass MailerBase).
For example, supposing your controller is named Home, from:
public class Home : Controller {
To:
public class Home : MailerBase {
It's in Mvc.Mailer namespace (same of MvcMailerMessage class) anyway it's not an extension method so you don't even need to worry about it.

Put the cursor on the keyword and hit Alt+Shift+F10. It will show you it's source, and you'll be able to include the whole namespace, or use the keyword just once. It will only work if you have a correct .dll reference in your project.

I think you got the code from this GitHub repository.
https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
public virtual MvcMailMessage Welcome()
{
ViewBag.Name = "Sohan";
return Populate(x =>{
x.viewName = "Welcome";
x.To.Add("sohan39#example.com");
});
}
This code was provided by the Developer of the Package and he showed how to use it to edit the MvcMailer.
If so, the guy there used these namespaces in the top of his C# file.
using Mvc.Mailer;
So, I guess it would be a part of this Namespace. Include it to your project and you're done!

Related

How to pass a variable from one project to another project C#

I have a static variable inside of my main project (mvc), I am wanting to be able to pass/use that variable in my other project (asp.net core 5.0 web api) project. I was reading up on how you can perform this task, one of the ways is using a static variable which I have. I read this post and one of the solutions mentions you can call that static variable from the first project into the other project by calling the namespace of that first project in the first project. However, when I do so it does not let me it says it does not exist. Is there a way to be able to do this?
On the post their example was:
using System.Windows.Forms;
namespace Demo1
{
public class Sample1
{
public static string x = "initial value of 'x";
public void sampleFn1() {x = "value of 'x set in function";}
}
}
namespace Demo2
{
public class Sample2
{
public void sampleFn2(){MessageBox.Show(Demo1.Sample1.x);}
}
}
For me, Project 1 is CustomerApp and Project 2 is Service.Api:
namespace CustomerApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public static Guid uniqueId = Guid.NewGuid();
}
}
Then in my ServiceApi I tried performing the same as the example from the post, but when I call the namespace CustomerApp it does not give me any options to reference it to the other project. Is there a specific using I need to use in order to replicate the example from the post?
namespace Service.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger;
public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;
}
// GET: api/<ValuesController>
[HttpGet]
[Route("sample")]
public ActionResult Get()
{
_logger.LogInformation("Target method invoked.....{#CorrelationId}", CustomerApp.); // here I am trying to perform CustomerApp.Controllers.HomeController.uniqueId.ToString()
}
}
}
You will want to make sure that the static variable is defined in a Class Library project, and that the Web project has a reference to the Class Library project.
The way your code is currently constructed, it looks like both projects are web projects (your first project mentions the HomeController). As much as possible, avoid this type of co-mingling. Move business logic into the class library, and keep the web logic in the web project.
I think you forgot to add the project reference to destination project where you want to use the variable ,
Add reference like this :
right-click on your destination project and select Add > Project Reference
and in final choose the variable project
this will help you
first, if you haven't, add it to the HomeController class (using CustomerApp.Controllers.HomeController;). Your own example does not match the example you reference. In the first example, a static variable is used between two different classes in the same namespaces, but in your example you are trying to operate between different namespaces and different classes.
So if your service is inside your main project you should add.
then you can use it as below.
public ActionResult Get()
{
_logger.LogInformation("Target method invoked.....{#CorrelationId}", HomeController.uniqueId.ToString());
}

A view component named 'PreviewCV' could not be found

I have created a view component.
public class PreviewCVComponent : ViewComponent
{
..
public async Task<IViewComponentResult> InvokeAsync(int id)
{
return View();
}
}
I have added a folder into views/shared/components which is given the name PreviewCV. Under that folder I have added a view called Default.cshtml.
The Component is called from another view. Which is located under views/CV, and has the name CV.cshtml.
I am trying to call the component with the use of
#await Component.InvokeAsync("PreviewCV", new { id = -1 })
This results in:
InvalidOperationException: A view component named 'PreviewCV" could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.
I am using .net core.
--In Models folder
FileName: TestViewComponent.cs
--In TestViewComponent class
[ViewComponent(Name = "TestViewComponent")] //Solution
public class TestViewComponent: ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
Put ViewComponent in suffix solve the problem.
As suggested by Kirk Larkin. I need to include the View in the class.
Using net core 5.0, class name (e.g. PreviewCV) can either be written as PreviewCV OR PreviewCVViewComponent
so
public class PreviewCV : ViewComponent
and
public class PreviewCVViewComponent : ViewComponent
will work fine while below will generate error (same as shown in question)
public class PreviewCVComponent : ViewComponent
Also noticed that attribute didn't have any effect on these
[ViewComponentAttribute]
One solution is to call it like:
#await Component.InvokeAsync(typeof(PreviewCVComponent), new { id = -1 })

No type was found that matches the controller named ***

I am working on an ASP.NET MVC app using oData 4. Up until yesterday they project was in VB.NET. We are now finally attempting to move from VB.NET to C#. I've tried to introduce 2 controllers written in C# into the project and in both instances, receive the dreaded "No type was found that matches the controller named ***" error when attempting to access either controller.
The first one was a new controller. It looks like this:
using System.Data.Entity.Infrastructure;
using System.Net;
using System.Web.Http;
using System.Web.OData;
namespace Controllers
{
public class ORDER_LINE_SUMMARYController : ODataController
{
private Entities db = new Entities();
[EnableQuery()]
public IQueryable<ORDER_LINE_SUMMARY> GetORDER_LINE_SUMMARY()
{
return db.ORDER_LINE_SUMMARY;
}
[EnableQuery()]
public SingleResult<ORDER_LINE_SUMMARY> GetORDER_LINE_SUMMARY([FromODataUri()] decimal key)
{
return SingleResult.Create(db.ORDER_LINE_SUMMARY.Where(ORDER_LINE_SUMMARY => ORDER_LINE_SUMMARY.ID == key));
}
protected override void Dispose(bool disposing)
{
if ((disposing))
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ORDER_LINE_SUMMARYExists(decimal key)
{
return db.ORDER_LINE_SUMMARY.Count(e => e.ID == key) > 0;
}
}
}
In order to make certain that I didn't miss a step in incorporating this new controller, I also tried replacing an existing VB.NET controller with a C# controller and receive the same error. Except for the entity name, the code is essentially identical to the one above, so I'm not positing it here for brevity's sake.
One interesting note, and I think this is germane to the underlying problem. When I added the new C# controller to replace the existing VB.NET one I hadn't yet removed the VB.NET controller from the project. Obviously the class names for both are the same, however; the .NET compiler didn't error or otherwise complain about this. I suspect this issue may be related to attempting to mix C# and VB.NET within the same assembly due to this.
Any suggestions or ideas would be greatly appreciated. TIA.

How to locate image resources in Orchard

I want to get a link to image resource in a MVC view that is part of an Orchard module.
Googling a bit resulted in the following approach:
https://stackoverflow.com/a/9256515/3936440
and its using #Html.ResourceUrl() in views to get the resource URL.
I wonder where the ResourceUrl() comes from as its not documented in MSDN and i cannot use it in my projects either.
Did someone used that approach already and can shed some light on whats missing here?
Update:
I figured it out. The following code works in connection with Orchard modules.
First you need to add a resource manifest to the Orchard module like so
public class ResourceManifest : Orchard.UI.Resources.IResourceManifestProvider
{
public void BuildManifests(Orchard.UI.Resources.ResourceManifestBuilder aBuilder)
{
Orchard.UI.Resources.ResourceManifest lManifest = aBuilder.Add();
string lModulePath = "~/Modules/YourModuleName";
lManifest.DefineResource("ProfilePicture", "User1").SetUrl(lModulePath + "/Images/User1.png");
}
}
Then you extend the Html object:
// This class adds so called "extension methods" to class System.Web.Mvc.HtmlHelper
public static class HtmlHelperExtensions
{
// This method retrieves the URL of a resource defined in ResourceManifest.cs via the Orchard resource management system
public static string ResourceUrl(this System.Web.Mvc.HtmlHelper aHtmlHelper, string aResourceType, string aResourceName)
{
// note:
// resolving Orchard.UI.Resources.IResourceManager via work context of orchard because
// - calling System.Web.Mvc.DependencyResolver.Current.GetService() does not work as it always returns null at this point
// - constructor parameter injection is not allowed in static classes
// - setting the resource manager from another class that uses constructor parameter injection does not work as it causes a "circular component dependency "
Orchard.WorkContext lWorkContext = Orchard.Mvc.Html.HtmlHelperExtensions.GetWorkContext(aHtmlHelper);
Orchard.UI.Resources.IResourceManager lResourceManager = (Orchard.UI.Resources.IResourceManager)lWorkContext.Resolve<Orchard.UI.Resources.IResourceManager>();
if (lResourceManager != null)
{
Orchard.UI.Resources.RequireSettings lSettings = new Orchard.UI.Resources.RequireSettings { Type = aResourceType, Name = aResourceName, BasePath = aResourceType };
Orchard.UI.Resources.ResourceDefinition lResource = lResourceManager.FindResource(lSettings);
if (lResource != null)
{
Orchard.UI.Resources.ResourceRequiredContext lContext = new Orchard.UI.Resources.ResourceRequiredContext { Resource = lResource, Settings = lSettings };
string lAppBasePath = System.Web.HttpRuntime.AppDomainAppVirtualPath;
return lContext.GetResourceUrl(lSettings, lAppBasePath);
}
}
return null;
}
}
and then you can write:
<img src="#Html.ResourceUrl("ProfilePicture", "User1")" />
in an Orchard module view to get appropriate image link for User1.
I hope this helps.
ResourceUrl() is a custom HtmlHelper extension.
The code that you need to implement it is included in the answer you have linked.
You simply need to create a static class that contains the method code.
Asp.net article on how to create custom html helpers
PS: Make sure you import your namespace into the view with #using YourNamespace or add it to the System.Web.Mvc.HtmlHelper class.

Microsoft Unity 2, how to register the following?

Right now we have a dll file that contains all the database calls and i can't change it. However i need to call i from my Mvc 3 project. The process to call it is simple, i use the following:
ManageProvider.GetProxy<T>(ident);
T is an interface that i want to get the class back from (its like an IoC of its own) and ident is the user identification class. So by calling
var classReturned = ManageProvider.GetProxy<ICommunity>(new UserIden{ Email = "test#test.com" });
I would get a class back with all the community functions.
Now i want to implement Unity in my Mvc 3 project. The question is, can i somehow add these calls to the dll file through unity?
I want to resolve the call by using:
var classReturned = myContainer.Resolve<ICommunity>(new UserIden{ Email = "test#test.com" });
How can i register this in Unity (or is it even possible) ?
Update:
1) Is it better to call the methods with the email/user ident instead of defining a Dependency property? (ex below)
2) There is a bout 20 or so interfaces in the dll file right now. Should i add them all to the same reposatory? (ex below)
public class ProxyWrapper : IDllRepository
{
[Dependency]
public UserIdent UserIdent { get; set; }
public ICommunity GetCommunity()
{
return ManageProvider.GetProxy<ICommunity>(UserIdent);
}
public IDesktop GetDesktop()
{
return ManageProvider.GetProxy<IDesktop>(UserIdent);
}
}
public interface IDllRepository
{
ICommunity GetCommunity();
IDesktop GetDesktop();
}
Whats the best way and how would i call it from my code?
Does the [Dependency] attribute also fall into the Service Locator anti pattern?
Update 23.05.11
1) Yes, something like that. They contain all the logic that is provided to all the projects that includes the dll file.
Regarding the ManagerProvider. It accepts an interface and returns the class that is mapped to this interface. So for the community, the interface looks like this (removed a lot of calls to keep it short, there is also posts, comments, community create/update etc):
List<CommunityThread> GetThreads(int pStartRowIndex, int pMaximumRows, string pOrderBy, string pSearchExpression);
Guid? CreateThread(string pTitle, string pDescription, string pPostContent);
bool DeleteThread(Guid pThreadId);
List<CommunityThread> GetCommunityUserThreads(Guid pCommunityUserId);
2) What i can't update is how the ManageProvider.GetProxy works. The GetProxy is a class in the dll file that is hardcoded. Here is the part for the community. The class does the same for all the other interfaces as well, if typeof(interface) ... return class.
private static IManageProxy GetProxyForInterface<T>(UserIdent pIdent)
{
....
if (typeof(T).Equals(typeof(ICommunity)))
return new PCommunity();
....
}
3) Once registered using this new wrapper class, i can call it through the following code (MvcUnityContainer is a static class that only has a property called Container):
var c = MvcUnityContainer.Container.Resolve<IBackendRepository>(new PropertyOverride("UserIdent",
new UserIdent()));
Global.asax
IUnityContainer container = InitContainer();
MvcUnityContainer.Container = container;
DependencyResolver.SetResolver(new UnityMvcResolver(container));
The question is, do i need the static class MvcUnityContainer? Is it possible to configure the DependecyResolver to do that for me? Something like (problem is that it doesn't accept the override parameter):
var c = DependencyResolver.Current.GetService<IBackendRepository>(new PropertyOverride("UserIdent", new UserIdent()));
I think you need to hide the creation behind another abstraction, for instance:
public interface ICommunityRepository
{
ICommunity GetByEmailAddress(string address);
}
public class ManageProviderCommunityRepository
: ICommunityRepository
{
public ICommunity GetByEmailAddress(string address)
{
var id = new UserIden { Email = address };
return ManageProvider.GetProxy<ICommunity>(id);
}
}
This will hide both the ManageProvider and the UserIden behind this abstraction, and allows you to replace it later on with something more useful and makes testing easier.
Registration now is very easy:
RegisterType<ICommunityRepository, ManageProviderCommunityRepository>();
Instead of calling myContainer.Resolve (as you do in your example), inject the dependencies in your classes. This prevents you from using the Service Locator anti-pattern.
Perhaps you could do something like this, using the InjectionFactory:
myContainer.RegisterType<ICommunity>(
new InjectionFactory(c => ManageProvider.GetProxy<ICommunity>(new UserIden {Email = "test#test.com"})));
var classReturned = myContainer.Resolve<ICommunity>();
... Though you wouldn't be able to pass the UserIden as a parameter to the Resolve call, so I'm not sure if this is what you want.
To register all the public classes of the assembly you could perhaps iterate over Assembly.GetTypes() and register them in the same way?

Categories

Resources