I found the LocalizationResourceManager class. It enables users to respond to culture changes at runtime. But I found that it need to initialize with just one ResourceManager LocalizationResourceManager.Current.Init(AppResources.ResourceManager);. It doesn't make sense.
In my app, there're many pages and I also create many resx files for the specific page. For example,
-- Resx
----Main
--------MainResource.resx
--------MainResource.en-US.resx
--------MainResource.es.resx
--------MainResource.ja.resx
----Setting
--------SettingResource.resx
--------SettingResource.en-US.resx
--------SettingResource.ja.resx
......
In this case, How to initialize LocalizationResourceManager?
Here AppResources represents your resource file , modify your code as below
LocalizationResourceManager.Current.PropertyChanged += (sender, e) => MainResource.Culture = LocalizationResourceManager.Current.CurrentCulture;
LocalizationResourceManager.Current.Init(MainResource.ResourceManager);
LocalizationResourceManager.Current.CurrentCulture = new CultureInfo("en");
Check official sample :
https://github.com/xamarin/XamarinCommunityToolkit/tree/main/samples .
Related
I have an ASP.NET project that sends its logs to NLog.
However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.
I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.
How can this be accomplished?
This is the code that creates the logger:
// create the module name
var ProcessName = Process.GetCurrentProcess().ProcessName;
_ModuleName = ProcessName + " (\"" + Oracle.GuessMyName() + "\")";
// create the logger configuration
var Configuration = new LoggingConfiguration();
// create the file target
var FileTarget = new FileTarget ("file")
{
FileName = #"x:\Logs\${processname}.log",
ArchiveFileName = #"x:\Logs\${processname}.{#}.log",
Layout = #"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
ArchiveEvery = FileArchivePeriod.Day,
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 7,
ConcurrentWrites = true
};
Configuration.AddTarget(FileTarget);
// create the viewer target
var ViewerTarget = new NLogViewerTarget ("viewer")
{
Layout = #"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
IncludeSourceInfo = true,
IncludeCallSite = true,
Address = #"udp://127.0.0.1:9999"
};
Configuration.AddTarget(ViewerTarget);
// set the rules
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));
// set the configuration
LogManager.Configuration = Configuration;
// create a new logger
_Logger = LogManager.GetLogger(_ModuleName);
and this is also how ASP.net gets attached to nlog:
LoggerFactory.AddNLog();
Application.AddNLogWeb();
Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)
so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.
the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.
Look at the code of NLog.Extensions.Logging, where it injects its own custom log-provider.
You can do the same and just wrap your global-logger object:
https://github.com/NLog/NLog.Extensions.Logging/blob/e48d6cc54d9abd70d976066265c7992117cbac5a/src/NLog.Extensions.Logging/NLogLoggerProvider.cs
https://github.com/NLog/NLog.Extensions.Logging/blob/1474ffe5b26d2ac95534ed01ef259133133bfb67/src/NLog.Extensions.Logging/NLogLoggerFactory.cs
https://github.com/NLog/NLog.Extensions.Logging/blob/2c05a4fbdda0fe026e60814d535e164e18786aef/src/NLog.Extensions.Logging/ConfigureExtensions.cs
public static ILoggerFactory AddNLog(this ILoggerFactory factory, NLogProviderOptions options)
{
ConfigureHiddenAssemblies();
using (var provider = new NLogLoggerProvider(options))
{
factory.AddProvider(provider);
}
return factory;
}
You could also create a custom-target, and redirect all non-global-logger messages to this target using NLog rules:
https://github.com/nlog/NLog/wiki/Configuration-file#rules
The custom target can then just forward the log-event to the global-logger:
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
You should be careful with cyclic logging. Maybe have a filter in the custom-target to ignore messages from the global-logger.
But I think this is an ugly solution, and I fail to understand the restriction of only one logger-object. Especially when the reason is because it should be named after the application. Why not not a global variable for the name instead of abusing the logger-name?
Alternative you can create a custom target wrapper, that fixes the Logger on LogEventInfo's, so when forwarded to the wrapped target (UDP- / File-target), then it looks like they are all come from the same logger.
Similar to what this guy is trying to do:
https://github.com/NLog/NLog/issues/2352
Again really ugly solution, and should only be used when not able to figure out, how to avoid using the logger-name in the configuration of the wanted Nlog-targets (Ex. configure file-target-filename using something else).
I want my extension to do something everytime an item gets added to the project. This works fine for normale Projects or, with some magic (see here), for the Project Type "Website". But i cant get it to work with .xproj.
Here my current code to access the ItemAdded event (shortened)
var events = _dte.Events as Events2;
_projectItemEvents = events.ProjectItemsEvents;
_projectItemEvents.ItemAdded += ItemAdded;
_websiteItemEvents = events.GetObject ("WebSiteItemsEvents") as ProjectItemsEvents;
_websiteItemEvents.ItemAdded += ItemAdded;
_csharpItemEvents = events.GetObject ("CSharpProjectItemsEvents") as ProjectItemsEvents;
_csharpItemEvents.ItemAdded += ItemAdded;
Does anyone know how to access the ItemAdded event in case of an .xproj project type?
Edit: Edited code; The variables are all class fields and are not garbage collected, as in case of the other project types, the events are fired properly, just not in case of an .xproj.
I have written the following inside my RegisterRoutes() in Global.asax in webforms application.
I have an xml file called CacheInfo.xml that stores the details of cached pages.The default page has an entry in the xml called EnDefaultPage, which contains two child nodes.
The child node LastUpdationTimeStamp stores, last updation timestamp (unix timestamp in seconds ) of the cache for Default page.
The child node ExpiryTimestamp stores the timestamp at which the cache will be expired.So if the expiry timestamp is greater than lastupdation timestamp, the file from Cache will be loaded (Default.html).Currently the script is working, but it is not routing to the Default.html although the conditional block that defines the route is being executed.I couldn't find the exact reason behind the issue.Can anybody suggest me a fix.All the other routes are working perfectly.
My code is attached below.
ublic void RegisterRoutes(RouteCollection routes)
{
string relPath = "~/CacheInfo.xml";
string absPath = Server.MapPath(relPath);
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.Load(
absPath
);//loading XML in xml doc
string nodeName="", nodeVal="",upStamp="0",expiry="0";
int iUpStamp,iExpiry;
upStamp = xdoc.GetElementsByTagName("EnDefaultPage")[0].SelectSingleNode("LastUpdationTimeStamp").InnerText;
expiry = xdoc.GetElementsByTagName("EnDefaultPage")[0].SelectSingleNode("ExpiryTimeStamp").InnerText;
iUpStamp = Convert.ToInt32(upStamp);
iExpiry = Convert.ToInt32(expiry);
if(!String.IsNullOrEmpty(upStamp)) {
if (iExpiry > iUpStamp)
{
System.Diagnostics.Debug.WriteLine("stamp is " + upStamp + " Expiry is " + expiry);
// routes.MapPageRoute("EnHome1", "", "~/en/DefaultCache.aspx");
routes.MapPageRoute("EHome", "en/", "~/en/Default.html");
//this routing is not working
}
else
{
}
}
routes.MapPageRoute("GArticle", "Gallery/{slug}", "~/Gallery/Article.aspx");
routes.MapPageRoute("GCategory", "Gallery/Categories/{slug}", "~/Gallery/Categories.aspx");
routes.MapPageRoute("GSlideShow", "Gallery/{slug}/{id}", "~/Gallery/SlideShow.aspx");
routes.MapPageRoute("Article", "en/{slug}", "~/english/Article.aspx");
routes.MapPageRoute("Category", "en/Categories/{slug}", "~/english/Categories.aspx");
routes.MapPageRoute("enFeed", "en/category/english/{slug}/feed", "~/en/feed.aspx");
routes.MapPageRoute("teFeed", "te/category/telugu/{slug}/feed", "~/te/feed.aspx");
routes.MapPageRoute("Tags", "en/Tags/{tag}", "~/english/Tags.aspx");
routes.MapPageRoute("tArticleHtml", "te/{slug}.html", "~/telugu/Article.aspx");
routes.MapPageRoute("tArticle", "te/{slug}", "~/telugu/Article.aspx");
routes.MapPageRoute("tCategoryHtml", "te/Categories/{slug}.html", "~/telugu/Categories.aspx");
routes.MapPageRoute("tCategory", "te/Categories/{slug}", "~/telugu/Categories.aspx");
routes.MapPageRoute("tTagsHtml", "te/Tags/{tag}.html", "~/telugu/Tags.aspx");
routes.MapPageRoute("tTags", "te/Tags/{tag}", "~/telugu/Tags.aspx");
}
}
If I read your intent correctly, you want the user to be directed to default any time their access is expired. If so, you can't get there from here.
RegisterRoutes is used to register routes as the application starts up.The last 3 words are the clue as to why certain logic will not work later in the application.
Now to your RegisterRoutes. Here is the logic.
Get expiration date
Get timestamp
If the expiration date is greater than last updated, when the application starts, route the user to default
If you truly mean "at startup determine whether to route every page that can be expired to default, every time" then you have the correct logic and it is working as expected. The fact you asked the question says that is not your intent. You want a decision made on a page access by page access basis. If I am correct, you can't do it in RegisterRoutes. You will have to implement the "caching logic" elsewhere.
My suggestion, rather than building this by hand, is look into software that handles caching.
I am trying to override the javascript controller node-header.js of components\node-details with the extension module of alfresco share
This is my node-header.get.js
<import resource="classpath:/alfresco/templates/org/alfresco/import/alfresco-util.js">
for (var i=0; i<model.widgets.length; i++)
{
if (model.widgets[i].id == "NodeHeader")
{
if(model.widgets[i].options.nodeRef!=null)
{
var jsNode = new Alfresco.util.Node(model.widgets[i].options.nodeRef);
if(jsNode.hasAspect("custom:intranetFile")){
model.widgets[i].options.showFavourite = false;
model.widgets[i].options.showLikes = false;
}
}
}
}
I am getting this error
Error Message: 05270002 Failed to execute script
'classpath*:webscripts/custom/nodeheader/hidelikesync/node-header.get.js':
05270001 ReferenceError: "Alfresco" is not defined.
(jar:file:/C:/Alfresco/Alfresco42/tomcat/webapps/share/WEB-INF/lib/customshare.jar!/webscripts/custom/nodeheader/hidelikesync/node-header.get.js#1555)
Error lies in this line
var jsNode = new Alfresco.util.Node(model.widgets[i].options.nodeRef);
as Alfresco object is not available how can I get it?
Based on my answer yesterday on the share-extras-devel list:
Your issue is that you are mixing up your web script JS with client-side JavaScript. Alfresco.util.Node is a client-side helper class and is therefore available to client-side JS running in the web browser, but not to your web script code which runs on the server.
If you look at the source of alfresco-util.js, which you are including, you will see that there is a helper class there but it is called AlfrescoUtil.
To get some information on this given node I would suggest that you want to use the static method AlfrescoUtil.getNodeDetails() from that class, e.g.
var jsNode = AlfrescoUtil.getNodeDetails(model.widgets[i].options.nodeRef);
The structure of the jsNode object will be as per the JSON returned by the doclist-v2 webscripts, so you should be able to check for the presence of your custom aspect in the aspects array property.
If you check the source of alfresco-util.js you will see that additional parameters are also supported by getNodeDetails(). It seems to me you can also pass in an optional site name, plus some options if you wish.
I want to populate
Response.ContentType = "text/plain";
From somewhere in the server/web/dictionary ALL possible MIME types according to file extension:
public string GetMimeType(string extension)
{
//This is what I am looking for.
}
Also, I have to rename the file (at least if going to be downloaded, so I have to know in advance if it's going to be opened or not.
You can store the mimetype when the file is uploaded ( FileUpload.PostedFile.ContentType ) and send that when the file is requested.
Umm... why? You're not going to be returning content of every possible type, are you?
Here's a list of common types: http://www.webmaster-toolkit.com/mime-types.shtml. There is no list that would include "ALL" types simply because any application vendor can create a custom one and associate it with a custom extension.
It's going to depend on your platform. Here's one for C# and IIS: http://blog.crowe.co.nz/archive/2006/06/02/647.aspx
In Powershell it's a one-liner:
([adsi]"IIS://localhost/MimeMap").MimeMap
The code in the link posted by Richard:
// Maintain a sorted list to contain the MIME Types
SortedList sl = new SortedList();
Console.WriteLine("IIS Mime Map - c#");
Console.WriteLine();
// Serve to connect to...
string ServerName = "LocalHost";
// Define the path to the metabase
string MetabasePath = "IIS://" + ServerName + "/MimeMap";
// Note: This could also be something like
// string MetabasePath = "IIS://" + ServerName + "/w3svc/1/root";
try
{
// Talk to the IIS Metabase to read the MimeMap Metabase key
DirectoryEntry MimeMap = new DirectoryEntry(MetabasePath);
// Get the Mime Types as a collection
PropertyValueCollection pvc = MimeMap.Properties["MimeMap"];
// Add each Mime Type so we can display it sorted later
foreach (object Value in pvc)
{
// Convert to an IISOle.MimeMap - Requires a connection to IISOle
// IISOle can be added to the references section in VS.NET by selecting
// Add Reference, selecting the COM Tab, and then finding the
// Active DS Namespace provider
IISOle.MimeMap mimetypeObj = (IISOle.MimeMap)Value;
// Add the mime extension and type to our sorted list.
sl.Add(mimetypeObj.Extension, mimetypeObj.MimeType);
}
// Render the sorted MIME entries
if (sl.Count == 0)
Console.WriteLine("No MimeMap entries are defined at {0}!", MetabasePath);
else
foreach (string Key in sl.Keys)
Console.WriteLine("{0} : {1}", Key.PadRight(20), sl[Key]);
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
Console.WriteLine(" Property MimeMap does not exist at {0}", MetabasePath);
else
Console.WriteLine("An exception has occurred: \n{0}", ex.Message);
}
// Convert to an IISOle.MimeMap - Requires a connection to IISOle
// IISOle can be added to the references section in VS.NET by selecting
// Add Reference, selecting the COM Tab, and then finding the
// Active DS Namespace provider
According to my googling: (lost the links, sorry)
The "Active DS IIS Namespace Provider" is part of the IIS installation.
After you install IIS you will see that in the list of options.
If you don't see it should be located at C:\windows\system32\inetsrv\adsiss.dll.
To install IIS:
click Start, Settings, Control Panel, Add or Remove Programs, Add or Remove Windows Components, select Internet Informatoin Services (IIS).
Most of the code I've seen uses some combination of these:
using System.IO;
using System.DirectoryServices; // Right-click on References, and add it from .NET
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using IISOle;
using System.Collections.Specialized;
The Active DS Namespace might be under the COM tab when adding the reference.
I've written a small class based on the webmaster-toolkit.com list. This is to avoid using COM and the IIS route or any IIS references.
It uses an XML serialized list which contains about 400 mimetypes, so is usually more than enough unless you have really obscure mimetypes. In that case you can just add to the XML file.
The full solution can be found here. Here's a sample:
class Program
{
static void Main(string[] args)
{
var list = MimeType.Load();
MimeType mimetype = list.FirstOrDefault(m => m.Extension == "jpg");
}
}