log4net: Logging works only in the Mainclass - log4net

I've got a Windows Service that creates an instance of a Class every x minutes by using System.Threads and Timers.The logging in the mainclass where the servicecall is made works, but the called classes can't log, i just do not get any output.
Thats my framework of the mainclass:
/// <summary>
/// Create an Instance of the Log
/// </summary>
private static readonly ILog logger = LogManager.GetLogger("Test");
/// <summary>
/// Get the Instance of the Log
/// </summary>
internal static ILog log
{
get { return logger; }
}
If i now call out of any other class the Service.log reference and try to write a log, e.g Service.log.Info("test"); nothing comes up.
If i try to create a new Instance of the log in the 2nd Class, by using
/// <summary>
/// Create an Instance of the Log
/// </summary>
private static readonly ILog logsomething = LogManager.GetLogger("Test");
I do not get any output either, it only works in the mainclass. i cant get it to work in any other threaded class. My configuration is based on RollingFileAppender.

May be log4net is erring out. Enable tracing and check the log for additional details.
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4net.txt" />
</listeners>
</trace>

Related

Quartz.net RFC 2445 or RFC 5545 instead of CRON

We have a web server running in .NET which uses Quartz to schedule jobs.
The triggers for the jobs are provided in RFC 2445 format, but Quartz uses the CRON format. I would now like to either
A: Find a library which can convert my RFC 2445 rule to a CRON Rule
B: Rather, give Quartz the RFC rule.
In the latter case, I found some Java libraries but not for .NET.
I also tried writing my own library but I'm stuck with intervals. An RFC2445 rule can define a biweekly (or triweekly or n-weekly) job with
FREQ=WEEKLY;BYDAY=MO;INTERVAL=2
I.e. Every other monday. Yet CRON does not seem to have this functionality.
I have a similar requirement and I couldn't find a RFC 5545 compliant library to work with Quartz scheduler and ended up implementing a custom trigger myself following this suggestion
In my case we are using Telerik Scheduler control to populate the RRULE but you could probably do the same with iCal.Net library as well. This is not the full implementation here but it will get you started and the code is UNTESTED.
Another note: "FREQ=WEEKLY;BYDAY=MO;INTERVAL=2" will probably fail if you try to parse it using Telerik RecurrenceRule, since it's missing DTSTART, DTEND etc. This is an example of a recurrence rule string that will not fail: "DTSTART:20210309T050000Z\r\nDTEND:20210309T060000Z\r\nRRULE:FREQ=WEEKLY;BYDAY=TU;INTERVAL=1".
You need to implement ITrigger interface. A lot of it can be copied from CroneTriggerImpl class and modified.
public interface IRRuleTrigger : ITrigger
{
string RecurrenceRuleString { get; set; }
}
Then you need an implementation class inherited from AbstractTrigger
public class MyTriggerImpl: AbstractTrigger, IRRuleTrigger
{
//implement all members here. Look at CronTriggerImpl class in Quartz.Net source. I'm pasting some of the implementation code but not all.
//...
private RecurrenceRule rRule;
/// <summary>
/// Gets or sets the RRULE expression string.
/// </summary>
/// <value>The expression string.</value>
public string RecurrenceRuleString
{
set
{
TimeZoneInfo originalTimeZone = TimeZone;
var success = RecurrenceRule.TryParse(value, out var parsedRule);
if(success) rRule = parsedRule ;// RecurrenceRule(value!);
}
get => rRule?.ToString();
}
/// <summary>
/// Gets or sets the RRULE expression string.
/// </summary>
/// <value>The expression string like RRULE:FREQ=WEEKLY;BYDAY=MO;INTERVAL=2.</value>
public string RecurrenceRuleString
{
set
{
TimeZoneInfo originalTimeZone = TimeZone;
var success = RecurrenceRule.TryParse(value, out var parsedRule);
if(success) rRule = parsedRule ;// RecurrenceRule(value!);
}
get => rRule?.ToString();
}
////////////////////////////////////////////////////////////////////////////
//
// Computation Functions
//
////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the next time to fire after the given time.
/// </summary>
/// <param name="afterTime">The time to compute from.</param>
/// <returns></returns>
protected DateTimeOffset? GetTimeAfter(DateTimeOffset afterTime)
{
return rRule?.HasOccurrences == true ?
rRule?.Occurrences.Where(o => o > afterTime).Min()
: null;
}
/// <summary>
/// Returns the time before the given time
/// that this <see cref="IRRuleTrigger" /> will fire.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
protected DateTimeOffset? GetTimeBefore(DateTimeOffset? date)
{
return rRule?.HasOccurrences == true ?
rRule?.Occurrences.Where(o=> o < date).Max()
: null;
}
}
public class RRuleScheduleBuilder : ScheduleBuilder<IRRuleTrigger>
{
private int misfireInstruction = MisfireInstruction.SmartPolicy;
private RecurrenceRule recurrenceRule;
public override IMutableTrigger Build()
{
MyTriggerImpl myTriggerImpl = new MyTriggerImpl();
myTriggerImpl.MisfireInstruction = misfireInstruction;
myTriggerImpl.RecurrenceRuleString = this.recurrenceRule.ToString();
return myTriggerImpl;
}
/// <summary>
/// Create a RRuleScheduleBuilder with the given string expression - which
/// is presumed to be valid expression (and hence only a RuntimeException
/// will be thrown if it is not).
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="recurrenceRuleString">the RRule expression to base the schedule on.</param>
/// <returns>the new RRuleScheduleBuilder</returns>
public static RRuleScheduleBuilder RecurrenceRuleSchedule(string recurrenceRuleString)
{
var success = RecurrenceRule.TryParse(recurrenceRuleString, out var rRule);
if(!success) throw new ArgumentException($"Recurrence Rule String ({recurrenceRuleString}) is invalid.");
return new RRuleScheduleBuilder(rRule);
}
protected RRuleScheduleBuilder(RecurrenceRule rule)
{
this.recurrenceRule = rule ?? throw new ArgumentNullException(nameof(rule), "recurrenceRule cannot be null");
}
}
/// <summary>
/// Extension methods that attach <see cref="RRuleScheduleBuilder" /> to <see cref="TriggerBuilder" />.
/// </summary>
public static class RRuleScheduleTriggerBuilderExtensions
{
public static TriggerBuilder WithRRuleSchedule(this TriggerBuilder triggerBuilder, string recurrenceRuleString)
{
RRuleScheduleBuilder builder = RRuleScheduleBuilder.RecurrenceRuleSchedule(recurrenceRuleString);
return triggerBuilder.WithSchedule(builder);
}
public static TriggerBuilder WithRRuleSchedule(this TriggerBuilder triggerBuilder, string recurrenceRuleString, Action<RRuleScheduleBuilder> action)
{
RRuleScheduleBuilder builder = RRuleScheduleBuilder.RecurrenceRuleSchedule(recurrenceRuleString);
action(builder);
return triggerBuilder.WithSchedule(builder);
}
}
After implementing that, you can create and use your trigger like this:
// Grab the Scheduler instance from the Factory
StdSchedulerFactory factory = new StdSchedulerFactory();
var scheduler = await factory.GetScheduler();
await scheduler.Start();
var job = JobBuilder.Create<MyBusinessClassThatImplementsIJobInterface>()
.WithIdentity("someIdentity", "someGroupName")
.Build();
var trigger = (IRRuleTrigger)TriggerBuilder.Create()
.WithIdentity("someName", "myGroup")
.WithRRuleSchedule(rule.ToString())
.Build();
await scheduler.ScheduleJob(job, trigger);

Register custom class in Kentico 9

I have created a custom gateway class and I need to register this in admin module.
I have added this line in cs file but it throws a namespace error
[assembly: RegisterCustomClass("CustomGateway", typeof(CustomGateway))]
Also in admin -> modules-> e-commerce -> classes tab it says I cannot add or delete class in installed module.
How should I register my customgateway class ?
Make sure you add a using statement for the CMS namespace in the .cs file.
using CMS;
Furthermore, if your CustomGateway class is in a custom namespace (let's call it MyCompany), you will need to add a using statement for that namespace, as well.
using CMS;
using MyCompany;
Regarding the "Classes" tab - the e-commerce classes have nothing to do with registering a custom payment gateway.
As long as you have registered it with the RegisterCustomClass attribute, it will be fine.
You can then proceed with setting it up in the "Store configuration" application.
The full docs regarding custom payment gateways can be found here.
You can't register custom payment gateway class in the module in the Admin UI, you can only do it by placing .cs file in your module folder. That will allow to easly export gateway class within your module.
This is how I've done in 8.2. Example below is for in E-Commerce module. Try it:
public partial class CMSModuleLoader
{
#region "Macro methods loader attribute"
/// <summary>
/// Module registration
/// </summary>
private class CustomGatewayLoaderAttribute : CMSLoaderAttribute
{
/// <summary>
/// Constructor
/// </summary>
public CustomGatewayLoaderAttribute()
{
// Require E-commerce module to load properly
RequiredModules = new string[] { ModuleName.ECOMMERCE };
}
/// <summary>
/// Initializes the module
/// </summary>
public override void Init()
{
// This line provides the ability to register the classes via web.config cms.extensibility section from App_Code
ClassHelper.OnGetCustomClass += GetCustomClass;
}
/// <summary>
/// Gets the custom class object based on the given class name. This handler is called when the assembly name is App_Code.
/// </summary>
private static void GetCustomClass(object sender, ClassEventArgs e)
{
if (e.Object == null)
{
// Provide your custom classes
switch (e.ClassName.ToLower())
{
// Define the class CustomGatewayProvider inheriting the CMSPaymentGatewayProvider and you can customize the provider
case "customgatewayprovider":
e.Object = new CustomGatewayProvider();
break;
}
}
}
}
#endregion
}

How to have a configuration based queue name for web job processing?

I have a webjob app to process a ServiceBus queue, which runs fine, with the following method:
public static void ProcessQueueMessage([ServiceBusTrigger("myQueueName")] BrokeredMessage message, TextWriter log)
However, I would like to be able to change the queue name without recompiling, according for example to a configuration appsetting, can it be done?
Yes, you can do this. You can implement your own INameResolver and set it on JobHostConfiguration.NameResolver. Then, you can use a queue name like %myqueue% in our ServiceBusTrigger attribute - the runtime will call your INameResolver to resolve that %myqeuue% variable - you can use whatever custom code you want to resolve the name. You could read it from app settings, etc.
I've found an implementation of the INameResolver using configuration setting from the azure-webjobs-sdk-samples.
/// <summary>
/// Resolves %name% variables in attribute values from the config file.
/// </summary>
public class ConfigNameResolver : INameResolver
{
/// <summary>
/// Resolve a %name% to a value from the confi file. Resolution is not recursive.
/// </summary>
/// <param name="name">The name to resolve (without the %... %)</param>
/// <returns>
/// The value to which the name resolves, if the name is supported; otherwise throw an <see cref="InvalidOperationException"/>.
/// </returns>
/// <exception cref="InvalidOperationException"><paramref name="name"/>has not been found in the config file or its value is empty.</exception>
public string Resolve(string name)
{
var resolvedName = CloudConfigurationManager.GetSetting(name);
if (string.IsNullOrWhiteSpace(resolvedName))
{
throw new InvalidOperationException("Cannot resolve " + name);
}
return resolvedName;
}
}

DataAnnotation in Universal App

I have used Data Annotations in my project, but in the universal app, it shows an error for there is no namespace for DataAnnotations.
Is "using System.ComponentModel.DataAnnotations" supported in Unversal App ?
Doesn't look like it. According to their roadmap You'll have to scroll down to the bottom table to see that it's available for every platform but the phone. :(
yes, it is support in Windows Universal app, sample code:
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace SystematixIndia.Universal.Extensions
{
/// <summary>
/// Provides extensions for the <see cref="Enum" /> class.
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// Gets the display name attribute as a string
/// </summary>
/// <param name="en">The enum.</param>
/// <returns>The display name attribute as a string</returns>
public static string ToDisplayNameAttribute(this Enum en)
{
return en.GetType().GetMember(en.ToString()).First().GetCustomAttribute<DisplayAttribute>().GetName();
}
}
}

Multithreading Entity Framework: The connection was not closed. The connection's current state is connecting

So I have a windows service process that performs a workflow process. The back end uses Repository and UnitofWork Pattern and Unity on top of Entity Framework with the entities class generated from the edmx. I won't go into a whole lot of detail as its not necessary but basically there are 5 steps that the workflow goes through. A particular process might be at any stage at any point in time (in order of course). Step one just generates data for step two, which validates the data via a long running process to another server. Then step there generates a pdf with that data. For each stage we spawn a timer, however it is configurable to allow more than one timer to be spawned for each stage. Therein lays the problem. When I add a processor to a particular stage, it the following error randomly:
The connection was not closed. The connection's current state is connecting.
Reading up on this it seems obvious that this is happening because the context is trying to access the same entity from two threads. But this is where it is kind of throwing me for a loop. All of the information I can find on this states that we should be using a instance context per thread. Which as far as I can tell I am doing (see the code below). I am not using singleton pattern or statics or anything so I am not really sure why this is happening or how to avoid it. I have posted the relevant bits of my code below for your review.
The base repository:
public class BaseRepository
{
/// <summary>
/// Initializes a repository and registers with a <see cref="IUnitOfWork"/>
/// </summary>
/// <param name="unitOfWork"></param>
public BaseRepository(IUnitOfWork unitOfWork)
{
if (unitOfWork == null) throw new ArgumentException("unitofWork");
UnitOfWork = unitOfWork;
}
/// <summary>
/// Returns a <see cref="DbSet"/> of entities.
/// </summary>
/// <typeparam name="TEntity">Entity type the dbset needs to return.</typeparam>
/// <returns></returns>
protected virtual DbSet<TEntity> GetDbSet<TEntity>() where TEntity : class
{
return Context.Set<TEntity>();
}
/// <summary>
/// Sets the state of an entity.
/// </summary>
/// <param name="entity">object to set state.</param>
/// <param name="entityState"><see cref="EntityState"/></param>
protected virtual void SetEntityState(object entity, EntityState entityState)
{
Context.Entry(entity).State = entityState;
}
/// <summary>
/// Unit of work controlling this repository.
/// </summary>
protected IUnitOfWork UnitOfWork { get; set; }
/// <summary>
///
/// </summary>
/// <param name="entity"></param>
protected virtual void Attach(object entity)
{
if (Context.Entry(entity).State == EntityState.Detached)
Context.Entry(entity).State = EntityState.Modified;
}
protected virtual void Detach(object entity)
{
Context.Entry(entity).State = EntityState.Detached;
}
/// <summary>
/// Provides access to the ef context we are working with
/// </summary>
internal StatementAutoEntities Context
{
get
{
return (StatementAutoEntities)UnitOfWork;
}
}
}
StatementAutoEntities is the autogenerated EF class.
The repository implementation:
public class ProcessingQueueRepository : BaseRepository, IProcessingQueueRepository
{
/// <summary>
/// Creates a new repository and associated with a <see cref="IUnitOfWork"/>
/// </summary>
/// <param name="unitOfWork"></param>
public ProcessingQueueRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
/// <summary>
/// Create a new <see cref="ProcessingQueue"/> entry in database
/// </summary>
/// <param name="Queue">
/// <see cref="ProcessingQueue"/>
/// </param>
public void Create(ProcessingQueue Queue)
{
GetDbSet<ProcessingQueue>().Add(Queue);
UnitOfWork.SaveChanges();
}
/// <summary>
/// Updates a <see cref="ProcessingQueue"/> entry in database
/// </summary>
/// <param name="queue">
/// <see cref="ProcessingQueue"/>
/// </param>
public void Update(ProcessingQueue queue)
{
//Attach(queue);
UnitOfWork.SaveChanges();
}
/// <summary>
/// Delete a <see cref="ProcessingQueue"/> entry in database
/// </summary>
/// <param name="Queue">
/// <see cref="ProcessingQueue"/>
/// </param>
public void Delete(ProcessingQueue Queue)
{
GetDbSet<ProcessingQueue>().Remove(Queue);
UnitOfWork.SaveChanges();
}
/// <summary>
/// Gets a <see cref="ProcessingQueue"/> by its unique Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ProcessingQueue GetById(int id)
{
return (from e in Context.ProcessingQueue_SelectById(id) select e).FirstOrDefault();
}
/// <summary>
/// Gets a list of <see cref="ProcessingQueue"/> entries by status
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
public IList<ProcessingQueue> GetByStatus(int status)
{
return (from e in Context.ProcessingQueue_SelectByStatus(status) select e).ToList();
}
/// <summary>
/// Gets a list of all <see cref="ProcessingQueue"/> entries
/// </summary>
/// <returns></returns>
public IList<ProcessingQueue> GetAll()
{
return (from e in Context.ProcessingQueue_Select() select e).ToList();
}
/// <summary>
/// Gets the next pending item id in the queue for a specific work
/// </summary>
/// <param name="serverId">Unique id of the server that will process the item in the queue</param>
/// <param name="workTypeId">type of <see cref="WorkType"/> we are looking for</param>
/// <param name="operationId">if defined only operations of the type indicated are considered.</param>
/// <returns>Next pending item in the queue for the work type or null if no pending work is found</returns>
public int GetNextPendingItemId(int serverId, int workTypeId, int? operationId)
{
var id = Context.ProcessingQueue_GetNextPending(serverId, workTypeId, operationId).SingleOrDefault();
return id.HasValue ? id.Value : -1;
}
/// <summary>
/// Returns a list of <see cref="ProcessingQueueStatus_dto"/>s objects with all
/// active entries in the queue
/// </summary>
/// <returns></returns>
public IList<ProcessingQueueStatus_dto> GetActiveStatusEntries()
{
return (from e in Context.ProcessingQueueStatus_Select() select e).ToList();
}
/// <summary>
/// Bumps an entry to the front of the queue
/// </summary>
/// <param name="processingQueueId"></param>
public void Bump(int processingQueueId)
{
Context.ProcessingQueue_Bump(processingQueueId);
}
}
We use Unity for dependency injection, some calling code for example:
#region Members
private readonly IProcessingQueueRepository _queueRepository;
#endregion
#region Constructors
/// <summary>Initializes ProcessingQueue services with repositories</summary>
/// <param name="queueRepository"><see cref="IProcessingQueueRepository"/></param>
public ProcessingQueueService(IProcessingQueueRepository queueRepository)
{
Check.Require(queueRepository != null, "processingQueueRepository is required");
_queueRepository = queueRepository;
}
#endregion
The code in the windows service that kicks off the timers is as follows:
_staWorkTypeConfigLock.EnterReadLock();
foreach (var timer in from operation in (from o in _staWorkTypeConfig.WorkOperations where o.UseQueueForExecution && o.AssignedProcessors > 0 select o)
let interval = operation.SpawnInternval < 30 ? 30 : operation.SpawnInternval
select new StaTimer
{
Interval = _runImmediate ? 5000 : interval*1000,
Operation = (ProcessingQueue.RequestedOperation) operation.OperationId
})
{
timer.Elapsed += ApxQueueProcessingOnElapsedInterval;
timer.Enabled = true;
Logger.DebugFormat("Queue processing for operations of type {0} will execute every {1} seconds", timer.Operation, timer.Interval/1000);
}
_staWorkTypeConfigLock.ExitReadLock();
StaTimer is just a wrapper on timer adding operation type. ApxQueueProcessingOnElapsedInterval then bascially just assigns work to the process based on the operation.
I will also add a bit of the ApxQueueProcessingOnElapsedInterval code where we are spawning tasks.
_staTasksLock.EnterWriteLock();
for (var x = 0; x < tasksNeeded; x++)
{
var t = new Task(obj => ProcessStaQueue((QueueProcessConfig) obj),
CreateQueueProcessConfig(true, operation), _cancellationToken);
_staTasks.Add(new Tuple<ProcessingQueue.RequestedOperation, DateTime, Task>(operation, DateTime.Now,t));
t.Start();
Thread.Sleep(300); //so there are less conflicts fighting for jobs in the queue table
}
_staTasksLock.ExitWriteLock();
Looks like your service, repository and context are supposed to live for the whole life time of your application but that is incorrect. You can have multiple timers triggered at the same time. That means multiple threads will use your service in parallel and they will execute the code of your service in their thread = context is shared among multiple threads => exception because context is not thread safe.
The only option is to use a new context instance for each operation you want to execute. You can for example change your classes to accept context factory instead of context and get a new context for each operation.
In case this helps anyone:
In my case, I did ensure that the non-thread-safe DbContext had a TransientLifetime (using Ninject), but it was still causing concurrency issues! Turns out that in some of my custom ActionFilters I used Dependency Injection to get access to the DbContext in the constructor, but ActionFilters have a lifetime that keeps them instantiated over multiple requests, so the context didn't get recreated.
I fixed it by manually resolving the dependency in the OnActionExecuting method instead of in the constructor so that it is a fresh instance every time.
In my case I was getting this problem because I forgot the await keyword before one of my DAL function calls. Putting await there resolved it.

Resources