Why this error comes "The plug-in execution failed because no Sandbox Worker processes are currently available"? - dynamics-crm-2013

I am using an free trial version of online ms crm 2015 just to understand it and
I wrote this plugin with threads int them
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk; // for Iplugin interface
using nonitcompany; // for earlybinding generated by crmsvcuti.exe
using Microsoft.Crm.Sdk; //for stestate requests
using Microsoft.Crm.Sdk.Messages; //for stestate requests
namespace Plugin_on_create_deact_rec
{
public class account_deactivate:IPlugin
{
public static int semaphore0 = 0, semaphore1 = 0, semaphore2 = 0;
public static IPluginExecutionContext context;
public static IOrganizationServiceFactory factory;
public static IOrganizationService service;
public static IServiceProvider serviceProvider_;
public static Entity accounts;
public static SetStateRequest deactivate;
public static SetStateResponse setstate_response;
public void Execute(IServiceProvider serviceProvider)
{
serviceProvider_ = serviceProvider;
ThreadStart _context = new ThreadStart(context_);
ThreadStart _factory = new ThreadStart(factory_);
ThreadStart _execute = new ThreadStart(execute_);
Thread context_t = new Thread(_context);
Thread factory_t = new Thread(_factory);
Thread execute_t= new Thread(_execute);
context_t.Start();
factory_t.Start();
execute_t.Start();
wait(semaphore0);
}
private static void context_()
{
context = (IPluginExecutionContext)serviceProvider_.GetService(typeof(IPluginExecutionContext));
accounts = (Entity)context.InputParameters["Target"];
EntityReference accounts_reference = new EntityReference();
accounts_reference.LogicalName = accounts.LogicalName;
accounts_reference.Id = accounts.Id;
deactivate = new SetStateRequest();
deactivate.EntityMoniker = accounts_reference;
deactivate.State = new OptionSetValue((int)AccountState.Inactive);
deactivate.Status = new OptionSetValue(2);
signal(semaphore1);
}
private static void factory_()
{
factory = (IOrganizationServiceFactory)serviceProvider_.GetService(typeof(IOrganizationServiceFactory));
service = (IOrganizationService)factory.CreateOrganizationService(context.UserId);
signal(semaphore2);
}
private static void execute_()
{
wait(semaphore1);
wait(semaphore2);
setstate_response = (SetStateResponse)service.Execute(deactivate);
signal(semaphore0);
}
private static void wait(int semaphore)
{
while (semaphore == 0)
{
//do nothing
}
semaphore = semaphore - 1;
}
private static void signal(int semaphore)
{
semaphore = semaphore + 1;
}
}
}
i registerd it on create post syncronous mode in accounts entity .
this error come from then after for every sync plugins registered :
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The plug-in execution failed because no Sandbox Worker processes are currently available. Please try again.
System.ServiceModel.CommunicationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #5CD64A38Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147204723</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>The plug-in execution failed because no Sandbox Worker processes are currently available. Please try again.
System.ServiceModel.CommunicationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #5CD64A38</Message>
<Timestamp>2015-03-12T13:19:42.5150181Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText>
[PluginProfiler.Plugins: PluginProfiler.Plugins.ProfilerPlugin]
[dc99cb02-b6c8-e411-80eb-c4346bada6b4: Plugin_on_create_deact_rec.account_deactivate: Create of account (Profiler)]
</TraceText>
</OrganizationServiceFault>
can any one tell me what the hell happened to my instance of crm ..

Related

Azure IoT Edge Offline capabilities Example

I'm a little bit confused on how to use IoT Edge Offline mode. I though it was out-of-box!
The location of my IoT Hub is in West US. When I disconnect my Edge device from the network nothing happen. The datas is not saved or resend after reconnecting it online.
I got only one module that send data to the IoT Hub, I can see the datas flowing with Device Explorer Twin app and I saved the data in a database.
After disconnecting, wait 5 minutes and reconnecting, I don't see the datas that I was trying to send during offline mode in the database.
All messages while offline are missing (I'm sequencing the message with datetime stamp).
Did I missed a configuration?
Any idea why the offline mode doesn't work for me?
I'm using Iot Edge Runtime v1.0.6 and Windows Containers.
Here the source code of my testing module:
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Loader;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static int monitoringInterval { get; set; } = 60;// 60 seconds
static System.Timers.Timer testTimer;
static ModuleClient ioTHubModuleClient;
static void Main(string[] args)
{
Init().Wait();
StartTestTimer();
// Wait until the app unloads or is cancelled
var cts = new CancellationTokenSource();
AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel();
Console.CancelKeyPress += (sender, cpe) => cts.Cancel();
WhenCancelled(cts.Token).Wait();
}
/// <summary>
/// Handles cleanup operations when app is cancelled or unloads
/// </summary>
public static Task WhenCancelled(CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
/// <summary>
/// Initializes the ModuleClient and sets up the callback to receive
/// messages containing temperature information
/// </summary>
static async Task Init()
{
AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
ITransportSettings[] settings = { amqpSetting };
// Open a connection to the Edge runtime
ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await ioTHubModuleClient.OpenAsync();
Console.WriteLine("IoT Hub module client initialized.");
}
static void StartTestTimer()
{
Console.WriteLine("Start Monitoring Timer: " + monitoringInterval + " seconds");
// Set up a timer that triggers every minute.
testTimer = new System.Timers.Timer();
testTimer.Interval = monitoringInterval * 1000; // 60 seconds
testTimer.Elapsed += new System.Timers.ElapsedEventHandler(SendEvent);
testTimer.Start();
SendEvent(null, null);
}
async static void SendEvent(object sender, System.Timers.ElapsedEventArgs args)
{
DateTime today = DateTime.Now;
Console.WriteLine("[" + today + "] Send Data has started...");
try
{
//IoT device connection string
string connectionString = "HostName=xxxxxx.azure-devices.net;DeviceId=IOT-Device1;SharedAccessKey=ett8xxxxxxxxx";
// Connect to the IoT hub using the MQTT protocol
DeviceClient _DeviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Mqtt);
_DeviceClient.OperationTimeoutInMilliseconds = 10000;
Dictionary<string, Object> telemetryDataPoint = new Dictionary<string, Object>();
string dateTime = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
telemetryDataPoint.Add("DateTime", dateTime);
string messageString = JsonConvert.SerializeObject(telemetryDataPoint);
Message message = new Message(Encoding.ASCII.GetBytes(messageString));
// Send the telemetry message
Console.WriteLine("\n*> Sending message: {0}", messageString);
await _DeviceClient.SendEventAsync(message).ConfigureAwait(false);
Console.WriteLine("Message sent!");
}
catch (Exception e)
{
Console.WriteLine("Message not sent. Connection error to Iot Hub:" + e.Message);
}
}
}
Why is the code creating a moduleClient in Init(), but then attempting to send an a message directly to IoT Hub using a deviceClient in SendEvent()? This bypasses the edge runtime (specifically edgeHub) completely which is what facilitates offline store and forward.
Here is an example of the right way to do this: https://github.com/Azure/iotedge/blob/ad41fec507bb91a2e57a07cd32e287ada0ca08d8/edge-modules/SimulatedTemperatureSensor/src/Program.cs#L95

Azure IoT Edge module direct method responses shows as [object Object]

When invoking a direct method on a specific module I just receive the result [object Object] in the azure portal and I don't know what I'm doing wrong.
Note that when I did exactly the same using the azure IoT SDK for c# (without running the azure iot runtime), I properly received the JSON object and it was not just shown as [object Object].
Note that I'm developing this in c# and the docker containers (used for IoT edge runtime and it's modules) is running Linux as OS.
I have the following sample method that I've registered as a direct method.
In the iot edge runtime Init() function I do the following:
await ioTHubModuleClient.SetMethodHandlerAsync("Sample1", Sample1, null);
The sample method looks like:
private static Task<MethodResponse> Sample1(MethodRequest methodRequest, object userContext)
{
// Get data but don't do anything with it... Works fine!
var data = Encoding.UTF8.GetString(methodRequest.Data);
var methodResponse = new MethodResponse(Encoding.UTF8.GetBytes("{\"status\": \"ok\"}"), 200);
return Task.FromResult(methodResponse);
}
I can monitor this module in the debug mode by setting breakpoints in the Sample1 method. I can't find what I'm doing wrong? Why is the response returned from this Sample1 method just shown as [object Object] and why don't I see the JSON-object {"status": "ok"} as I did when not using the Azure IoT Edge runtime?
The callback result for the Direct Method is object Task< MethodResponse >.It does not serialize to Json string to show in the Azure Portal. But you can use the Service Client Sdk to get the callback response and then serialize to JSON string.
The latest Microsoft Azure IoT Hub SDK for C# supports Modules and IoT Edge. You can refer to this sample with using the SDK.
Update:
In the latest Azure IoT Hub SDK(Microsoft.Azure.Devices.Client 1.18), please use ModuleClinet instead of DeviceClient. You can refer to the following code in module.
namespace SampleModuleA
{
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
class Program
{
static int counter;
static void Main(string[] args)
{
Init().Wait();
// Wait until the app unloads or is cancelled
var cts = new CancellationTokenSource();
AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel();
Console.CancelKeyPress += (sender, cpe) => cts.Cancel();
WhenCancelled(cts.Token).Wait();
}
/// <summary>
/// Handles cleanup operations when app is cancelled or unloads
/// </summary>
public static Task WhenCancelled(CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
/// <summary>
/// Initializes the ModuleClient and sets up the callback to receive
/// messages containing temperature information
/// </summary>
static async Task Init()
{
MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_WebSocket_Only);
ITransportSettings[] settings = { mqttSetting };
// Open a connection to the Edge runtime
ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await ioTHubModuleClient.OpenAsync();
Console.WriteLine("[{0:HH:mm:ss ffff}]IoT Hub SampleModuleA client initialized.", DateTime.Now);
await ioTHubModuleClient.SetMethodHandlerAsync("DirectMethod1", DirectMethod1, ioTHubModuleClient);
// Register callback to be called when a message is received by the module
await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);
}
static async Task<MethodResponse> DirectMethod1(MethodRequest methodRequest, object moduleClient)
{
Console.WriteLine("Call DirectMethod1.");
MethodResponse resp = null;
//to do Something
return resp;
}
/// <summary>
/// This method is called whenever the module is sent a message from the EdgeHub.
/// It just pipe the messages without any change.
/// It prints all the incoming messages.
/// </summary>
static async Task<MessageResponse> PipeMessage(Message message, object userContext)
{
int counterValue = Interlocked.Increment(ref counter);
var moduleClient = userContext as ModuleClient;
if (moduleClient == null)
{
throw new InvalidOperationException("UserContext doesn't contain " + "expected values");
}
byte[] messageBytes = message.GetBytes();
string messageString = Encoding.UTF8.GetString(messageBytes);
Console.WriteLine($"Received message: {counterValue}, Body: [{messageString}]");
if (!string.IsNullOrEmpty(messageString))
{
var pipeMessage = new Message(messageBytes);
foreach (var prop in message.Properties)
{
pipeMessage.Properties.Add(prop.Key, prop.Value);
}
await moduleClient.SendEventAsync("output1", pipeMessage);
Console.WriteLine("Received message sent");
}
return MessageResponse.Completed;
}
}
}

What is the magic behind the scene of Java ee jms?

I've just started with Java ee 7, and here is something I couldnt get the idea of how it magically works.
I follow the example from the book Beginning Java EE 7 by Antonio Goncalves. I managed to compile and deploye the code of chapter 13 (about JMS) without any problem. Messages are sent and received as expected, but that make me confused.
The source code is composite of a consumer class, a producer class, a POJO and a MDB class.
here is the consumer:
public class OrderConsumer {
public static void main(String[] args) throws NamingException {
// Gets the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination topic = (Destination) jndiContext.lookup("jms/javaee7/Topic");
// Loops to receive the messages
System.out.println("\nInfinite loop. Waiting for a message...");
try (JMSContext jmsContext = connectionFactory.createContext()) {
while (true) {
OrderDTO order = jmsContext.createConsumer(topic).receiveBody(OrderDTO.class);
System.out.println("Order received: " + order);
}
}
}
}
the producer:
public class OrderProducer {
public static void main(String[] args) throws NamingException {
if (args.length != 1) {
System.out.println("usage : enter an amount");
System.exit(0);
}
System.out.println("Sending message with amount = " + args[0]);
// Creates an orderDto with a total amount parameter
Float totalAmount = Float.valueOf(args[0]);
OrderDTO order = new OrderDTO(1234l, new Date(), "Serge Gainsbourg", totalAmount);
// Gets the JNDI context
Context jndiContext = new InitialContext();
// Looks up the administered objects
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee7/ConnectionFactory");
Destination topic = (Destination) jndiContext.lookup("jms/javaee7/Topic");
try (JMSContext jmsContext = connectionFactory.createContext()) {
// Sends an object message to the topic
jmsContext.createProducer().setProperty("orderAmount", totalAmount).send(topic, order);
System.out.println("\nOrder sent : " + order.toString());
}
}
}
the MDB :
#MessageDriven(mappedName = "jms/javaee7/Topic", activationConfig = {
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "orderAmount > 1000")
})
public class ExpensiveOrderMDB implements MessageListener {
public void onMessage(Message message) {
try {
OrderDTO order = message.getBody(OrderDTO.class);
System.out.println("Expensive order received: " + order.toString());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
Content of msg encapsulated in a POJO object which implements Serializable interface
ExpensiveOrderMDB and the POJO is packaged in a .jar file and deploy in glassfish server running locally. Connection and desitination resouces are created by asadmin.
Question is: How can the consumer and producer know that the connection and destination are available on local glassfish server for it to make a connection and send/receive msg? (The lines that create connection and destination say nothing about local glassfish server)
Probably there is a jndi.properties file in which the connection to the glassfish is defined

Access Current NHibernate Session in Castle Windsor IOC Container

I am trying to access my current nhibernate session using IOC from within a running Quartz.net Job and every time it comes back as null stating the following:
'NHibernateSession.Current' threw an exception of type 'SharpArch.Domain.PreconditionException' NHibernate.ISession SharpArch.Domain.PreconditionException}. An ISessionStorage has not been configured
Here is my current code setup. I cannot figure out for the life of me how to setup my IOC so that the NHibernate ISession within my IScheduledMessageQueries query is set correctly. The Quartz triggers are working correctly, I just cannot access the ISession to call my queries from within the Job. Any help and/or advice?
Global.cs Code:
protected virtual void InitializeServiceLocator()
{
_container = new WindsorContainer(new XmlInterpreter()).Install(new WebWindsorInstaller());
StartQuartzScheduler();
ComponentRegistrar.AddComponentsTo(_container);
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(_container));
DependencyResolver.SetResolver(new WindsorDependencyResolver(_container));
var activator = new WebApiControllerFactory(_container);
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), activator);
}
private static void StartQuartzScheduler()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IJobFactory jobFactory = new WindsorJobFactory(_container);
var scheduler = schedulerFactory.GetScheduler();
scheduler.JobFactory = jobFactory;
scheduler.Start();
var sendScheduledMessageJob = new JobDetailImpl("sendScheduledMessageJob", typeof(SendScheduledMessageJob));
var trigger = new CalendarIntervalTriggerImpl
{
StartTimeUtc = DateTime.UtcNow.Subtract(new TimeSpan(1)),
Name = "Daily Trigger",
RepeatIntervalUnit = IntervalUnit.Second,
RepeatInterval = 1
};
scheduler.ScheduleJob(sendScheduledMessageJob, trigger);
}
public class SendScheduledMessageJob : IJob
{
private readonly IScheduledMessageQueries _scheduledMessageQueries;
public SendScheduledMessageJob(IScheduledMessageQueries scheduledMessageQueries)
{
_scheduledMessageQueries = scheduledMessageQueries;
}
public void Execute(IJobExecutionContext context)
{
var unsentScheduledMessages =
_scheduledMessageQueries.GetAllUnsentScheduledMessages(DateTime.Now);
}
}

WCF REST Service: InstanceContextMode.PerCall not working

I have implemented a REST service for WCF. The service offers one function that can be called by many clients and this function takes more than 1 minute to complete. So what I wanted is that for each client, a new object is used, so that many clients can be handled at a time.
My interface looks like this:
[ServiceContract]
public interface ISimulatorControlServices
{
[WebGet]
[OperationContract]
string DoSomething(string xml);
}
And the (test) implementation of it:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall]
public class SimulatorControlService : SimulatorServiceInterfaces.ISimulatorControlServices
{
public SimulatorControlService()
{
Console.WriteLine("SimulatorControlService started.");
}
public string DoSomething(string xml)
{
System.Threading.Thread.Sleep(2000);
return "blub";
}
}
The problem now is: if I use a client that creates 10 (or whatever number) threads, each of it calling the service, they dont run concurrently. This means, the calls are being handled one after each other. Does anybody have an idea why this happens?
Added: client-side code
Spawning threads:
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(new ThreadStart(DoSomethingTest));
thread.Start();
}
Method:
private static void DoSomethingTest()
{
try
{
using (ChannelFactory<ISimulatorControlServices> cf = new ChannelFactory<ISimulatorControlServices>(new WebHttpBinding(), "http://localhost:9002/bla/SimulatorControlService"))
{
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
ISimulatorControlServices channel = cf.CreateChannel();
string s;
int threadID = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Thread {0} calling DoSomething()...", threadID);
string testXml = "test";
s = channel.StartPressureMapping(testXml);
Console.WriteLine("Thread {0} finished with reponse: {1}", threadID, s);
}
}
catch (CommunicationException cex)
{
Console.WriteLine("A communication exception occurred: {0}", cex.Message);
}
}
Thanks in advance!
Since the service is controlled by a GUI, the "UseSynchronizationContext" attribute was needed to solve the problem:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode=ConcurrencyMode.Multiple, UseSynchronizationContext=false)]