DataAnnotation in Universal App - win-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();
}
}
}

Related

There is no implicit reference conversion from StatelessService to 'Microsoft.ServiceFabric.Services.Remoting.IService'

I am writing a new azure service application which can communicate using service remoting.
I referenced this article. I am facing error:
The type 'PushMsgStatelessService.PushMsgStatelessService' cannot be used as type parameter 'TStatelessService' in the generic type or method 'ServiceRemotingExtensions.CreateServiceRemotingListener(TStatelessService, StatelessServiceContext)'. There is no implicit reference conversion from 'PushMsgStatelessService.PushMsgStatelessService' to 'Microsoft.ServiceFabric.Services.Remoting.IService'. PushMsgStatelessService C:\Nirvana\DataPerPerson\Narendra\PushMessageService\PushMsgStatelessService\PushMsgStatelessService.cs 30 Active
My code:
using System.Collections.Generic;
using System.Fabric;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using Microsoft.ServiceFabric.Services.Remoting.Runtime;
namespace PushMsgStatelessService
{
interface IPushMessageService
{
Task<string> GetMessageAsync();
}
/// <summary>
/// An instance of this class is created for each service instance by the Service Fabric runtime.
/// </summary>
internal sealed class PushMsgStatelessService : StatelessService, IPushMessageService
{
public PushMsgStatelessService(StatelessServiceContext context)
: base(context)
{ }
public Task<string> GetMessageAsync()
{
return Task.FromResult("Hello!");
}
/// <summary>
/// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests.
/// </summary>
/// <returns>A collection of listeners.</returns>
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[] { new ServiceInstanceListener(context => this.CreateServiceRemotingListener(context)) };
}
}
}
I am stuck here.
You should add a reference to the IService interface in your interface. So change your interface IPushMessageService to interface IPushMessageService : IService.
Side node 1: You should probably make your interface public.
Side node 2: It is better to put your interface in a separate project to prevent any circular dependencies when working with remoting.

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;
}
}

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.

log4net: Logging works only in the Mainclass

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>

Resources