I have created a dotnetnuke module, it has multiple controls wrapped in a single moduleNow i want to access the settings variable across module, say for example i have a setting for dateformat, now the dateformat user selects should be used throughout moduleIt works fine with the view control which comes by default with Dotnetnuke (ChrisToc Template)But when i add new control it does not works, i also added proper inherits, it never throws compile error (in case it does not gets proper namespace)
Below is the code i am using:
public partial class ViewEntry : WireModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("SETTINGS: " + Settings["WireDateFormat"]);
}
}
Any help will be appreciated
I don't ever use the Setting dictionary in my module views. First, it leaves you open to code errors by having to hardcode the key string when accessing the setting. Second, it makes it hard to share with you business logic or other views. My preferred pattern for settings is to create an interface and class for my settings that provides class attribute for my settings and performs the plumbing calls to DNN core to get and set those settings.
Follow this link to a Codeplex project where you will find a class SettingsRepository and ISettingsRepository interface.
Once you modified the public properties for your settings (ie: WireDateFormat) into the class and interface, you can then use it in your module settings implementation.
Get the setting:
ISettingsRepository settingsCtrl = new SettingsRepository(this.ModuleId, this.TabModuleId);
txtSetting1.Text = settingsCtrl.Setting1;
Write the setting
ISettingsRepository settingsCtrl = new SettingsRepository(this.ModuleId, this.TabModuleId);
settingsCtrl.Setting1 = txtSetting1.Text;
Once the settings is stored (in this case using the TabModuleId, but you can use the ModuleID constructor overload if you want to share the setting across modules on a page), you can use the same "get" code in any of your module views or business logic.
Related
I'm new to .net core development after years of working in .net framework on mostly webform applications.
I'm trying to localize a new project and looking at options determined for this particular use that a shared resource would be the most maintainable solution long term and followed this example: https://damienbod.com/2017/11/01/shared-localization-in-asp-net-core-mvc/
This appears to work great for adding the localized data in the view but I am struggling to be able to do so in the controller such as returning a localized error when something is caught server side and a custom message would be returned.
In my controller's I added
private readonly LocService _SharedLocalizer;
Within a view's method in the controller if I try and add
ViewBag.localizedmessage = _SharedLocalizer.GetLocalizedHtmlString("message")
I get a null error on accessing the page on this line.
If I create a new instance within the view's method I am not sure what to provide as the argument value for the IStringLocalizerFactory.
_SharedLocalizer = new LocService();
What is the piece I am missing or how do I go about properly accessing the shared resource in a controller?
Try this
public class YourController : Controller
{
private readonly LocService _SharedLocalizer;
public YourController(LocService localizer)
{
_SharedLocalizer = localizer;
}
}
I try to create a Universal Windows App which has a main window containing different views.
ContentFrame.Navigate(typeof(SimplePage));
where ContentFrame is a XAML Frame and SimplePage is a view.
The project has two localisations. Therefore I created a folder Strings in the solution containing two folders, en and de, containing each a Resources.resw file.
I want to use a string from the resw-file inside the SimplePage-view. Therefore I tried:
tbSimpleInput1.Text = ResourceManager.Current.MainResourceMap.GetValue("Resources/dataToolDiameter", ResourceContext.GetForCurrentView()).ValueAsString;
I also tried using ResourceContext.GetForViewIndependentUse() instead of ResourceContext.GetForCurrentView() but I always get a NullReferenceException when trying to debug.
What is the correct way to access the resources in different views?
Here a screenshot of the solution in Visual Studio:
If you're having a single-project solution, I'd recommend you either to create a Shell - as the Microsoft example recommends, or to use the App.xaml.cs class for localization purposes.
First, in the constructor of either class, get the current ResourceLoader:
// E.g use the static constructor of your App class
static App()
{
_resourceLoader = new ResourceLoader();
}
Now getting a resource (e.g. a text) is very easy:
public static string GetLocalizedString(string key)
{
return _resourceLoader.GetString(key);
}
Now you can load a string form the default resource dictionary:
tbSimpleInput1.Text = App.GetLocalizedString("dataToolDiameter");
Please note: this only works as long as you use the default pattern for localization in your project. If you use different resource files, you'd have use an overload of the ResourceLoader constructor.
I am developing an MVC app to serve multiple domains - each is a branch of a larger company.
A LocalBranch class stores details such as phone, address, email, location coordinates etc.
I want to create a single instance of this class per http request and have it available throughout the application - from within controllers, views, some helper classes and other code.
Is there a recommended way of doing this?
Right now I have it as a property on a BaseController and use ViewBagto pass it to views. But I would prefer it strongly typed in Views if possible.
I don't want to put it in an application variable, because we need to serve different values to different domains.
I would rather avoid a session variable if possible because we might scale up to use multiple servers in the future, and I've heard this doesn't play well with sessions.
Please feel free to update tags / title if you think there is a clearer way of expressing what I'm after. Thank you.
The best way to maintain your state in a web application per request is simply use the HttpContext class.
You need to store your state(LocalBranch) as an Item in the HttpContext:
HttpContext.Current.Items.Add("LocalBranch", GetLocalBranch());
You can fetch the Item all across your application like this:
LocalBranch branch = HttpContext.Current.Items["LocalBranch"] as LocalBranch;
The Items property is simply a key value Dictionary. The value is an object. You will have to check for nulls and this is really similar to the Session object you know. The main difference is the scope. The HttpContext is a dot net object that has a lifetime of an http request.
Now using the HttpContext the way I've shown you is the simplest way to do it.
You can go two steps forward and use a framework called Unity and add a lifetime to your objects.
Unity does much more and the lifetime management is just one gem.
You can create a custom HttpContext lifetime that generates objects per request. Something like this.
And them all you need to do is:
1.Register you LocalBranch class with the HttpContext lifetime.
2.Add a static Current property which will use the Unity container and resolve the correct instance of LocalBranch.
3.Use it something like this: LocalBranch.Current
BTW, you can use Unity's dependency injection for injecting objects into controllers and other modules. That's a better practice then just using the static Current property.
You kind of have two questions here. The first is "How do I create a single instance of this class per HttpRequest?" The second is "How do I make this available to strongly typed views?"
The first has pretty much been answered by #amir-popovich to use dependency injection. However, FWIW I would probably use Ninject instead of Unity (just preference, really) and I would probably implement it differently. I would not use HttpContext, and simply build a service (which is instanciated using Ninject's OnePerHttpRequest Module, passing the domain as an argument to get the proper values).
Then, in order to add these LocalBranch values to your strongly typed View Model, you can first create a base view model which holds this type:
public class BaseViewModel
{
public LocalBranch Branch {get;set;}
}
Then, make all of your current view models inherit this base type
public MyViewModel : BaseViewModel
{
public string SomeValue {get;set;}
}
Then in your controller, it is easy enough to add these values from the service you created from the first step
public ActionResult SomeAction()
{
var vm = new MyViewModel();
vm.Branch = LocalBranchService.GetLocalBranchValues(); //Local Branch Service has been injected with Ninject
//do other stuff
return View(vm);
}
However, that gets pretty tedious to add that to each controller action, so you can instead create a Result Filter to add it for you:
public class LocalBranchResultFilter : FilterAttribute, IResultFilter
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
//This method gets invoked before the ActionResult is executed.
filterContext.Controller.ViewData.Model.Branch = LocalBranchService.GetLocalBranchValues(); //Local Branch Service has been injected with Ninject
}
}
Now, you can just decorate your Controller and/or Actions with the filter (you could even set it in the Global Filters if you want).
You can embed the child actions into your layout or a view. You can even cache its output so you don't keep re-querying the database.
controller
[ChildActionOnly]
[OutputCache(Duration=500, VaryByParam="*")]
public ActionResult Info()
{
var localBranch = db.GetLocalBranch();
return PartialView("_Info", localBranch);
}
_Info view
This bit will get inserted into your other views
#model LocalBranch
<span>#Model.address</span>
<span>#Model.phone</span>
Use in _Layout or other view
<p>lorem ipsum...</p>
#Html.Action("Info")
I have an ASP.net MVC site, which I want to use a couple of resource files to set some strings.
I have a class library containing my viewmodels, and I have added a resource file (ValidationMessages) there, with a single string (called Test), and then have a property like so in my view model:
public string TestResource
{
get
{
return ValidationMessages.Test;
}
}
And that works fine, when output on my view like so:
<div>#Model.TestResource</div>
If I add a ValidationMessages.en-au.resx (my default would be en-gb) file to my class library and create a different version of the test string, and then have the following in my global.asax:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-au");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-au");
}
And this also works fine.
What I want to do is add a custom culture 'en-gb-ly' - I have registered this culture on my machine ok (using code from here). When I set the current culture to "en-gb-ly" in my global.asax and include a ValidationMessages.en-gb-ly.resx in my class library, the output has reverted back to the 'base' version of the Test string, not the one in my en-gb-ly resource.
Anybody any idea why this might be happening?
A first thing to check is that the en-ly satellite assembly gets deployed as expected. Unfortunately if your custom culture is not installed on your build machine, then it won't even get built!
I am writing an Orchard CMS module within a multi-tenant application.
I would like to be able to access the settings declared when the tenant was set up, namely the DB table prefix which i'd like to use as a unique identifier for the current tenant in other areas of my system.
Is there an API/Helper I can query for these settings?
Cheers.
Get the site item from the work context. It has all the settings as parts. For the table prefix specifically it's a little different: you need to inject ShellSettings. But I would question the need to do that first...
I have found this, if it helps:
private readonly ISiteService _siteService;
public MyController(ISiteService siteService)
{
_siteService = siteService;
}
public void MethodExample(){
var myVar = _siteService.GetSiteSettings().BaseUrl;
}