I have app.config in m win application, and loggingConfiguration section (enterprise library 4.1).
I need do this programatically,
Get a list of all listener in loggingConfiguration
Modify property fileName=".\Trazas\Excepciones.log" of several RollingFlatFileTraceListener's
Modify several properties of AuthenticatingEmailTraceListener listener,
Any suggestions, I havent found any reference or samples
<listeners>
<add name="Excepciones RollingFile Listener" fileName=".\Trazas\Excepciones.log"
formatter="Text Single Formatter"
footer="</Excepcion>"
header="<Excepcion>"
rollFileExistsBehavior="Overwrite" rollInterval="None" rollSizeKB="1500" timeStampPattern="yyyy-MM-dd"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="AuthEmailTraceListener"
type="zzzz.Frk.Logging.AuthEmailTraceListener.AuthenticatingEmailTraceListener, zzzz.Frk.Logging.AuthEmailTraceListener"
listenerDataType="zzzz.Frk.Logging.AuthEmailTraceListener.AuthenticatingEmailTraceListenerData, zzzz.Frk.Logging.AuthEmailTraceListener"
formatter="Exception Formatter"
traceOutputOptions="None"
toAddress="xxxx#gmail.com"
fromAddress="xxxx#gmail.com"
subjectLineStarter=" Excepción detectada - "
subjectLineEnder="incidencias"
smtpServer="smtp.gmail.com"
smtpPort="587"
authenticate="true"
username="xxxxxxx#gmail.com"
password="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
enableSsl="true"
/>
I'm not sure if you can do it programmatically. You would have to map the configuration data to the actual implementation classes (and properties). Plus, if the config is currently being used, you would have to ensure that the programmatic changes would override the config.
In this example, I read the config in, change some settings, copy the config and write it back to the config file. This is made laborious because many properties are readonly so new objects need to be created. The writing of the config should work but I haven't tested actually calling Enterprise Library after doing this (and I really wouldn't recommend doing it for a production application).
// Open config file
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"MyApp.exe.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
// Get EL log settings
LoggingSettings log = config.GetSection("loggingConfiguration") as LoggingSettings;
List<TraceListenerData> newListeners = new List<TraceListenerData>();
foreach(TraceListenerData listener in log.TraceListeners)
{
// set new values for TraceListeners
if (listener is FormattedEventLogTraceListenerData)
{
FormattedEventLogTraceListenerData oldData = listener as FormattedEventLogTraceListenerData;
FormattedEventLogTraceListenerData data =
new FormattedEventLogTraceListenerData(oldData.Name, oldData.Source + "new", oldData.Log, oldData.MachineName, oldData.Formatter, oldData.TraceOutputOptions);
newListeners.Add(data);
}
else if (listener is RollingFlatFileTraceListenerData)
{
RollingFlatFileTraceListenerData oldData = listener as RollingFlatFileTraceListenerData;
RollingFlatFileTraceListenerData data =
new RollingFlatFileTraceListenerData(oldData.Name, oldData.FileName + ".new", oldData.Header, oldData.Footer, oldData.RollSizeKB, oldData.TimeStampPattern, oldData.RollFileExistsBehavior, oldData.RollInterval, oldData.TraceOutputOptions, oldData.Formatter, oldData.Filter);
newListeners.Add(data);
}
}
// Replace the listeners
foreach (TraceListenerData traceListener in newListeners)
{
log.TraceListeners.Remove(traceListener.Name);
log.TraceListeners.Add(traceListener);
}
// Copy the LogSettings since when config.Sections.Remove() is called the original log object becomes "empty".
LoggingSettings newLog = new LoggingSettings();
newLog.DefaultCategory = log.DefaultCategory;
foreach (var formatter in log.Formatters)
{
newLog.Formatters.Add(formatter);
}
foreach (var filter in log.LogFilters)
{
newLog.LogFilters.Add(filter);
}
foreach (var listener in log.TraceListeners)
{
newLog.TraceListeners.Add(listener);
}
foreach (var source in log.TraceSources)
{
newLog.TraceSources.Add(source);
}
newLog.LogWarningWhenNoCategoriesMatch = log.LogWarningWhenNoCategoriesMatch;
newLog.RevertImpersonation = log.RevertImpersonation;
newLog.SpecialTraceSources = log.SpecialTraceSources;
newLog.TracingEnabled = log.TracingEnabled;
// replace section
config.Sections.Remove("loggingConfiguration");
config.Sections.Add("loggingConfiguration", newLog);
// save and reload config
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("loggingConfiguration");
If this isn't 100% what you wanted hopefully it gives you some ideas.
Related
I’m using the following AS3 code to write and read data in two arrays to a local file, using Animate CC 2019 on Windows 10 and AIR 30.0 for Desktop/Flash (.swf) publishing settings. I use two input text boxes, input1 & input2, to add new data to the arrays.
When I test the FLA, the data file created has a .sol extension and is placed in a folder path:
C:\Users\username\AppData\Roaming\FLA filename\Local Store#SharedObjects\FLA filename.swf\
If I publish and install the program using an .air installer package, the exact same file, in the same folder path, is also accessed by the installed version of the program. Same location is used if I install on another computer running Windows 7, so the file location seems pretty consistent.
Question:
How can I force the code to save to a different location on the local hard drive on Windows? For example, in the documents folder or to create a new folder on the system drive and save the file there? Or, even better, prompt the user to choose the folder and file himself?
Please consider I’m looking for an answer using SharedObject, if possible, and not alternative methods like URLLoader, File, FileStream, FileMode. The reason is this way I can store multiple array contents in a file, without having to deal with the in-file data arrangement. So, I can read back the data for each array easily as shown below.
Thanks in advance
This is the code I use to access the local file:
var datavariable:SharedObject = SharedObject.getLocal("filiename");
var data1:Array = new Array ();
var data2:Array = new Array ();
btn_read.addEventListener(MouseEvent.CLICK, readfromfile);
btn_write.addEventListener(MouseEvent.CLICK, writetofile);
btn_new.addEventListener(MouseEvent.CLICK, newentry);
//To add new data from input text boxes to the arrays:
function newentry(e:Event):void
{
data1.push(input1.text);
data2.push(input2.text);
}
//To write to the local file:
function readfromfile(e:Event):void
{
data1 = datavariable.data.d1
data2 = datavariable.data.d2
}
//To read from the local file:
function writetofile(e:Event):void
{
datavariable.data.d1 = data1
datavariable.data.d2 = data2
datavariable.flush();
}
I don't know of a way of changing the shared object storage location. That mechanism is designed to be abstracted out from the developer.
Since you are using AIR, you can actually forget shared objects, and just write your own files anywhere your app has permission to do so. You can do this using the same format as shared object and don't have to worry about in file data arrangement (you save an object, you read back an object - just like Shared Object does), the only difference is you load/save the file where you choose.
Here is an example:
function writetofile(e:Event):void
{
//create an object that holds your data, this will act the same as the 'data' value of a shared object
var saveObject = {
d1: data1,
d2: data2
}
//using the File and FileStream classes to read/save files
var file:File = File.applicationStorageDirectory.resolvePath("saveData.data"); //or where and whatever you want to store and call the save file
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeObject(saveObject); //write the object to this file
fileStream.close(); //close the File Stream
}
function readfromfile(e:Event):void
{
var file:File = File.applicationStorageDirectory.resolvePath("saveData.data");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var savedObject = fileStream.readObject();
fileStream.close();
data1 = savedObject.d1;
data2 = savedObject.d2;
}
If you want to save complex objects (objects that aren't primitives), you need to register the class first. This goes for shared objects as well. See this answer for example of that.
I have 2 .NET Core 2.0 console applications. The first application calls the second one via System.Diagnostics.Process.Start(). Somehow the second app is inheriting the development configuration information located in the appsettings.development.json of the first app.
I execute the first app by running either dotnet run in the root of the project or dotnet firstapp.dll in the folder where the DLL exists. This is started from in Powershell.
Both apps are separate directories. I'm not sure how this is happening.
UPDATE WITH CODE
The apps reside in
C:\Projects\ParentConsoleApp
C:\Projects\ChildConsoleApp
This is how I call the app from parent application:
System.Diagnostics.Process.Start("dotnet", "C:\\projects\\ChildConsoleApp\\bin\\Debug\\netcoreapp2.0\\publish\\ChildConsoleApp.dll" + $" -dt {DateTime.Now.Date.ToString("yyyy-MM-dd")}");
This is how I load the configuration from JSON (this is same in both apps):
class Program
{
private static ILogger<Program> _logger;
public static IConfigurationRoot _configuration;
public static IServiceProvider Container { get; private set; }
static void Main(string[] args)
{
RegisterServices();
_logger = Container.GetRequiredService<ILogger<Program>>();
_logger.LogInformation("Starting GICMON Count Scheduler Service");
Configure();
// At this point DBContext has value from parent! :(
var repo = Container.GetService<ICountRepository>();
var results = repo.Count(_configuration.GetConnectionString("DBContext"), args[0]);
}
private static void Configure()
{
string envvar = "DOTNET_ENVIRONMENT";
string env = Environment.GetEnvironmentVariable(envvar);
if (String.IsNullOrWhiteSpace(env))
throw new ArgumentNullException("DOTNET_ENVIRONMENT", "Environment variable not found.");
_logger.LogInformation($"DOTNET_ENVIRONMENT environment variable value is: {env}.");
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
if (!String.IsNullOrWhiteSpace(env)) // environment == "Development"
{
builder.AddJsonFile($"appsettings.{env}.json", optional: true);
}
_configuration = builder.Build();
}
private static void RegisterServices()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("nlog.config");
Container = serviceProvider;
}
}
The problem is caused by the fact that you set base path for configuration builder to the current working directory:
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
When you create a child process, it inherits current directory from the parent process (unless you set current directory explicitly).
So the child process basically uses JSON configs from the directory of parent process.
There are several possible fixes:
Do not set base path to the current directory.
When the application is launched, you don't know for sure that current directory will match directory where application binaries are placed.
If you have an exe file in c:\test\SomeApp.exe and launch it from the command line while the current directory is c:\, then current directory of your application will be c:\. In this case, if you set base path for configuration builder to current directory, it will not be able to load configuration files.
By default, configuration builder loads config files from AppContext.BaseDirectory which is the directory where application binaries are placed. It should be desired behavior in most cases.
So just remove SetBasePath() call:
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
If for some reason you want to set the base path of configuration builder to the current directory, then you should set correct current directory for the launched child process:
var childDllPath = "C:\\projects\\ChildConsoleApp\\bin\\Debug\\netcoreapp2.0\\publish\\ChildConsoleApp.dll";
var startInfo = new ProcessStartInfo("dotnet", childDllPath + $" -dt {DateTime.Now.Date.ToString("yyyy-MM-dd")}")
{
WorkingDirectory = Path.GetDirectoryName(childDllPath),
};
Process.Start(startInfo);
As #CodeFuller explained, the reason is that both apps read the same appsettings.{env}.json file. For simplicity, you may just rename the config file (and the corresponding name in .AddJsonFile) for the second app to prevent any possible overrides.
See, when you register JSON file as a configuration source by .AddJsonFile, configuration API allows you to use whatever file name you need and
you are not forced to use the same $"appsettings.{env}.json" pattern for both applications.
How can I save the modified data to the same xml file after loading from that external xml file in ActionScript3.
Is there exist any function or method or any way to save the modified data again in the same file from which it was loaded.
import flash.net.URLRequest;
var myXML:XML = new XML();
var XML_URL:String = "sample.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener("complete", xmlLoaded);
function xmlLoaded(event:Event):void
{
myXML = XML(myLoader.data);
trace("Data loaded.");
trace(myXML); //showing output of just loaded xml file.
//process of adding new child node or property.
var newnode:XML = new XML();
newnode =
<student >
<sname srno="2">mm</sname>
<father tax="no">
<fname>Ratan</fname>
<focc>business man</focc>
<mobno>9928946899</mobno>
</father>
</student>;
myXML = myXML.appendChild(newnode);
trace(myXML); //showing o/p after being the child-node appended.
}
where the sample.xml file located in the same working path, contains only the following data.-
<data>
<student srno="1" class="5" rollno="1">
<sname>Rohan Jain</sname>
<father tax="yes">
<fname>Ronak Jain</fname>
<focc>teacher</focc>
<mobno>9928946899</mobno>
</father>
</student>
</data>
If you're building a browser based application; nothing you can do on the client will save the file to a specific name and location. You'll have to send your updated doc to the server for saving. It is easy to write a service to do this in most server side languages I have dealt with.
If you want to save the file to the client machine; you can do so using FileReference.save(). However, this requires user input and there is no way to guarantee what the user will name the file or where they'll put it.
So I've tried to build a small utility to view the contents of a JSON file in an easy-to-understand manner (for non-tech people).
I have Googled far and wide, high and low, but every example that shows how to consume a JSON file in Flash Builder uses the HTTP service, pointing to a file on the web.
Here I am, sitting in front of my MacBook, wondering why I can't make this work. In the documentation I've found (sort of relating to this issue), they always show Windows examples, and they seem to work fine:
C://me/projects/json/my_json.json
Perhaps I'm completely missing the obvious, but is this possible on a Mac as well?
I've tried
file:///Users/me/projects/json/my_json.json
That doesn't work. I've tried some "resolve to path" syntax, but the HTTP service does not seem to allow for anything but file paths in quotes.
Would anyone be able to pint me in the right direction?
Use the File API. It's really easy, here's a quick code sample:
// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;
// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);
// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");
// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);
// Select event handler
private function onSelect(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
// Cast to File
var selectedFile:File = e.currentTarget as File;
readFile(selectedFile);
}
private function onCancel(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
}
private function readFile(file:File):void
{
// Read file
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.READ);
var contents:String = fs.readUTFBytes(selectedFile.size);
fs.close()
// Parse your JSON for display or whatever you need it for
parseJSON(contents);
}
You hinted at this in your post about examples being for Windows and you being on a Mac but I'll state it explicitly here: you should always use the File API because it is cross platform. This code will work equally well on Windows and Mac.
I'm trying to programmatically encrypt configuration sections of App.config and Web.config files. In the following code, I set the path configuration file I want to edit in the configFilePath variable and then expect it to encrypt the connectionStrings section.
var config = ConfigurationManager.OpenExeConfiguration(configFilePath);
var section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
This runs fine without any errors but makes no changes to the given file. It's like it's not really accessing the file I want to access.
Any ideas?
Right, answering my own question...
The code was indeed not opening the right config file. To do that we need to use ConfigurationManager.OpenMappedExeConfiguration() instead of ConfigurationManager.OpenExeConfiguration().
So, the first line of the code above changes to:
var map = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);