I want to archive log files periodically(for every hour) from "Logs" folder to "Archive" folder and then delete those archived files from "logs" folder immediately. Can we achieve this using NLog?
Currently, I am using the below c# code for archiving, but I am not seeing the desired output. We are using Nlog version 4.7.11.
target.FileName = #"C:\Logs\Log-${date:format=yyyy-MM-dd-hh}.log";
target.ArchiveFileName = #"C:\Archives\Log-${date:format=yyyy-MM-dd-hh}.log";
target.ArchiveEvery = FileArchivePeriod.Hour;
target.ArchiveOldFileOnStartup = true;
target.DeleteOldFileOnStartup = true;
target.MaxArchiveDays = 10;
target.ArchiveNumbering = ArchiveNumberingMode.Date;
target.MaxArchiveFiles = 50;
target.ArchiveDateFormat = "yyyy-mmm-dd hh-mm";
target.EnableArchiveFileCompression = true;
NLog supports 2 file-archive-modes:
Static FileName Archive-mode, where ArchiveEvery controls when to roll.
Dynamic FileName Archive-mode, where FileName contains ${date} or ${shortdate} (Rolls automatically)
NLog does not support mixing these 2 file-archive-modes. If you want files to be moved into the Archive-folder, then you must use static FileName:
target.FileName = #"C:\Logs\App.log";
target.ArchiveFileName = #"C:\Archives\App-{#}.log.zip";
target.ArchiveEvery = FileArchivePeriod.Hour;
target.ArchiveOldFileOnStartup = true;
target.DeleteOldFileOnStartup = true;
target.MaxArchiveDays = 10;
target.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
target.MaxArchiveFiles = 50;
target.ArchiveDateFormat = "yyyy-MM-dd-hh";
target.EnableArchiveFileCompression = true;
Alternative you can use dynamic-archive-mode and then use scheduled-task/cron-job to compress/move log-files to the wanted location:
target.FileName = #"C:\Logs\Log-${date:format=yyyy-MM-dd-hh}.log";
target.ArchiveOldFileOnStartup = true;
target.MaxArchiveDays = 10;
target.MaxArchiveFiles = 50;
See also Do not mix dynamic with static-archive-mode
You can extend your NLog method to run some method after logging. Please refer to the following: https://github.com/NLog/NLog/wiki/MethodCall-target.
MethodCall target: Calls the specified static method on each log message and passes contextual parameters to it.
You can create some code that uses System.IO to move and archive your code based on your needs.
Related
I need to get the full diff between master and develop for a specific directory, so I can parse it and create an easy to read changelog.
I want to replicate "git diff --unified=0 master directory/ >file.diff" with libgit2sharp. I do manage to get a list of all modified/added/deleted files, but I do not know how to get the content of the diff for each file.
using (var repo = new Repository("C:\\dev\\myProject"))
{
var changes = repo.Diff.Compare<TreeChanges>(repo.Branches["master"].TrackedBranch.Tip.Tree,
DiffTargets.WorkingDirectory);
foreach (var changed in changes.Modified)
{
if (changed.Path.Contains("directory"))
{
Console.WriteLine("modified:" + changed.Path);
}
}
}
I'd like to have something similar to the actual git command, so I can parse it. Another solution would be to use "Process.Start", but maybe libgit2sharp is a much cleaner approach. I do not have .Net Core 2.0 for PowerShell.
By default patches are unified format
git diff master..develop <directory> > output.diff
I solved it using Process.Start. I'd still be interested in the libgit2sharp solution. Hint: 1252 encoding does not work in standard .Net Core.
const string command = "git";
const string directory = "C:\\dev\\myProject";
const string arguments = "diff --unified=0 master directory/";
var startInfo = new ProcessStartInfo
{
WorkingDirectory = directory,
FileName = command,
Arguments = arguments,
StandardOutputEncoding = Encoding.GetEncoding(1252),
UseShellExecute = false,
RedirectStandardOutput = true
};
var cmd = Process.Start(startInfo);
var sr = cmd?.StandardOutput;
var output = sr?.ReadToEnd();
cmd?.WaitForExit();
Hello this is my code and i don't know how to run and get output of this code. Please suggest me the answer for this.And I want to create command for autocad using this code so suggest me according to this requirement.
using System;
using System.IO;
using System.Globalization;
using UDC;
using AutoCAD = Autodesk.AutoCAD.Interop;
namespace AutoCADtoPDF
{
class Program
{
static void PrintAutoCADtoPDF(string AutoCADFilePath)
{
//Create a UDC object and get its interfaces
IUDC objUDC = new APIWrapper();
IUDCPrinter Printer = objUDC.get_Printers("Universal Document Converter");
IProfile Profile = Printer.Profile;
//Use Universal Document Converter API to change settings of converterd drawing
//Load profile located in folder "%APPDATA%\UDC Profiles".
//Value of %APPDATA% variable should be received using Environment.GetFolderPath method.
//Or you can move default profiles into a folder you prefer.
string AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string ProfilePath = Path.Combine(AppDataPath, #"UDC Profiles\Drawing to PDF.xml");
Profile.Load(ProfilePath);
Profile.OutputLocation.Mode = LocationModeID.LM_PREDEFINED;
Profile.OutputLocation.FolderPath = #"c:\UDC Output Files";
Profile.PostProcessing.Mode = PostProcessingModeID.PP_OPEN_FOLDER;
AutoCAD.AcadApplication App = new AutoCAD.AcadApplicationClass();
double Version = double.Parse(App.Version.Substring(0, 4), new CultureInfo("en-US"));
//Open drawing from file
Object ReadOnly = false;
Object Password = Type.Missing;
AutoCAD.AcadDocument Doc = App.Documents.Open(AutoCADFilePath, ReadOnly, Password);
//AutoCAD.Common.AcadPaperSpace ActiveSpace;
AutoCAD.Common.AcadLayout Layout;
//Change AutoCAD preferences for scaling the drawing to page
if (Doc.ActiveSpace == 0)
Layout = Doc.PaperSpace.Layout;
else
Layout = Doc.ModelSpace.Layout;
Layout.PlotType = AutoCAD.Common.AcPlotType.acExtents;
Layout.UseStandardScale = true;
Layout.StandardScale = AutoCAD.Common.AcPlotScale.acScaleToFit;
Layout.CenterPlot = true;
Object nBACKGROUNDPLOT = 0, nFILEDIA = 0, nCMDDIA = 0;
if (Version >= 16.1f)
{
nBACKGROUNDPLOT = Doc.GetVariable("BACKGROUNDPLOT");
nFILEDIA = Doc.GetVariable("FILEDIA");
nCMDDIA = Doc.GetVariable("CMDDIA");
Object xNull = 0;
Doc.SetVariable("BACKGROUNDPLOT", xNull);
Doc.SetVariable("FILEDIA", xNull);
Doc.SetVariable("CMDDIA", xNull);
}
Doc.Plot.QuietErrorMode = true;
//Plot the drawing
Doc.Plot.PlotToDevice("Universal Document Converter");
if (Version >= 16.1f)
{
//Restore AutoCAD default preferences
Doc.SetVariable("BACKGROUNDPLOT", nBACKGROUNDPLOT);
Doc.SetVariable("FILEDIA", nFILEDIA);
Doc.SetVariable("CMDDIA", nCMDDIA);
}
//Close drawing
Object SaveChanges = false;
Doc.Close(SaveChanges, Type.Missing);
//Close Autodesk AutoCAD
App.Quit();
}
static void Main(string[] args)
{
string TestFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFile.dwg");
PrintAutoCADtoPDF(TestFilePath);
}
}
}
Did you read the comments in the original source ?
This code is a example of using a third part application name Universal Document Converter (UDC) to build a standalone application (exe) to print the active space of a dwg file into a pdf file.
It requires the UDC software to be installed.
It cannot be transformed into an AutoCAD plugin (dll with CommandMethod).
You certainly can get more informations about this with the UDC Support.
You will not learn .NET and AutoCAD API by copying codes found on the web that you do not understand and asking someone here or elsewhere to modify them to suit your needs.
first: add a using to the runtime.
using Autodesk.AutoCAD.Runtime;
next: Add an attribute to your method.
[CommandMethod("YOURCOMMANDNAMEINAUTOCAD")]
Last: Your class and method need to be public, for AutoCAD to see them.
Update: (Very last): your Method cannot take parameters.
I am attempting to programmatically create a rolling file appender in C#. I'm using Visual Studios 2008. I am using log4net version 1.2.0.30714.
My main issue is that my rolling file appender is acting like a file appender. The log file will not roll based upon any size or date criteria I give it. Below is my configuration and I would appreciate any insight or suggestions. Below the code is some of the ideas I have tried.
string path = "Logs\";
string filename = "test.log";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout("[%d] %l %n - %m %n%n");
patternLayout.ActivateOptions();
RollingFileAppender appender = new RollingFileAppender();
appender.Threshold = Level.ALL;
appender.StaticLogFileName = false;
appender.CountDirection = 0; // Makes the logs count 1, 2, 3
appender.RollingStyle = RollingFileAppender.RollingMode.Size;
appender.MaximumFileSize = "1KB";
appender.MaxFileSize = 1 * 1024; // 1 KB
appender.MaxSizeRollBackups = 5;
appender.DatePattern = "yy.MM.dd.hh.mm.ss";
appender.Layout = patternLayout;
appender.Name = "QTracImportHelper";
appender.ImmediateFlush = true;
appender.File = filename;
appender.Writer = new StreamWriter(path + filename, true);
appender.ActivateOptions();
Hierarchy hierarchy = (Hierarchy)LogManager.GetLoggerRepository();
hierarchy.Root.AddAppender(appender);
hierarchy.Configured = true;
I've noticed that removing the StreamWriter leads to no file being created at all but no exceptions. Removing the file name causes an exception from within log4net. I have tried using both MaxFileSize and MaximumFileSize to no avail as well as changing the rolling stile to Date and Composite. Additionally if the writer stream is malformed it will create the same exception as not including the File property ({"Value cannot be null.\r\nParameter name: fileName"}{System.ArgumentNullException}).
I think this may be due to you supplying the "Writer" parameter directly before the ActivateOptions() call. The writer should be opened by the RollingLogFileAppender not externally. It's only exposed because of the inheritance of the class from TextWriterAppender.
//Don't do this:
//appender.Writer = new StreamWriter(path + filename, true);
//Do fully-qualify the file name:
appender.File = Path.Combine(path, filename);
I believe I have been taking the right approach to this so far, but I would like to have a button start a video game on my computer.
So far, I have a button linking to a process:
void button2_Click(object sender, EventArgs e)
{
process1.Start();
}
this.process1.EnableRaisingEvents = true;
this.process1.StartInfo.Domain = "";
this.process1.StartInfo.FileName = "MBO\\marbleblast.exe";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.SynchronizingObject = this;
this.process1.Exited += new System.EventHandler(this.Process1Exited);
So, where-ever I place the EXE (the one I'm coding), it will launch the "marbleblast.exe" under the subfolder MBO relative to it's location.
It seems to be working and trying to launch the game, however, it says it cannot load files that are there. I tested the game without my launcher, and it worked. I believe it's trying to run the EXE, but not letting it use the other files inside of it's folder.
I'll give more details if needed.
How can I get the game to run normally?
try adding this
this.process1.StartInfo.WorkingDirectory= "MBO\\";
or something similar to set the Working Directory.
this.process1.StartInfo.WorkingDirectory= "MBO\";
There's sloppy programming in the game, it relies on the Environment.CurrentDirectory being set right. Which by default is the same directory as where the EXE is located. The upvoted answer repeats the mistake though. To make that statement actually fix the problem, you now rely on your CurrentDirectory being set right. If it is not set where you think it is then it still won't work.
The problem with the program's current directory is that it can be changed by software that you don't control. The classic example is OpenFileDialog with the RestoreDirectory property set to the default value of false. Etcetera.
Always program defensively and pass the full path name of files and directories. Like c:\mumble\foo.ext. To get that going, start with Assembly.GetEntryAssembly().Location, that's the path to your EXE. Then use the System.IO.Path class to generate path names from that. The correct always-works code is:
using System.IO;
using System.Reflection;
...
string myDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string gameDir = Path.Combine(myDir, "MBO");
string gameExe = Path.Combine(gameDir, "marbleblast.exe");
process1.StartInfo.FileName = gameExe;
process1.StartInfo.WorkingDirectory = gameDir;
process1.SynchronizingObject = this;
process1.EnableRaisingEvents = true;
process1.Exited += new EventHandler(Process1Exited);
Set the WorkingDirectory property of the ProcessInfo to the correct directory.
I am Dobrakmato from MBForums. You simple need to add Working directory for Marble Blast.
this.process1.EnableRaisingEvents = true;
this.process1.StartInfo.Domain = "";
this.process1.StartInfo.FileName = "MBO\\marbleblast.exe";
this.process1.StartInfo.WorkingDirectory = "pathto marbleblast.exe directory";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.SynchronizingObject = this;
this.process1.Exited += new System.EventHandler(this.Process1Exited);
I managed to accidentally delete a backup of files I had which I then later recovered. The recovery has lost the files names and location and I am left with about 3000+ .indd (Adobeb InDesign) files.
My problem is I am trying to find the .indd file that I was working on with out having to open each one manually to check.
I know some of the words that I had and I am wondering if I could maybe read the .indd file using a binary reader looking for one of the keywords...I could build it in c# or whatever
Anyone got any ideas?
If regular search does not work, try the built in scripting, of which you can use Javascript, Visual Basic Script, or AppleScript to code. I'm going with JS...
I'm no expert, but I found this code snippet from page 101 of InDesignCS5_ScriptingGuide_JS.pdf and modified it a bit:
var folder = new Folder("C:/Path/To/Files");
var files = folder.getFiles('*.indd');
for (var i=0; i<files.length; i++) {
var file = files[i];
open(file):
var myDocument = app.activeDocument;
//Clear the find/change text preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Search the document for the string "Important Text".
app.findTextPreferences.findWhat = "Important Text";
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = true;
app.findChangeTextOptions.includeHiddenLayers = true;
app.findChangeTextOptions.includeLockedLayersForFind = true;
app.findChangeTextOptions.includeLockedStoriesForFind = true;
app.findChangeTextOptions.includeMasterPages = true;
app.findChangeTextOptions.wholeWord = false;
//Perform search
var myFoundItems = myDocument.findText();
if (myFoundItems.length) {
alert("FOUND!");
break;
}
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
myDocument.close();
}
Don't quote me on that, I did not actually run the code, but that's the idea.