Delete files older then X day.. BUT not by date modified - batch-file

I have a config file for an .exe my workplace built where you can specify deleting of files (specifically retaining the last say 30 days files in my test here [logs and sql are fine]) and it even clears out sub folders. however it is deleting by date modified, so newer folders with some old remnents of data are getting the old remnents deleted.
Folder1:
File: Modified:
File 1 2018/02/02
File 2 2010/05/06
File 3 2018/02/01
Folder 2:
File: Modified:
File 1 2011/12/30
File 2 2006/01/16
File 3 2018/02/02
Would leave:
Folder1:
File: Modified:
File 1 2018/02/02
File 3 2018/02/01
Folder 2:
File: Modified:
File 3 2018/02/02
Is there anyway to change this so it retains the last 30 folders and contents,, deleting everything else?
This is the contents of the "cleaner".exe.config file I have:
<?xml version="2.0" encoding="utf-8"?> <configuration> <configSections> </configSections> <!-- Make sure that every new location has a name with an increasing number e.g clear 1 -->
<appSettings>
<add key="connstring" value="Data Source=localhost;user id = *****;password = *****;Initial Catalog =Database;" />
<add key="sqldays" value="180" />
<add key="LogLocation" value="C:\File\Logs\Cleaner\" />
<add key="clear" value="C:\Directory\Logs,90" />
<add key="clear2" value="C:\Directory\CSV\Backup,30 " />
<add key="fileExtensions" value=".txt,.csv,.log,.fmt,.hdr,.Log" />
<add key="ClientSettingsProvider.ServiceUri" value="" /> </appSettings> </configuration>

Just to close this out it didnt matter about the modified date, the files just needed to 'be gone' so I added a few more directories to the config file and let it loose.
Example:
<?xml version="2.0" encoding="utf-8"?> <configuration> <configSections> </configSections> <!-- Make sure that every new location has a name with an increasing number e.g clear 1 -->
<appSettings>
<add key="connstring" value="Data Source=localhost;user id = *****;password = *****;Initial Catalog =Database;" />
<add key="sqldays" value="180" />
<add key="LogLocation" value="C:\File\Logs\Cleaner\" />
<add key="clear" value="C:\Directory\Logs,90" />
<add key="clear2" value="C:\Directory\CSV\Backup,30 " />
<add key="clear3"value="C:\Directory1\CSV\Backup,30 " />
<add key="clear4" value="C:\Directory2\CSV\Backup,30 " />
<add key="fileExtensions" value=".txt,.csv,.log,.fmt,.hdr,.Log" />
<add key="ClientSettingsProvider.ServiceUri" value="" /> </appSettings> </configuration>

Related

How to resolve key/value pair with external .config file

I am specifying <appSettings> in my app.config file, I am adding
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings configSource="ShareAppSettings.debug.config"/>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1"/>
</startup>
</configuration>
ShareAppSettigns.debug.config is my external config file, which I am using on my local machine and I do not want to share it with the rest of my team.
ShareAppSettings.debug.config looks like:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="clientID" value="11" />
<add key="clientSecret" value="11" />
<add key="tenantID" value="11" />
</appSettings>
Whenever I am trying to debug the main code:
private static List<string> AppCredentials()
{
string clientID = ConfigurationManager.AppSettings["clientID"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
string tenantID = ConfigurationManager.AppSettings["tenantID"];
List<string> appCred = new List<string> { clientID, clientSecret, tenantID };
if (clientID == null)
throw new Exception("ShareAppSettings.Debug.Config file was not provided in this repo.");
return (appCred);
}
For some reason I am not getting values for clientId, slientSecret nor tenantId. This code is a part of grasshopper Add-on for v6 template, and its running on .NET Framework 4.7.1. Whenever I copy the same code into a new C# console of a same framework, the code is built. I would truly appreciate if you could give me suggestions on how to solve this.
What "EnableWindowsFormsHighDpiAutoResizing" means and how can make this work?
Many Thanks
enter image description here
I suggest to use the file attribute (corresponding to the AppSettingsSection.File property) instead of the configSource attribute (corresponding to the SectionInformation.ConfigSource property) in the appSettings section.
configSource doesn't support other keys in the section, while appSettings may contain other keys, needed by the Application and possibly somewhere else (someone else may add/remove them - for testing purposes or any other reason).
The file attribute allows instead the presence of other key in the appSettings section.
Your app.config file can be:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings file="ShareAppSettings.debug.config">
<add key="DpiAwareness" value="PerMonitorV2"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1"/>
</startup>
</configuration>
Now the values are accessible by both opening a named configuration section:
appSettings.Settings[] returns a KeyValueConfigurationElement
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
var kvpClientID = appSettings.Settings["clientID"];
var kvpClientSecret = appSettings.Settings["clientSecret"];
var kvpCenantID = appSettings.Settings["tenantID"];
string clientID = kvpClientID.Value;
and directly, using ConfigurationManager.AppSettings - a NameValueCollection - which returns the value of the specified key:
string clientID = ConfigurationManager.AppSettings["clientID"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
string tenantID = ConfigurationManager.AppSettings["tenantID"];
As a note, using the file attribute, your ShareAppSettings.debug.config doesn't need (but it's not forbidden) the XML header, it can be just:
<appSettings>
<add key="clientID" value="11" />
<add key="clientSecret" value="11" />
<add key="tenantID" value="11" />
</appSettings>
Secondary note:
you can set the file attribute to point to another file at run-time and refresh the appSettings values to updated the configuration.
Note that, if a file attribute was already set, all values contained in that .config file are not dismissed, but instead moved to the [Application].exe.config file, to become part of the <appSettings> section (thus, they are preserved).
Another reason why using the file attribute may be preferable.
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var appSettings = config.AppSettings;
appSettings.File = "SomeOtherFile.config";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

log4net log file not being written when the app is deployed

I have a WPF app that uses log4net. When I run it in Visual Studio, the log file is created in the Debug or Release folder as expected.
However, when I create an installer and run the installed app, the log file is not created. I added the following lines to the code...
string logFilePath = ((Hierarchy)LogManager.GetRepository())
.Root.Appenders.OfType<FileAppender>()
.FirstOrDefault()?.File;
using (StreamWriter sw = new StreamWriter(#"d:\log.log")) {
sw.WriteLine("Log file: " + logFilePath);
}
...to enable me to check that the log file was being written in the location I expected. It showed me that the log file was supposed to be written to C:\Program Files (x86)\Physio Diary\PhysioDiaryClient.log which is what I expected.
However, the file doesn't exist. Any idea why?
Here is the top of the App.config file...
<?xml version="1.0"
encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender"
type="log4net.Appender.RollingFileAppender">
<param name="File"
value="PhysioDiaryClient.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-7level %logger - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
The bottom of the file looks like this...
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
The bits in between are all to do with the WCF services that the app uses.
Anyone any ideas?
Edit: As a test, I tried hard-coding the log file path in App.config to my D: drive (so it's hard-coded, and no question of a permissions issue), but the file still wasn't created.
Thanks to #dymanoid for pointing me in the right direction. The log4net docs are a bit weak in this area, but I found this answer that pointed out that you can use normal environment variables in the config file.
With the aid of this list of environment variables, I ended up with the following...
<param name="File"
value="${LOCALAPPDATA}\Physio Diary\PhysioDiaryClient.log" />
This correctly write the file to C:\Users\MyUsername\AppData\Local\Physio Diary\PhysioDiaryClient.log
Hope this helps someone.

Can't insert into SQL Server table with log4net AdoNetAppender

I am trying to understand how log4net works so I've added this to my app.config (I should add that Console Appender and FileAppender work perfectly, I only have trouble with the AdoNetAppender).
How can I debug this, to see if at least the connection to db succeeds?
The problem is the INSERT statement isn't executed.
I should add the
Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;password=juan,
works perfectly when I try to connect to SQL Server manually, so not sure if that's the problem.
Also, the ConnectionType was taken from the official site:
https://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Appender.AdoNetAppender.ConnectionType.html
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.log4netConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="AdoNetAppender"
type="log4net.Appender.AdoNetAppender">
<bufferSize value="10" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;Password=juan;Pooling=False" />
<commandText value="INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')" />
<commandType value="Text" />
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Later edit (after using the debug method recommended by David):
haacked.com is indeed extremely interesting, great tip! However, it seems that it's describing what I'm instructing log4net to log, but not the result of those actions(?), if I'm reading this well (no failed/or succeeded?)
e.g.
log4net: Setting Property [ConnectionType] to String value
[System.Data.SqlClien t.SqlConnection, System.Data,
Version=1.0.3300.0, Culture=neutral, PublicKeyToke n=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [Data
Source=MyWorkgroup\SQLEXPRESS; Initial
Catalog=MyNewDatabase;
User ID=juan; Password=juan;
Pooling=False] log4net: Setting Property [CommandText] to String value [INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')] log4net:
Setting Property [CommandType] to CommandType value [Text] log4net:
Created Appender [AdoNetAppender] log4net: Adding appender named
[AdoNetAppender] to logger [root]. log4net: Hierarchy Threshold []
Piece of code that helped me obtain this info (in case the site should become unavailable) is:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4netdiagn.txt" />
</listeners>
</trace>
</system.diagnostics>

XML Connectionstrings

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Citrus_Welding.My.MySettings.CitWeldConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Citrus Welding\CitWeld.mdb""
providerName="System.Data.OleDb" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
I am looking at the connection string, I need the Data Source to = a selected file from another page by default... I tried & pagename.openfiledialog.filename & but I keep getting an error. Any ideas?
It appears that you're saying that you want the user to be able to set the Data Source at run time. If so then omit it from the connection string in the config file and set it like this at run time:
Dim builder As New OleDbConnectionStringBuilder(My.Settings.CitWeldConnectionString)
builder.DataSource = newDataSourceValue
Dim connection As New OleDbConnection(builder.ConnectionString)

Setting up BugTracker.NET complete noob

This is my first ASP.NET project and I'm stuck right away.
I'm setting up a bugtracker on a remote webhotel but I can't get the connectionstrings to work.
If we say that my host is called hosting.org and my website would be www.trallala.com
what do I have to change in this script?
<configSections>
</configSections>
<system.web>
<!--
BugTracker.NET is not compatible with Session serialization.
Timeout session after 120 minutes
-->
<sessionState mode="InProc" timeout="120"/>
<compilation debug="true">
<assemblies>
<add assembly="System.DirectoryServices.Protocols, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<pages validateRequest="true" />
<!-- A few people over the years have needed to override the default IIS settings...
<httpRuntime executionTimeout="300" maxRequestLength="51200"/>
-->
<!-- for my testing <globalization culture="de-DE" uiCulture="en-US" /> -->
</system.web>
<appSettings>
<!--
********* QUICK START *************
If you want to get started quickly, then just change the following
and then try to log in:
ConnectionString
AbsouteUrlPrefix
After you can log in and create a bug, then you probably want to
set up the email integration. Set up the following:
ErrorEmailTo
ErrorEmailFrom
NotificationEmailEnabled
NotificationEmailFrom
And your SMTP settings below.
-->
<!--
Change this to point to your database
-->
<add key="ConnectionString" value="server=(local)\SQLEXPRESS;database=btnet;user id=sa;password=x;Trusted_Connection=no"/>
<!--
Used when creating absolute href's. For example, in notification emails.
Don't forget trailing slash!.
-->
<add key="AbsoluteUrlPrefix" value="http://127.0.0.1/btnet2/"/>
<!--
You can turn the logging and emailing of errors on and off.
Log file name is "btnet_log_yyyy_mm_dd.txt"
For the LogFileFolder setting, if you specify the folder starting with a
drive letter or the \\ that indicates a UNC path, it's treated as a full path.
For example: c:\\something or \\somemachine\something
Otherwise it's treated as a path relative to where you virtual directory is
located.
LogEnabled turns on and off logging as a whole.
LogSqlEnabled turns on and off just the logging of SQL statements, but
that's about 98% of what gets logged, so if you want to reduce the
volume, turn that off.
-->
<add key="LogEnabled" value="1"/>
<add key="LogSqlEnabled" value="1"/>
<add key="LogFileFolder" value="App_Data\logs"/>
<!-- If BugTracker.NET itself experiences an error, it can send an email notification -->
<add key="ErrorEmailEnabled" value="1"/>
<add key="ErrorEmailTo" value="YOUR EMAIL HERE"/>
<add key="ErrorEmailFrom" value="FROM EMAIL HERE"/>
<!--
You can "subscribe" to email notifications on a per-bug basis.
You will receive an email whenever the bug is updated.
-->
<add key="NotificationEmailEnabled" value="1"/>
<add key="NotificationEmailFrom" value="FROM EMAIL HERE"/>
<!--
This controls the format of the subject of the email notifications.
The available variables are:
$THING$ - from the "SingularBugLabel" setting
$BUGID$
$ACTION$ - added or changed
$SHORTDESC$
$PROJECT$
$CATEGORY$
$ORGANIZATION$
$PRIORITY$
$STATUS$
$TRACKINGID$ - from the "TrackingIdString" setting
-->
<add key="NotificationSubjectFormat" value="$THING$:$BUGID$ was $ACTION$ - $SHORTDESC$ $TRACKINGID$"/>
<!--
If you aren't using the local SMTP server that comes with IIS,
set the name, user, and password for your SMTP server here.
-->
<!-- Sample SMTP Settings -->
<!--
These settings work with my SBC account
-->
<!--
<add key="SmtpServer" value="smtp.att.yahoo.com"/>
<add key="SmtpServerAuthenticateUser" value="ctrager#sbcglobal.net"/>
<add key="SmtpServerPort" value="465"/>
<add key="SmtpUseSSL" value="1"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
-->
<!--
These settings work with my GMail account
-->
<!--
<add key="SmtpServer" value="smtp.gmail.com"/>
<add key="SmtpServerAuthenticateUser" value="ctrager#gmail.com"/>
<add key="SmtpServerPort" value="465"/>
<add key="SmtpUseSSL" value="1"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
-->
<!--
These settings work with my GoDaddy account
-->
<!--
<add key="SmtpServer" value="relay-hosting.secureserver.net"/>
<add key="SmtpServerAuthenticateUser" value="ctrager#ifdefined.com"/>
<add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/>
<add key="SmtpServerPort" value="25"/>
-->
<!--
Specify the pickup directory if you have the problem described here:
http://support.microsoft.com/default.aspx?scid=kb;en-us;816789#8
-->
<!--
<add key="SmtpServerPickupDirectory" value=""/>
<add key="SmtpSendUsing" value="1"/>
-->
<!--
Ignore this setting unless you are esperiencing the symptoms
related to this: http://cr.yp.to/docs/smtplf.html
-->
<!--
<add key="SmtpForceReplaceOfBareLineFeeds" value="1"/>
-->
<!--
By default, emails are UTF8 encoded. If that doesn't work for you,
uncomment the following.
-->
<!--
<add key="BodyEncodingUTF8" value="0"/>
-->
<add key="ConnectionString" value="Persist Security Info=true;User ID=bugtracker;Password=bugs;Initial Catalog=BugTracker;Data Source=[IP ADDRESS]" />
This is what you'd need to add/edit in the web.config. once it's setup, BugTracker will run the scripts to create the proper database elements.
You need to make sure that "ConnectionString" points to the right Database and has the right username and password for DB-access.
You might want to make sure that your Database is actually up and running and that the username and password are correct by simply trying to log in as that user in your DB.
If that doesn't work, than the problem doesn't lie with your asp.net configuration.
The BugTracker.NET documentation includes this section on connection strings:
The hardest part ...for most people is getting the ConnectionString to work.
For help, see these links, the "SqlConnection (.NET)" sections
http://www.connectionstrings.com/?carrier=sqlserver2005
http://www.sqlstrings.com/SQL-Server-connection-strings.htm
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-3513_11-6084879.html
Another thing you might try to get the connection string right is the following:
Create a new blank file and name it test.udl.
Double click on it, and a "Data Link Properties" dialog should appear.
On "Providers" tab, select "Microsoft OLE DB Provider for SQL Server" or "SQL Native Client"
On "Connections" tab, try various settings and use the "Test Connection" button to test them. Click "Ok" when it works.
Open the test.udl file in Notepad and copy the line that starts with "Provider=" into your Web.config "ConnectionString" value, BUT delete the little part that says "Provider=SQLNCLI.1;"

Resources